OSDN Git Service

2009-07-28 Sergey Rybin <rybin@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 * Predefined Rules::
494
495 Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 * Converting Ada Files to html with gnathtml::
505
506 @ifclear vms
507 Code Coverage and Profiling
508
509 * Code Coverage of Ada Programs using gcov::
510 * Profiling an Ada Program using gprof::
511 @end ifclear
512
513 Running and Debugging Ada Programs
514
515 * The GNAT Debugger GDB::
516 * Running GDB::
517 * Introduction to GDB Commands::
518 * Using Ada Expressions::
519 * Calling User-Defined Subprograms::
520 * Using the Next Command in a Function::
521 * Ada Exceptions::
522 * Ada Tasks::
523 * Debugging Generic Units::
524 * GNAT Abnormal Termination or Failure to Terminate::
525 * Naming Conventions for GNAT Source Files::
526 * Getting Internal Debugging Information::
527 * Stack Traceback::
528
529 @ifset vms
530 * LSE::
531 @end ifset
532
533 @ifset vms
534 Compatibility with HP Ada
535
536 * Ada Language Compatibility::
537 * Differences in the Definition of Package System::
538 * Language-Related Features::
539 * The Package STANDARD::
540 * The Package SYSTEM::
541 * Tasking and Task-Related Features::
542 * Pragmas and Pragma-Related Features::
543 * Library of Predefined Units::
544 * Bindings::
545 * Main Program Definition::
546 * Implementation-Defined Attributes::
547 * Compiler and Run-Time Interfacing::
548 * Program Compilation and Library Management::
549 * Input-Output::
550 * Implementation Limits::
551 * Tools and Utilities::
552
553 Language-Related Features
554
555 * Integer Types and Representations::
556 * Floating-Point Types and Representations::
557 * Pragmas Float_Representation and Long_Float::
558 * Fixed-Point Types and Representations::
559 * Record and Array Component Alignment::
560 * Address Clauses::
561 * Other Representation Clauses::
562
563 Tasking and Task-Related Features
564
565 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
566 * Assigning Task IDs::
567 * Task IDs and Delays::
568 * Task-Related Pragmas::
569 * Scheduling and Task Priority::
570 * The Task Stack::
571 * External Interrupts::
572
573 Pragmas and Pragma-Related Features
574
575 * Restrictions on the Pragma INLINE::
576 * Restrictions on the Pragma INTERFACE::
577 * Restrictions on the Pragma SYSTEM_NAME::
578
579 Library of Predefined Units
580
581 * Changes to DECLIB::
582
583 Bindings
584
585 * Shared Libraries and Options Files::
586 * Interfaces to C::
587 @end ifset
588
589 Platform-Specific Information for the Run-Time Libraries
590
591 * Summary of Run-Time Configurations::
592 * Specifying a Run-Time Library::
593 * Choosing the Scheduling Policy::
594 * Solaris-Specific Considerations::
595 * Linux-Specific Considerations::
596 * AIX-Specific Considerations::
597 * Irix-Specific Considerations::
598
599 Example of Binder Output File
600
601 Elaboration Order Handling in GNAT
602
603 * Elaboration Code::
604 * Checking the Elaboration Order::
605 * Controlling the Elaboration Order::
606 * Controlling Elaboration in GNAT - Internal Calls::
607 * Controlling Elaboration in GNAT - External Calls::
608 * Default Behavior in GNAT - Ensuring Safety::
609 * Treatment of Pragma Elaborate::
610 * Elaboration Issues for Library Tasks::
611 * Mixing Elaboration Models::
612 * What to Do If the Default Elaboration Behavior Fails::
613 * Elaboration for Access-to-Subprogram Values::
614 * Summary of Procedures for Elaboration Control::
615 * Other Elaboration Order Considerations::
616
617 Conditional Compilation
618 * Use of Boolean Constants::
619 * Debugging - A Special Case::
620 * Conditionalizing Declarations::
621 * Use of Alternative Implementations::
622 * Preprocessing::
623
624 Inline Assembler
625
626 * Basic Assembler Syntax::
627 * A Simple Example of Inline Assembler::
628 * Output Variables in Inline Assembler::
629 * Input Variables in Inline Assembler::
630 * Inlining Inline Assembler Code::
631 * Other Asm Functionality::
632
633 Compatibility and Porting Guide
634
635 * Compatibility with Ada 83::
636 * Compatibility between Ada 95 and Ada 2005::
637 * Implementation-dependent characteristics::
638 @ifclear vms
639 @c This brief section is only in the non-VMS version
640 @c The complete chapter on HP Ada issues is in the VMS version
641 * Compatibility with HP Ada 83::
642 @end ifclear
643 * Compatibility with Other Ada Systems::
644 * Representation Clauses::
645 @ifset vms
646 * Transitioning to 64-Bit GNAT for OpenVMS::
647 @end ifset
648
649 @ifset unw
650 Microsoft Windows Topics
651
652 * Using GNAT on Windows::
653 * CONSOLE and WINDOWS subsystems::
654 * Temporary Files::
655 * Mixed-Language Programming on Windows::
656 * Windows Calling Conventions::
657 * Introduction to Dynamic Link Libraries (DLLs)::
658 * Using DLLs with GNAT::
659 * Building DLLs with GNAT::
660 * GNAT and Windows Resources::
661 * Debugging a DLL::
662 * Setting Stack Size from gnatlink::
663 * Setting Heap Size from gnatlink::
664 @end ifset
665
666 * Index::
667 @end menu
668 @end ifnottex
669
670 @node About This Guide
671 @unnumbered About This Guide
672
673 @noindent
674 @ifset vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development toolset for the full Ada
677 programming language, implemented on OpenVMS for HP's Alpha and
678 Integrity server (I64) platforms.
679 @end ifset
680 @ifclear vms
681 This guide describes the use of @value{EDITION},
682 a compiler and software development
683 toolset for the full Ada programming language.
684 @end ifclear
685 It documents the features of the compiler and tools, and explains
686 how to use them to build Ada applications.
687
688 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
689 Ada 83 compatibility mode.
690 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
691 but you can override with a compiler switch
692 (@pxref{Compiling Different Versions of Ada})
693 to explicitly specify the language version.
694 Throughout this manual, references to ``Ada'' without a year suffix
695 apply to both the Ada 95 and Ada 2005 versions of the language.
696
697
698 @ifclear FSFEDITION
699 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
700 ``GNAT'' in the remainder of this document.
701 @end ifclear
702
703
704
705
706 @menu
707 * What This Guide Contains::
708 * What You Should Know before Reading This Guide::
709 * Related Information::
710 * Conventions::
711 @end menu
712
713 @node What This Guide Contains
714 @unnumberedsec What This Guide Contains
715
716 @noindent
717 This guide contains the following chapters:
718 @itemize @bullet
719
720 @item
721 @ref{Getting Started with GNAT}, describes how to get started compiling
722 and running Ada programs with the GNAT Ada programming environment.
723 @item
724 @ref{The GNAT Compilation Model}, describes the compilation model used
725 by GNAT.
726
727 @item
728 @ref{Compiling Using gcc}, describes how to compile
729 Ada programs with @command{gcc}, the Ada compiler.
730
731 @item
732 @ref{Binding Using gnatbind}, describes how to
733 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 utility.
735
736 @item
737 @ref{Linking Using gnatlink},
738 describes @command{gnatlink}, a
739 program that provides for linking using the GNAT run-time library to
740 construct a program. @command{gnatlink} can also incorporate foreign language
741 object units into the executable.
742
743 @item
744 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
745 utility that automatically determines the set of sources
746 needed by an Ada compilation unit, and executes the necessary compilations
747 binding and link.
748
749 @item
750 @ref{Improving Performance}, shows various techniques for making your
751 Ada program run faster or take less space.
752 It discusses the effect of the compiler's optimization switch and
753 also describes the @command{gnatelim} tool and unused subprogram/data
754 elimination.
755
756 @item
757 @ref{Renaming Files Using gnatchop}, describes
758 @code{gnatchop}, a utility that allows you to preprocess a file that
759 contains Ada source code, and split it into one or more new files, one
760 for each compilation unit.
761
762 @item
763 @ref{Configuration Pragmas}, describes the configuration pragmas
764 handled by GNAT.
765
766 @item
767 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
768 shows how to override the default GNAT file naming conventions,
769 either for an individual unit or globally.
770
771 @item
772 @ref{GNAT Project Manager}, describes how to use project files
773 to organize large projects.
774
775 @item
776 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
777 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
778 way to navigate through sources.
779
780 @item
781 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
782 version of an Ada source file with control over casing, indentation,
783 comment placement, and other elements of program presentation style.
784
785 @item
786 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
787 metrics for an Ada source file, such as the number of types and subprograms,
788 and assorted complexity measures.
789
790 @item
791 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
792 file name krunching utility, used to handle shortened
793 file names on operating systems with a limit on the length of names.
794
795 @item
796 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
797 preprocessor utility that allows a single source file to be used to
798 generate multiple or parameterized source files by means of macro
799 substitution.
800
801 @ifset vms
802 @item
803 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
804 a tool for rebuilding the GNAT run time with user-supplied
805 configuration pragmas.
806 @end ifset
807
808 @item
809 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
810 utility that displays information about compiled units, including dependences
811 on the corresponding sources files, and consistency of compilations.
812
813 @item
814 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
815 to delete files that are produced by the compiler, binder and linker.
816
817 @ifclear vms
818 @item
819 @ref{GNAT and Libraries}, describes the process of creating and using
820 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 library.
822
823 @item
824 @ref{Using the GNU make Utility}, describes some techniques for using
825 the GNAT toolset in Makefiles.
826 @end ifclear
827
828 @item
829 @ref{Memory Management Issues}, describes some useful predefined storage pools
830 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 memory references.
832 @ifclear vms
833 It also describes @command{gnatmem}, a utility that monitors dynamic
834 allocation and deallocation and helps detect ``memory leaks''.
835 @end ifclear
836
837 @item
838 @ref{Stack Related Facilities}, describes some useful tools associated with
839 stack checking and analysis.
840
841 @item
842 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
843 a utility that checks Ada code against a set of rules.
844
845 @item
846 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
847 a utility that generates empty but compilable bodies for library units.
848
849 @item
850 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
851 generate automatically Ada bindings from C and C++ headers.
852
853 @item
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
856
857 @ifclear vms
858 @item
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
861 @end ifclear
862
863 @item
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
865 Ada programs.
866
867 @ifset vms
868 @item
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
873 @cindex DEC Ada
874 and for
875 historical compatibility reasons, the relevant libraries still use the
876 DEC prefix.
877 @end ifset
878
879 @item
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
884
885 @item
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
888
889 @item
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
892
893 @item
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
896
897 @item
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
899 in an Ada program.
900
901 @item
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
905
906 @ifset unw
907 @item
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
910 @end ifset
911 @end itemize
912
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
917
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
920 @noindent
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
923 1995.
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
926 and Amendment 1).
927 Both reference manuals are included in the GNAT documentation
928 package.
929
930 @node Related Information
931 @unnumberedsec Related Information
932
933 @noindent
934 For further information about related tools, refer to the following
935 documents:
936
937 @itemize @bullet
938 @item
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
942
943 @ifset unw
944 @item
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
947
948 @item
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
951 @end ifset
952
953 @item
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
956
957 @item
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
960
961 @item
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
963 @ifset vms
964 in the GNU:[DOCS] directory,
965 @end ifset
966 for all details on the use of the GNU source-level debugger.
967
968 @item
969 @xref{Top,, The extensible self-documenting text editor, emacs,
970 GNU Emacs Manual},
971 @ifset vms
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
973 @end ifset
974 for full information on the extensible editor and programming
975 environment Emacs.
976
977 @end itemize
978
979 @c **************
980 @node Conventions
981 @unnumberedsec Conventions
982 @cindex Conventions
983 @cindex Typographical conventions
984
985 @noindent
986 Following are examples of the typographical and graphic conventions used
987 in this guide:
988
989 @itemize @bullet
990 @item
991 @code{Functions}, @command{utility program names}, @code{standard names},
992 and @code{classes}.
993
994 @item
995 @option{Option flags}
996
997 @item
998 @file{File names}, @samp{button names}, and @samp{field names}.
999
1000 @item
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1002 variables}.
1003
1004 @item
1005 @emph{Emphasis}.
1006
1007 @item
1008 @r{[}optional information or parameters@r{]}
1009
1010 @item
1011 Examples are described by text
1012 @smallexample
1013 and then shown this way.
1014 @end smallexample
1015 @end itemize
1016
1017 @noindent
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1024
1025 @ifset unw
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1030 @end ifset
1031
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1035
1036 @noindent
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1039 @ifset unw
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1050 @end ifset
1051
1052 @menu
1053 * Running GNAT::
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1057 @ifset vms
1058 * Editing with Emacs::
1059 @end ifset
1060 @ifclear vms
1061 * Introduction to GPS::
1062 @end ifclear
1063 @end menu
1064
1065 @node Running GNAT
1066 @section Running GNAT
1067
1068 @noindent
1069 Three steps are needed to create an executable file from an Ada source
1070 file:
1071
1072 @enumerate
1073 @item
1074 The source file(s) must be compiled.
1075 @item
1076 The file(s) must be bound using the GNAT binder.
1077 @item
1078 All appropriate object files must be linked to produce an executable.
1079 @end enumerate
1080
1081 @noindent
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1085
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1088
1089 @noindent
1090 Any text editor may be used to prepare an Ada program.
1091 (If @code{Emacs} is
1092 used, the optional Ada mode may be helpful in laying out the program.)
1093 The
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1097
1098 @smallexample @c ada
1099 @cartouche
1100 with Ada.Text_IO; use Ada.Text_IO;
1101 procedure Hello is
1102 begin
1103    Put_Line ("Hello WORLD!");
1104 end Hello;
1105 @end cartouche
1106 @end smallexample
1107
1108 @noindent
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1111 that each file
1112 contain a single compilation unit whose file name is the
1113 unit name,
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1124
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1127
1128 @smallexample
1129 $ gcc -c hello.adb
1130 @end smallexample
1131
1132 @noindent
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1138
1139 @ifclear vms
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1144 @end ifclear
1145
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1159
1160 @smallexample
1161 $ gnatbind hello
1162 $ gnatlink hello
1163 @end smallexample
1164
1165 @noindent
1166 A simpler method of carrying out these steps is to use
1167 @command{gnatmake},
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1174
1175 @smallexample
1176 $ gnatmake hello.adb
1177 @end smallexample
1178
1179 @noindent
1180 The result is an executable program called @file{hello}, which can be
1181 run by entering:
1182
1183 @smallexample
1184 $ ^hello^RUN HELLO^
1185 @end smallexample
1186
1187 @noindent
1188 assuming that the current directory is on the search path
1189 for executable programs.
1190
1191 @noindent
1192 and, if all has gone well, you will see
1193
1194 @smallexample
1195 Hello WORLD!
1196 @end smallexample
1197
1198 @noindent
1199 appear in response to this command.
1200
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1204
1205 @noindent
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1208
1209 @smallexample @c ada
1210 @cartouche
1211 @group
1212 package Greetings is
1213    procedure Hello;
1214    procedure Goodbye;
1215 end Greetings;
1216
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1219    procedure Hello is
1220    begin
1221       Put_Line ("Hello WORLD!");
1222    end Hello;
1223
1224    procedure Goodbye is
1225    begin
1226       Put_Line ("Goodbye WORLD!");
1227    end Goodbye;
1228 end Greetings;
1229 @end group
1230
1231 @group
1232 with Greetings;
1233 procedure Gmain is
1234 begin
1235    Greetings.Hello;
1236    Greetings.Goodbye;
1237 end Gmain;
1238 @end group
1239 @end cartouche
1240 @end smallexample
1241
1242 @noindent
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1245
1246 @table @file
1247 @item greetings.ads
1248 spec of package @code{Greetings}
1249
1250 @item greetings.adb
1251 body of package @code{Greetings}
1252
1253 @item gmain.adb
1254 body of main program
1255 @end table
1256
1257 @noindent
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1261
1262 @smallexample
1263 $ gcc -c gmain.adb
1264 $ gcc -c greetings.adb
1265 $ gnatbind gmain
1266 $ gnatlink gmain
1267 @end smallexample
1268
1269 @noindent
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1277
1278 @smallexample
1279 $ gcc -c greetings.ads -gnatc
1280 @end smallexample
1281
1282 @noindent
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1288
1289 @smallexample
1290 $ gnatmake gmain.adb
1291 @end smallexample
1292
1293 @noindent
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1295 more detail.
1296
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1300
1301 @noindent
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1311
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1321
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1324
1325 @smallexample
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1328 @end smallexample
1329
1330 @noindent
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1339
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1349
1350 @ifset vms
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1353 @cindex Emacs
1354
1355 @noindent
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1358
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1363
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1367
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1372 prompt.
1373
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1377 @end ifset
1378
1379 @ifclear vms
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1384 @noindent
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs.  This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1392
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1396 for a program.
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1401 startup menu).
1402
1403 @menu
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1406 @end menu
1407
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1410 @noindent
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1419
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1422 programs.
1423
1424 @enumerate
1425 @item @emph{Creating a project}
1426
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1429 radio buttons:
1430
1431 @itemize @bullet
1432 @item
1433 @code{Start with default project in directory}
1434
1435 @item
1436 @code{Create new project with wizard}
1437
1438 @item
1439 @code{Open existing project}
1440 @end itemize
1441
1442 @noindent
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear.  In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1465
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1470
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}.  This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1475
1476 @item @emph{Creating and saving the source file}
1477
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1480
1481 @itemize @bullet
1482 @item
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1485
1486 @item
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1490 @end itemize
1491
1492 @noindent
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1497
1498 @smallexample @c ada
1499 @group
1500 with Ada.Text_IO; use Ada.Text_IO;
1501 procedure Hello is
1502 begin
1503   Put_Line("Hello from GPS!");
1504 end Hello;
1505 @end group
1506 @end smallexample
1507
1508 @noindent
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1510 @file{hello.adb}.
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1513
1514 @item @emph{Updating the project file}
1515
1516 You need to add the new source file to the project.
1517 To do this, select
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1520 @code{Add} button.
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1523 Click @code{OK}.
1524
1525 @item @emph{Building and running the program}
1526
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1533 message.
1534
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1539
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1545 @end enumerate
1546
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1549 @noindent
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1552
1553 @enumerate
1554 @item @emph{Opening a project}
1555
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1558 earlier example.
1559
1560 @item @emph{Creating a source file}
1561
1562 Select @code{File}, then @code{New}, and type in the following program:
1563
1564 @smallexample @c ada
1565 @group
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568    Line : String (1..80);
1569    N    : Natural;
1570 begin
1571    Put_Line("Type a line of text at each prompt; an empty line to exit");
1572    loop
1573       Put(": ");
1574       Get_Line (Line, N);
1575       Put_Line (Line (1..N) );
1576       exit when N=0;
1577    end loop;
1578 end Example;
1579 @end group
1580 @end smallexample
1581
1582 @noindent
1583 Select @code{File}, then @code{Save as}, and enter the file name
1584 @file{example.adb}.
1585
1586 @item @emph{Updating the project file}
1587
1588 Add @code{Example} as a new main unit for the project:
1589 @enumerate a
1590 @item
1591 Select @code{Project}, then @code{Edit Project Properties}.
1592
1593 @item
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1596 click @code{Open}.
1597 You will see the file name appear in the list of main units
1598
1599 @item
1600 Click @code{OK}
1601 @end enumerate
1602
1603 @item @emph{Building/running the executable}
1604
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1607
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1611
1612 @item @emph{Debugging the program}
1613
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1616 a new project.
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1619
1620 @enumerate a
1621 @item @emph{Initializing}
1622
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1624
1625 @item @emph{Setting a breakpoint}
1626
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1633
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1636
1637 @item @emph{Starting program execution}
1638
1639 Select @code{Debug}, then @code{Run}.  When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1645
1646 @item @emph{Examining a variable}
1647
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1653
1654 @item @emph{Assigning a new value to a variable}
1655
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1659 @code{OK}.
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1664
1665 @item @emph{Single stepping}
1666
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1673
1674 @item @emph{Removing a breakpoint}
1675
1676 Toggle the breakpoint icon at line 10.
1677
1678 @item @emph{Resuming execution from a breakpoint}
1679
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1686 @end enumerate
1687 @end enumerate
1688 @end ifclear
1689
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1694
1695 @menu
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1706 @ifclear vms
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1709 @end ifclear
1710 * Comparison between GNAT and Conventional Ada Library Models::
1711 @ifset vms
1712 * Placement of temporary files::
1713 @end ifset
1714 @end menu
1715
1716 @noindent
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1727
1728 @node Source Representation
1729 @section Source Representation
1730 @cindex Latin-1
1731
1732 @noindent
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1739
1740 @table @code
1741 @item VT
1742 @findex VT
1743 Vertical tab, @code{16#0B#}
1744
1745 @item HT
1746 @findex HT
1747 Horizontal tab, @code{16#09#}
1748
1749 @item CR
1750 @findex CR
1751 Carriage return, @code{16#0D#}
1752
1753 @item LF
1754 @findex LF
1755 Line feed, @code{16#0A#}
1756
1757 @item FF
1758 @findex FF
1759 Form feed, @code{16#0C#}
1760 @end table
1761
1762 @noindent
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1768
1769 @cindex End of source file
1770 @cindex Source file, end
1771 @findex SUB
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1777
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1784
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1787
1788 @noindent
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1792 @menu
1793 * Latin-1::
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1796 @end menu
1797
1798 @node Latin-1
1799 @subsection Latin-1
1800 @cindex Latin-1
1801
1802 @noindent
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1809
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1817
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1820
1821 @noindent
1822 GNAT also supports several other 8-bit coding schemes:
1823
1824 @table @asis
1825 @item ISO 8859-2 (Latin-2)
1826 @cindex Latin-2
1827 @cindex ISO 8859-2
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-3 (Latin-3)
1832 @cindex Latin-3
1833 @cindex ISO 8859-3
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-4 (Latin-4)
1838 @cindex Latin-4
1839 @cindex ISO 8859-4
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-5 (Cyrillic)
1844 @cindex ISO 8859-5
1845 @cindex Cyrillic
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1848
1849 @item ISO 8859-15 (Latin-9)
1850 @cindex ISO 8859-15
1851 @cindex Latin-9
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1854
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1862
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1869
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1876
1877 @item No Upper-Half
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1880 @end table
1881
1882 @noindent
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1887
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1890
1891 @noindent
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1895
1896 @table @asis
1897
1898 @item Hex Coding
1899 In this encoding, a wide character is represented by the following five
1900 character sequence:
1901
1902 @smallexample
1903 ESC a b c d
1904 @end smallexample
1905
1906 @noindent
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1910 @code{16#A345#}.
1911 This scheme is compatible with use of the full Wide_Character set.
1912
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1920 external coding.
1921
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1925 @code{16#ab#} and
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1931
1932 @item EUC Coding
1933 @cindex EUC Coding
1934 A wide character is represented by a two-character sequence
1935 @code{16#ab#} and
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1940
1941 @item UTF-8 Coding
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1946 @smallexample
1947 @iftex
1948 @leftskip=.7cm
1949 @end iftex
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1953
1954 @end smallexample
1955
1956 @noindent
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1966 character sequence:
1967
1968 @smallexample
1969 [ " a b c d " ]
1970 @end smallexample
1971
1972 @noindent
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1979
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1983
1984 @end table
1985
1986 @noindent
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1990
1991 @node File Naming Rules
1992 @section File Naming Rules
1993
1994 @noindent
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
1999
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2002 @ifset vms
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2004 @end ifset
2005 @ifclear vms
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2007 @end ifclear
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2013 @ifset vms
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2015 @end ifset
2016 @ifclear vms
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2018 @end ifclear
2019 respectively.
2020
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2024
2025 @table @file
2026 @item main.ads
2027 Main (spec)
2028 @item main.adb
2029 Main (body)
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2034 @item func-spec.ads
2035 Func.Spec (child package spec)
2036 @item func-spec.adb
2037 Func.Spec (child package body)
2038 @item main-sub.adb
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2042 @end table
2043
2044 @noindent
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2052
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2061
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2069
2070 @node Using Other File Names
2071 @section Using Other File Names
2072 @cindex File names
2073
2074 @noindent
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2079 the files it needs.
2080
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2087
2088 @smallexample @c ada
2089 @cartouche
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091   Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093   Body_File_Name => "myutilst.ada");
2094 @end cartouche
2095 @end smallexample
2096
2097 @noindent
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2103
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2111
2112 @ifclear vms
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2119
2120 @smallexample
2121 $ gcc -c -x ada peculiar_file_name.sim
2122 @end smallexample
2123 @end ifclear
2124
2125 @noindent
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2130 be omitted.
2131
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2135 @cindex File names
2136
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2142
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2148
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151    Spec_File_Name  => FILE_NAME_PATTERN
2152  @r{[},Casing          => CASING_SPEC@r{]}
2153  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156    Body_File_Name  => FILE_NAME_PATTERN
2157  @r{[},Casing          => CASING_SPEC@r{]}
2158  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2159
2160 pragma Source_File_Name (
2161    Subunit_File_Name  => FILE_NAME_PATTERN
2162  @r{[},Casing             => CASING_SPEC@r{]}
2163  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2164
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2167 @end smallexample
2168
2169 @noindent
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2178
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2182 file name.
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2187
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2193
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2200
2201 The file name translation works in the following steps:
2202
2203 @itemize @bullet
2204
2205 @item
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2208
2209 @item
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2214
2215 @item
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2219
2220 @end itemize
2221
2222 @noindent
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2227 two pragmas appear:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231   (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233   (Body_File_Name => "*.2.ada");
2234 @end smallexample
2235
2236 @noindent
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2239
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2245 @end smallexample
2246
2247 @noindent
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2256
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259   (Spec_File_Name => "*_.ADA",
2260    Dot_Replacement => "__",
2261    Casing = Uppercase);
2262 pragma Source_File_Name
2263   (Body_File_Name => "*.ADA",
2264    Dot_Replacement => "__",
2265    Casing = Uppercase);
2266 pragma Source_File_Name
2267   (Subunit_File_Name => "*.SEP",
2268    Dot_Replacement => "__",
2269    Casing = Uppercase);
2270 @end smallexample
2271
2272 @node Generating Object Files
2273 @section Generating Object Files
2274
2275 @noindent
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2280
2281 @itemize @bullet
2282 @item
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2285
2286 @item
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2291
2292 @item
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2296
2297 @item
2298 @cindex Subunits
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2301 subunits.
2302
2303 @item
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2307
2308 @item
2309 @cindex Generics
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2315 @end itemize
2316
2317 @noindent
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2321 @file{.o} as usual.
2322
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2329
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2334
2335 @node Source Dependencies
2336 @section Source Dependencies
2337
2338 @noindent
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2343 recompiled.
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2346
2347 @itemize @bullet
2348 @item
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2354
2355 @item
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2358 unit.
2359
2360 @item
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2364
2365 @item
2366 @findex Inline
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2374
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates  inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2380
2381 When using a gcc-based back end (in practice this means using any version
2382 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2383 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2384 Historically front end inlining was more extensive than the gcc back end
2385 inlining, but that is no longer the case.
2386
2387 @item
2388 If an object file @file{O} depends on the proper body of a subunit through
2389 inlining or instantiation, it depends on the parent unit of the subunit.
2390 This means that any modification of the parent unit or one of its subunits
2391 affects the compilation of @file{O}.
2392
2393 @item
2394 The object file for a parent unit depends on all its subunit body files.
2395
2396 @item
2397 The previous two rules meant that for purposes of computing dependencies and
2398 recompilation, a body and all its subunits are treated as an indivisible whole.
2399
2400 @noindent
2401 These rules are applied transitively: if unit @code{A} @code{with}'s
2402 unit @code{B}, whose elaboration calls an inlined procedure in package
2403 @code{C}, the object file for unit @code{A} will depend on the body of
2404 @code{C}, in file @file{c.adb}.
2405
2406 The set of dependent files described by these rules includes all the
2407 files on which the unit is semantically dependent, as dictated by the
2408 Ada language standard. However, it is a superset of what the
2409 standard describes, because it includes generic, inline, and subunit
2410 dependencies.
2411
2412 An object file must be recreated by recompiling the corresponding source
2413 file if any of the source files on which it depends are modified. For
2414 example, if the @code{make} utility is used to control compilation,
2415 the rule for an Ada object file must mention all the source files on
2416 which the object file depends, according to the above definition.
2417 The determination of the necessary
2418 recompilations is done automatically when one uses @command{gnatmake}.
2419 @end itemize
2420
2421 @node The Ada Library Information Files
2422 @section The Ada Library Information Files
2423 @cindex Ada Library Information files
2424 @cindex @file{ALI} files
2425
2426 @noindent
2427 Each compilation actually generates two output files. The first of these
2428 is the normal object file that has a @file{.o} extension. The second is a
2429 text file containing full dependency information. It has the same
2430 name as the source file, but an @file{.ali} extension.
2431 This file is known as the Ada Library Information (@file{ALI}) file.
2432 The following information is contained in the @file{ALI} file.
2433
2434 @itemize @bullet
2435 @item
2436 Version information (indicates which version of GNAT was used to compile
2437 the unit(s) in question)
2438
2439 @item
2440 Main program information (including priority and time slice settings,
2441 as well as the wide character encoding used during compilation).
2442
2443 @item
2444 List of arguments used in the @command{gcc} command for the compilation
2445
2446 @item
2447 Attributes of the unit, including configuration pragmas used, an indication
2448 of whether the compilation was successful, exception model used etc.
2449
2450 @item
2451 A list of relevant restrictions applying to the unit (used for consistency)
2452 checking.
2453
2454 @item
2455 Categorization information (e.g.@: use of pragma @code{Pure}).
2456
2457 @item
2458 Information on all @code{with}'ed units, including presence of
2459 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460
2461 @item
2462 Information from any @code{Linker_Options} pragmas used in the unit
2463
2464 @item
2465 Information on the use of @code{Body_Version} or @code{Version}
2466 attributes in the unit.
2467
2468 @item
2469 Dependency information. This is a list of files, together with
2470 time stamp and checksum information. These are files on which
2471 the unit depends in the sense that recompilation is required
2472 if any of these units are modified.
2473
2474 @item
2475 Cross-reference data. Contains information on all entities referenced
2476 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2477 provide cross-reference information.
2478
2479 @end itemize
2480
2481 @noindent
2482 For a full detailed description of the format of the @file{ALI} file,
2483 see the source of the body of unit @code{Lib.Writ}, contained in file
2484 @file{lib-writ.adb} in the GNAT compiler sources.
2485
2486 @node Binding an Ada Program
2487 @section Binding an Ada Program
2488
2489 @noindent
2490 When using languages such as C and C++, once the source files have been
2491 compiled the only remaining step in building an executable program
2492 is linking the object modules together. This means that it is possible to
2493 link an inconsistent version of a program, in which two units have
2494 included different versions of the same header.
2495
2496 The rules of Ada do not permit such an inconsistent program to be built.
2497 For example, if two clients have different versions of the same package,
2498 it is illegal to build a program containing these two clients.
2499 These rules are enforced by the GNAT binder, which also determines an
2500 elaboration order consistent with the Ada rules.
2501
2502 The GNAT binder is run after all the object files for a program have
2503 been created. It is given the name of the main program unit, and from
2504 this it determines the set of units required by the program, by reading the
2505 corresponding ALI files. It generates error messages if the program is
2506 inconsistent or if no valid order of elaboration exists.
2507
2508 If no errors are detected, the binder produces a main program, in Ada by
2509 default, that contains calls to the elaboration procedures of those
2510 compilation unit that require them, followed by
2511 a call to the main program. This Ada program is compiled to generate the
2512 object file for the main program. The name of
2513 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2514 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 main program unit.
2516
2517 Finally, the linker is used to build the resulting executable program,
2518 using the object from the main program from the bind step as well as the
2519 object files for the Ada units of the program.
2520
2521 @node Mixed Language Programming
2522 @section Mixed Language Programming
2523 @cindex Mixed Language Programming
2524
2525 @noindent
2526 This section describes how to develop a mixed-language program,
2527 specifically one that comprises units in both Ada and C.
2528
2529 @menu
2530 * Interfacing to C::
2531 * Calling Conventions::
2532 @end menu
2533
2534 @node Interfacing to C
2535 @subsection Interfacing to C
2536 @noindent
2537 Interfacing Ada with a foreign language such as C involves using
2538 compiler directives to import and/or export entity definitions in each
2539 language---using @code{extern} statements in C, for instance, and the
2540 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2541 A full treatment of these topics is provided in Appendix B, section 1
2542 of the Ada Reference Manual.
2543
2544 There are two ways to build a program using GNAT that contains some Ada
2545 sources and some foreign language sources, depending on whether or not
2546 the main subprogram is written in Ada.  Here is a source example with
2547 the main subprogram in Ada:
2548
2549 @smallexample
2550 /* file1.c */
2551 #include <stdio.h>
2552
2553 void print_num (int num)
2554 @{
2555   printf ("num is %d.\n", num);
2556   return;
2557 @}
2558
2559 /* file2.c */
2560
2561 /* num_from_Ada is declared in my_main.adb */
2562 extern int num_from_Ada;
2563
2564 int get_num (void)
2565 @{
2566   return num_from_Ada;
2567 @}
2568 @end smallexample
2569
2570 @smallexample @c ada
2571 --  my_main.adb
2572 procedure My_Main is
2573
2574    --  Declare then export an Integer entity called num_from_Ada
2575    My_Num : Integer := 10;
2576    pragma Export (C, My_Num, "num_from_Ada");
2577
2578    --  Declare an Ada function spec for Get_Num, then use
2579    --  C function get_num for the implementation.
2580    function Get_Num return Integer;
2581    pragma Import (C, Get_Num, "get_num");
2582
2583    --  Declare an Ada procedure spec for Print_Num, then use
2584    --  C function print_num for the implementation.
2585    procedure Print_Num (Num : Integer);
2586    pragma Import (C, Print_Num, "print_num");
2587
2588 begin
2589    Print_Num (Get_Num);
2590 end My_Main;
2591 @end smallexample
2592
2593 @enumerate
2594 @item
2595 To build this example, first compile the foreign language files to
2596 generate object files:
2597 @smallexample
2598 ^gcc -c file1.c^gcc -c FILE1.C^
2599 ^gcc -c file2.c^gcc -c FILE2.C^
2600 @end smallexample
2601
2602 @item
2603 Then, compile the Ada units to produce a set of object files and ALI
2604 files:
2605 @smallexample
2606 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 @end smallexample
2608
2609 @item
2610 Run the Ada binder on the Ada main program:
2611 @smallexample
2612 gnatbind my_main.ali
2613 @end smallexample
2614
2615 @item
2616 Link the Ada main program, the Ada objects and the other language
2617 objects:
2618 @smallexample
2619 gnatlink my_main.ali file1.o file2.o
2620 @end smallexample
2621 @end enumerate
2622
2623 The last three steps can be grouped in a single command:
2624 @smallexample
2625 gnatmake my_main.adb -largs file1.o file2.o
2626 @end smallexample
2627
2628 @cindex Binder output file
2629 @noindent
2630 If the main program is in a language other than Ada, then you may have
2631 more than one entry point into the Ada subsystem. You must use a special
2632 binder option to generate callable routines that initialize and
2633 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2634 Calls to the initialization and finalization routines must be inserted
2635 in the main program, or some other appropriate point in the code. The
2636 call to initialize the Ada units must occur before the first Ada
2637 subprogram is called, and the call to finalize the Ada units must occur
2638 after the last Ada subprogram returns. The binder will place the
2639 initialization and finalization subprograms into the
2640 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2641 sources.  To illustrate, we have the following example:
2642
2643 @smallexample
2644 /* main.c */
2645 extern void adainit (void);
2646 extern void adafinal (void);
2647 extern int add (int, int);
2648 extern int sub (int, int);
2649
2650 int main (int argc, char *argv[])
2651 @{
2652   int a = 21, b = 7;
2653
2654   adainit();
2655
2656   /* Should print "21 + 7 = 28" */
2657   printf ("%d + %d = %d\n", a, b, add (a, b));
2658   /* Should print "21 - 7 = 14" */
2659   printf ("%d - %d = %d\n", a, b, sub (a, b));
2660
2661   adafinal();
2662 @}
2663 @end smallexample
2664
2665 @smallexample @c ada
2666 --  unit1.ads
2667 package Unit1 is
2668    function Add (A, B : Integer) return Integer;
2669    pragma Export (C, Add, "add");
2670 end Unit1;
2671
2672 --  unit1.adb
2673 package body Unit1 is
2674    function Add (A, B : Integer) return Integer is
2675    begin
2676       return A + B;
2677    end Add;
2678 end Unit1;
2679
2680 --  unit2.ads
2681 package Unit2 is
2682    function Sub (A, B : Integer) return Integer;
2683    pragma Export (C, Sub, "sub");
2684 end Unit2;
2685
2686 --  unit2.adb
2687 package body Unit2 is
2688    function Sub (A, B : Integer) return Integer is
2689    begin
2690       return A - B;
2691    end Sub;
2692 end Unit2;
2693 @end smallexample
2694
2695 @enumerate
2696 @item
2697 The build procedure for this application is similar to the last
2698 example's.  First, compile the foreign language files to generate object
2699 files:
2700 @smallexample
2701 ^gcc -c main.c^gcc -c main.c^
2702 @end smallexample
2703
2704 @item
2705 Next, compile the Ada units to produce a set of object files and ALI
2706 files:
2707 @smallexample
2708 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 @end smallexample
2711
2712 @item
2713 Run the Ada binder on every generated ALI file.  Make sure to use the
2714 @option{-n} option to specify a foreign main program:
2715 @smallexample
2716 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 @end smallexample
2718
2719 @item
2720 Link the Ada main program, the Ada objects and the foreign language
2721 objects. You need only list the last ALI file here:
2722 @smallexample
2723 gnatlink unit2.ali main.o -o exec_file
2724 @end smallexample
2725
2726 This procedure yields a binary executable called @file{exec_file}.
2727 @end enumerate
2728
2729 @noindent
2730 Depending on the circumstances (for example when your non-Ada main object
2731 does not provide symbol @code{main}), you may also need to instruct the
2732 GNAT linker not to include the standard startup objects by passing the
2733 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2734
2735 @node Calling Conventions
2736 @subsection Calling Conventions
2737 @cindex Foreign Languages
2738 @cindex Calling Conventions
2739 GNAT follows standard calling sequence conventions and will thus interface
2740 to any other language that also follows these conventions. The following
2741 Convention identifiers are recognized by GNAT:
2742
2743 @table @code
2744 @cindex Interfacing to Ada
2745 @cindex Other Ada compilers
2746 @cindex Convention Ada
2747 @item Ada
2748 This indicates that the standard Ada calling sequence will be
2749 used and all Ada data items may be passed without any limitations in the
2750 case where GNAT is used to generate both the caller and callee. It is also
2751 possible to mix GNAT generated code and code generated by another Ada
2752 compiler. In this case, the data types should be restricted to simple
2753 cases, including primitive types. Whether complex data types can be passed
2754 depends on the situation. Probably it is safe to pass simple arrays, such
2755 as arrays of integers or floats. Records may or may not work, depending
2756 on whether both compilers lay them out identically. Complex structures
2757 involving variant records, access parameters, tasks, or protected types,
2758 are unlikely to be able to be passed.
2759
2760 Note that in the case of GNAT running
2761 on a platform that supports HP Ada 83, a higher degree of compatibility
2762 can be guaranteed, and in particular records are layed out in an identical
2763 manner in the two compilers. Note also that if output from two different
2764 compilers is mixed, the program is responsible for dealing with elaboration
2765 issues. Probably the safest approach is to write the main program in the
2766 version of Ada other than GNAT, so that it takes care of its own elaboration
2767 requirements, and then call the GNAT-generated adainit procedure to ensure
2768 elaboration of the GNAT components. Consult the documentation of the other
2769 Ada compiler for further details on elaboration.
2770
2771 However, it is not possible to mix the tasking run time of GNAT and
2772 HP Ada 83, All the tasking operations must either be entirely within
2773 GNAT compiled sections of the program, or entirely within HP Ada 83
2774 compiled sections of the program.
2775
2776 @cindex Interfacing to Assembly
2777 @cindex Convention Assembler
2778 @item Assembler
2779 Specifies assembler as the convention. In practice this has the
2780 same effect as convention Ada (but is not equivalent in the sense of being
2781 considered the same convention).
2782
2783 @cindex Convention Asm
2784 @findex Asm
2785 @item Asm
2786 Equivalent to Assembler.
2787
2788 @cindex Interfacing to COBOL
2789 @cindex Convention COBOL
2790 @findex COBOL
2791 @item COBOL
2792 Data will be passed according to the conventions described
2793 in section B.4 of the Ada Reference Manual.
2794
2795 @findex C
2796 @cindex Interfacing to C
2797 @cindex Convention C
2798 @item C
2799 Data will be passed according to the conventions described
2800 in section B.3 of the Ada Reference Manual.
2801
2802 A note on interfacing to a C ``varargs'' function:
2803 @findex C varargs function
2804 @cindex Interfacing to C varargs function
2805 @cindex varargs function interfaces
2806
2807 @itemize @bullet
2808 @item
2809 In C, @code{varargs} allows a function to take a variable number of
2810 arguments. There is no direct equivalent in this to Ada. One
2811 approach that can be used is to create a C wrapper for each
2812 different profile and then interface to this C wrapper. For
2813 example, to print an @code{int} value using @code{printf},
2814 create a C function @code{printfi} that takes two arguments, a
2815 pointer to a string and an int, and calls @code{printf}.
2816 Then in the Ada program, use pragma @code{Import} to
2817 interface to @code{printfi}.
2818
2819 @item
2820 It may work on some platforms to directly interface to
2821 a @code{varargs} function by providing a specific Ada profile
2822 for a particular call. However, this does not work on
2823 all platforms, since there is no guarantee that the
2824 calling sequence for a two argument normal C function
2825 is the same as for calling a @code{varargs} C function with
2826 the same two arguments.
2827 @end itemize
2828
2829 @cindex Convention Default
2830 @findex Default
2831 @item Default
2832 Equivalent to C.
2833
2834 @cindex Convention External
2835 @findex External
2836 @item External
2837 Equivalent to C.
2838
2839 @ifclear vms
2840 @findex C++
2841 @cindex Interfacing to C++
2842 @cindex Convention C++
2843 @item C_Plus_Plus (or CPP)
2844 This stands for C++. For most purposes this is identical to C.
2845 See the separate description of the specialized GNAT pragmas relating to
2846 C++ interfacing for further details.
2847 @end ifclear
2848
2849 @findex Fortran
2850 @cindex Interfacing to Fortran
2851 @cindex Convention Fortran
2852 @item Fortran
2853 Data will be passed according to the conventions described
2854 in section B.5 of the Ada Reference Manual.
2855
2856 @item Intrinsic
2857 This applies to an intrinsic operation, as defined in the Ada
2858 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2859 this means that the body of the subprogram is provided by the compiler itself,
2860 usually by means of an efficient code sequence, and that the user does not
2861 supply an explicit body for it. In an application program, the pragma may
2862 be applied to the following sets of names:
2863
2864 @itemize @bullet
2865 @item
2866 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2867 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2868 two formal parameters. The
2869 first one must be a signed integer type or a modular type with a binary
2870 modulus, and the second parameter must be of type Natural.
2871 The return type must be the same as the type of the first argument. The size
2872 of this type can only be 8, 16, 32, or 64.
2873
2874 @item
2875 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2876 The corresponding operator declaration must have parameters and result type
2877 that have the same root numeric type (for example, all three are long_float
2878 types). This simplifies the definition of operations that use type checking
2879 to perform dimensional checks:
2880
2881 @smallexample @c ada
2882 type Distance is new Long_Float;
2883 type Time     is new Long_Float;
2884 type Velocity is new Long_Float;
2885 function "/" (D : Distance; T : Time)
2886   return Velocity;
2887 pragma Import (Intrinsic, "/");
2888 @end smallexample
2889
2890 @noindent
2891 This common idiom is often programmed with a generic definition and an
2892 explicit body. The pragma makes it simpler to introduce such declarations.
2893 It incurs no overhead in compilation time or code size, because it is
2894 implemented as a single machine instruction.
2895
2896 @item
2897 General subprogram entities, to bind an Ada subprogram declaration to
2898 a compiler builtin by name with back-ends where such interfaces are
2899 available. A typical example is the set of ``__builtin'' functions
2900 exposed by the GCC back-end, as in the following example:
2901
2902 @smallexample @c ada
2903    function builtin_sqrt (F : Float) return Float;
2904    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 @end smallexample
2906
2907 Most of the GCC builtins are accessible this way, and as for other
2908 import conventions (e.g. C), it is the user's responsibility to ensure
2909 that the Ada subprogram profile matches the underlying builtin
2910 expectations.
2911 @end itemize
2912
2913 @noindent
2914
2915 @ifset unw
2916 @findex Stdcall
2917 @cindex Convention Stdcall
2918 @item Stdcall
2919 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2920 and specifies that the @code{Stdcall} calling sequence will be used,
2921 as defined by the NT API. Nevertheless, to ease building
2922 cross-platform bindings this convention will be handled as a @code{C} calling
2923 convention on non-Windows platforms.
2924
2925 @findex DLL
2926 @cindex Convention DLL
2927 @item DLL
2928 This is equivalent to @code{Stdcall}.
2929
2930 @findex Win32
2931 @cindex Convention Win32
2932 @item Win32
2933 This is equivalent to @code{Stdcall}.
2934 @end ifset
2935
2936 @findex Stubbed
2937 @cindex Convention Stubbed
2938 @item Stubbed
2939 This is a special convention that indicates that the compiler
2940 should provide a stub body that raises @code{Program_Error}.
2941 @end table
2942
2943 @noindent
2944 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2945 that can be used to parametrize conventions and allow additional synonyms
2946 to be specified. For example if you have legacy code in which the convention
2947 identifier Fortran77 was used for Fortran, you can use the configuration
2948 pragma:
2949
2950 @smallexample @c ada
2951 pragma Convention_Identifier (Fortran77, Fortran);
2952 @end smallexample
2953
2954 @noindent
2955 And from now on the identifier Fortran77 may be used as a convention
2956 identifier (for example in an @code{Import} pragma) with the same
2957 meaning as Fortran.
2958
2959 @ifclear vms
2960 @node Building Mixed Ada & C++ Programs
2961 @section Building Mixed Ada and C++ Programs
2962
2963 @noindent
2964 A programmer inexperienced with mixed-language development may find that
2965 building an application containing both Ada and C++ code can be a
2966 challenge.  This section gives a few
2967 hints that should make this task easier. The first section addresses
2968 the differences between interfacing with C and interfacing with C++.
2969 The second section
2970 looks into the delicate problem of linking the complete application from
2971 its Ada and C++ parts. The last section gives some hints on how the GNAT
2972 run-time library can be adapted in order to allow inter-language dispatching
2973 with a new C++ compiler.
2974
2975 @menu
2976 * Interfacing to C++::
2977 * Linking a Mixed C++ & Ada Program::
2978 * A Simple Example::
2979 * Interfacing with C++ constructors::
2980 * Interfacing with C++ at the Class Level::
2981 @end menu
2982
2983 @node Interfacing to C++
2984 @subsection Interfacing to C++
2985
2986 @noindent
2987 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2988 generating code that is compatible with the G++ Application Binary
2989 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2990
2991 @noindent
2992 Interfacing can be done at 3 levels: simple data, subprograms, and
2993 classes. In the first two cases, GNAT offers a specific @code{Convention
2994 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2995 Usually, C++ mangles the names of subprograms. To generate proper mangled
2996 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2997 This problem can also be addressed manually in two ways:
2998
2999 @itemize @bullet
3000 @item
3001 by modifying the C++ code in order to force a C convention using
3002 the @code{extern "C"} syntax.
3003
3004 @item
3005 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3006 Link_Name argument of the pragma import.
3007 @end itemize
3008
3009 @noindent
3010 Interfacing at the class level can be achieved by using the GNAT specific
3011 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3012 gnat_rm, GNAT Reference Manual}, for additional information.
3013
3014 @node Linking a Mixed C++ & Ada Program
3015 @subsection Linking a Mixed C++ & Ada Program
3016
3017 @noindent
3018 Usually the linker of the C++ development system must be used to link
3019 mixed applications because most C++ systems will resolve elaboration
3020 issues (such as calling constructors on global class instances)
3021 transparently during the link phase. GNAT has been adapted to ease the
3022 use of a foreign linker for the last phase. Three cases can be
3023 considered:
3024 @enumerate
3025
3026 @item
3027 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3028 The C++ linker can simply be called by using the C++ specific driver
3029 called @code{g++}.
3030
3031 Note that if the C++ code uses inline functions, you will need to
3032 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3033 order to provide an existing function implementation that the Ada code can
3034 link with.
3035
3036 @smallexample
3037 $ g++ -c -fkeep-inline-functions file1.C
3038 $ g++ -c -fkeep-inline-functions file2.C
3039 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3040 @end smallexample
3041
3042 @item
3043 Using GNAT and G++ from two different GCC installations: If both
3044 compilers are on the @env{PATH}, the previous method may be used. It is
3045 important to note that environment variables such as
3046 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3047 @env{GCC_ROOT} will affect both compilers
3048 at the same time and may make one of the two compilers operate
3049 improperly if set during invocation of the wrong compiler.  It is also
3050 very important that the linker uses the proper @file{libgcc.a} GCC
3051 library -- that is, the one from the C++ compiler installation. The
3052 implicit link command as suggested in the @command{gnatmake} command
3053 from the former example can be replaced by an explicit link command with
3054 the full-verbosity option in order to verify which library is used:
3055 @smallexample
3056 $ gnatbind ada_unit
3057 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3058 @end smallexample
3059 If there is a problem due to interfering environment variables, it can
3060 be worked around by using an intermediate script. The following example
3061 shows the proper script to use when GNAT has not been installed at its
3062 default location and g++ has been installed at its default location:
3063
3064 @smallexample
3065 $ cat ./my_script
3066 #!/bin/sh
3067 unset BINUTILS_ROOT
3068 unset GCC_ROOT
3069 c++ $*
3070 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3071 @end smallexample
3072
3073 @item
3074 Using a non-GNU C++ compiler: The commands previously described can be
3075 used to insure that the C++ linker is used. Nonetheless, you need to add
3076 a few more parameters to the link command line, depending on the exception
3077 mechanism used.
3078
3079 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3080 to the libgcc libraries are required:
3081
3082 @smallexample
3083 $ cat ./my_script
3084 #!/bin/sh
3085 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3086 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3087 @end smallexample
3088
3089 Where CC is the name of the non-GNU C++ compiler.
3090
3091 If the @code{zero cost} exception mechanism is used, and the platform
3092 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3093 paths to more objects are required:
3094
3095 @smallexample
3096 $ cat ./my_script
3097 #!/bin/sh
3098 CC `gcc -print-file-name=crtbegin.o` $* \
3099 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3100 `gcc -print-file-name=crtend.o`
3101 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3102 @end smallexample
3103
3104 If the @code{zero cost} exception mechanism is used, and the platform
3105 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3106 Tru64 or AIX), the simple approach described above will not work and
3107 a pre-linking phase using GNAT will be necessary.
3108
3109 @end enumerate
3110
3111 Another alternative is to use the @command{gprbuild} multi-language builder
3112 which has a large knowledge base and knows how to link Ada and C++ code
3113 together automatically in most cases.
3114
3115 @node A Simple Example
3116 @subsection  A Simple Example
3117 @noindent
3118 The following example, provided as part of the GNAT examples, shows how
3119 to achieve procedural interfacing between Ada and C++ in both
3120 directions. The C++ class A has two methods. The first method is exported
3121 to Ada by the means of an extern C wrapper function. The second method
3122 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3123 a limited record with a layout comparable to the C++ class. The Ada
3124 subprogram, in turn, calls the C++ method. So, starting from the C++
3125 main program, the process passes back and forth between the two
3126 languages.
3127
3128 @noindent
3129 Here are the compilation commands:
3130 @smallexample
3131 $ gnatmake -c simple_cpp_interface
3132 $ g++ -c cpp_main.C
3133 $ g++ -c ex7.C
3134 $ gnatbind -n simple_cpp_interface
3135 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3136       -lstdc++ ex7.o cpp_main.o
3137 @end smallexample
3138
3139 @noindent
3140 Here are the corresponding sources:
3141 @smallexample
3142
3143 //cpp_main.C
3144
3145 #include "ex7.h"
3146
3147 extern "C" @{
3148   void adainit (void);
3149   void adafinal (void);
3150   void method1 (A *t);
3151 @}
3152
3153 void method1 (A *t)
3154 @{
3155   t->method1 ();
3156 @}
3157
3158 int main ()
3159 @{
3160   A obj;
3161   adainit ();
3162   obj.method2 (3030);
3163   adafinal ();
3164 @}
3165
3166 //ex7.h
3167
3168 class Origin @{
3169  public:
3170   int o_value;
3171 @};
3172 class A : public Origin @{
3173  public:
3174   void method1 (void);
3175   void method2 (int v);
3176   A();
3177   int   a_value;
3178 @};
3179
3180 //ex7.C
3181
3182 #include "ex7.h"
3183 #include <stdio.h>
3184
3185 extern "C" @{ void ada_method2 (A *t, int v);@}
3186
3187 void A::method1 (void)
3188 @{
3189   a_value = 2020;
3190   printf ("in A::method1, a_value = %d \n",a_value);
3191
3192 @}
3193
3194 void A::method2 (int v)
3195 @{
3196    ada_method2 (this, v);
3197    printf ("in A::method2, a_value = %d \n",a_value);
3198
3199 @}
3200
3201 A::A(void)
3202 @{
3203    a_value = 1010;
3204   printf ("in A::A, a_value = %d \n",a_value);
3205 @}
3206 @end smallexample
3207
3208 @smallexample @c ada
3209 -- Ada sources
3210 package body Simple_Cpp_Interface is
3211
3212    procedure Ada_Method2 (This : in out A; V : Integer) is
3213    begin
3214       Method1 (This);
3215       This.A_Value := V;
3216    end Ada_Method2;
3217
3218 end Simple_Cpp_Interface;
3219
3220 with System;
3221 package Simple_Cpp_Interface is
3222    type A is limited
3223       record
3224          Vptr    : System.Address;
3225          O_Value : Integer;
3226          A_Value : Integer;
3227       end record;
3228    pragma Convention (C, A);
3229
3230    procedure Method1 (This : in out A);
3231    pragma Import (C, Method1);
3232
3233    procedure Ada_Method2 (This : in out A; V : Integer);
3234    pragma Export (C, Ada_Method2);
3235
3236 end Simple_Cpp_Interface;
3237 @end smallexample
3238
3239 @node Interfacing with C++ constructors
3240 @subsection Interfacing with C++ constructors
3241 @noindent
3242
3243 In order to interface with C++ constructors GNAT provides the
3244 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3245 gnat_rm, GNAT Reference Manual}, for additional information).
3246 In this section we present some common uses of C++ constructors
3247 in mixed-languages programs in GNAT.
3248
3249 Let us assume that we need to interface with the following
3250 C++ class:
3251
3252 @smallexample
3253 @b{class} Root @{
3254 @b{public}:
3255   int  a_value;
3256   int  b_value;
3257   @b{virtual} int Get_Value ();
3258   Root();              // Default constructor
3259   Root(int v);         // 1st non-default constructor
3260   Root(int v, int w);  // 2nd non-default constructor
3261 @};
3262 @end smallexample
3263
3264 For this purpose we can write the following package spec (further
3265 information on how to build this spec is available in
3266 @ref{Interfacing with C++ at the Class Level} and
3267 @ref{Generating Ada Bindings for C and C++ headers}).
3268
3269 @smallexample @c ada
3270 with Interfaces.C; use Interfaces.C;
3271 package Pkg_Root is
3272   type Root is tagged limited record
3273      A_Value : int;
3274      B_Value : int;
3275   end record;
3276   pragma Import (CPP, Root);
3277
3278   function Get_Value (Obj : Root) return int;
3279   pragma Import (CPP, Get_Value);
3280
3281   function Constructor return Root;
3282   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3283
3284   function Constructor (v : Integer) return Root;
3285   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3286
3287   function Constructor (v, w : Integer) return Root;
3288   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3289 end Pkg_Root;
3290 @end smallexample
3291
3292 On the Ada side the constructor is represented by a function (whose
3293 name is arbitrary) that returns the classwide type corresponding to
3294 the imported C++ class. Although the constructor is described as a
3295 function, it is typically a procedure with an extra implicit argument
3296 (the object being initialized) at the implementation level. GNAT
3297 issues the appropriate call, whatever it is, to get the object
3298 properly initialized.
3299
3300 Constructors can only appear in the following contexts:
3301
3302 @itemize @bullet
3303 @item
3304 On the right side of an initialization of an object of type @var{T}.
3305 @item
3306 On the right side of an initialization of a record component of type @var{T}.
3307 @item
3308 In an Ada 2005 limited aggregate.
3309 @item
3310 In an Ada 2005 nested limited aggregate.
3311 @item
3312 In an Ada 2005 limited aggregate that initializes an object built in
3313 place by an extended return statement.
3314 @end itemize
3315
3316 @noindent
3317 In a declaration of an object whose type is a class imported from C++,
3318 either the default C++ constructor is implicitly called by GNAT, or
3319 else the required C++ constructor must be explicitly called in the
3320 expression that initializes the object. For example:
3321
3322 @smallexample @c ada
3323   Obj1 : Root;
3324   Obj2 : Root := Constructor;
3325   Obj3 : Root := Constructor (v => 10);
3326   Obj4 : Root := Constructor (30, 40);
3327 @end smallexample
3328
3329 The first two declarations are equivalent: in both cases the default C++
3330 constructor is invoked (in the former case the call to the constructor is
3331 implicit, and in the latter case the call is explicit in the object
3332 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3333 that takes an integer argument, and @code{Obj4} is initialized by the
3334 non-default C++ constructor that takes two integers.
3335
3336 Let us derive the imported C++ class in the Ada side. For example:
3337
3338 @smallexample @c ada
3339   type DT is new Root with record
3340      C_Value : Natural := 2009;
3341   end record;
3342 @end smallexample
3343
3344 In this case the components DT inherited from the C++ side must be
3345 initialized by a C++ constructor, and the additional Ada components
3346 of type DT are initialized by GNAT. The initialization of such an
3347 object is done either by default, or by means of a function returning
3348 an aggregate of type DT, or by means of an extension aggregate.
3349
3350 @smallexample @c ada
3351   Obj5 : DT;
3352   Obj6 : DT := Function_Returning_DT (50);
3353   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3354 @end smallexample
3355
3356 The declaration of @code{Obj5} invokes the default constructors: the
3357 C++ default constructor of the parent type takes care of the initialization
3358 of the components inherited from Root, and GNAT takes care of the default
3359 initialization of the additional Ada components of type DT (that is,
3360 @code{C_Value} is initialized to value 2009). The order of invocation of
3361 the constructors is consistent with the order of elaboration required by
3362 Ada and C++. That is, the constructor of the parent type is always called
3363 before the constructor of the derived type.
3364
3365 Let us now consider a record that has components whose type is imported
3366 from C++. For example:
3367
3368 @smallexample @c ada
3369   type Rec1 is limited record
3370      Data1 : Root := Constructor (10);
3371      Value : Natural := 1000;
3372   end record;
3373
3374   type Rec2 (D : Integer := 20) is limited record
3375      Rec   : Rec1;
3376      Data2 : Root := Constructor (D, 30);
3377   end record;
3378 @end smallexample
3379
3380 The initialization of an object of type @code{Rec2} will call the
3381 non-default C++ constructors specified for the imported components.
3382 For example:
3383
3384 @smallexample @c ada
3385   Obj8 : Rec2 (40);
3386 @end smallexample
3387
3388 Using Ada 2005 we can use limited aggregates to initialize an object
3389 invoking C++ constructors that differ from those specified in the type
3390 declarations. For example:
3391
3392 @smallexample @c ada
3393   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3394                           others => <>),
3395                   others => <>);
3396 @end smallexample
3397
3398 The above declaration uses an Ada 2005 limited aggregate to
3399 initialize @code{Obj9}, and the C++ constructor that has two integer
3400 arguments is invoked to initialize the @code{Data1} component instead
3401 of the constructor specified in the declaration of type @code{Rec1}. In
3402 Ada 2005 the box in the aggregate indicates that unspecified components
3403 are initialized using the expression (if any) available in the component
3404 declaration. That is, in this case discriminant @code{D} is initialized
3405 to value @code{20}, @code{Value} is initialized to value 1000, and the
3406 non-default C++ constructor that handles two integers takes care of
3407 initializing component @code{Data2} with values @code{20,30}.
3408
3409 In Ada 2005 we can use the extended return statement to build the Ada
3410 equivalent to C++ non-default constructors. For example:
3411
3412 @smallexample @c ada
3413   function Constructor (V : Integer) return Rec2 is
3414   begin
3415      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3416                                    others => <>),
3417                            others => <>) do
3418         --  Further actions required for construction of
3419         --  objects of type Rec2
3420         ...
3421      end record;
3422   end Constructor;
3423 @end smallexample
3424
3425 In this example the extended return statement construct is used to
3426 build in place the returned object whose components are initialized
3427 by means of a limited aggregate. Any further action associated with
3428 the constructor can be placed inside the construct.
3429
3430 @node Interfacing with C++ at the Class Level
3431 @subsection Interfacing with C++ at the Class Level
3432 @noindent
3433 In this section we demonstrate the GNAT features for interfacing with
3434 C++ by means of an example making use of Ada 2005 abstract interface
3435 types. This example consists of a classification of animals; classes
3436 have been used to model our main classification of animals, and
3437 interfaces provide support for the management of secondary
3438 classifications. We first demonstrate a case in which the types and
3439 constructors are defined on the C++ side and imported from the Ada
3440 side, and latter the reverse case.
3441
3442 The root of our derivation will be the @code{Animal} class, with a
3443 single private attribute (the @code{Age} of the animal) and two public
3444 primitives to set and get the value of this attribute.
3445
3446 @smallexample
3447 @b{class} Animal @{
3448  @b{public}:
3449    @b{virtual} void Set_Age (int New_Age);
3450    @b{virtual} int Age ();
3451  @b{private}:
3452    int Age_Count;
3453 @};
3454 @end smallexample
3455
3456 Abstract interface types are defined in C++ by means of classes with pure
3457 virtual functions and no data members. In our example we will use two
3458 interfaces that provide support for the common management of @code{Carnivore}
3459 and @code{Domestic} animals:
3460
3461 @smallexample
3462 @b{class} Carnivore @{
3463 @b{public}:
3464    @b{virtual} int Number_Of_Teeth () = 0;
3465 @};
3466
3467 @b{class} Domestic @{
3468 @b{public}:
3469    @b{virtual void} Set_Owner (char* Name) = 0;
3470 @};
3471 @end smallexample
3472
3473 Using these declarations, we can now say that a @code{Dog} is an animal that is
3474 both Carnivore and Domestic, that is:
3475
3476 @smallexample
3477 @b{class} Dog : Animal, Carnivore, Domestic @{
3478  @b{public}:
3479    @b{virtual} int  Number_Of_Teeth ();
3480    @b{virtual} void Set_Owner (char* Name);
3481
3482    Dog(); // Constructor
3483  @b{private}:
3484    int  Tooth_Count;
3485    char *Owner;
3486 @};
3487 @end smallexample
3488
3489 In the following examples we will assume that the previous declarations are
3490 located in a file named @code{animals.h}. The following package demonstrates
3491 how to import these C++ declarations from the Ada side:
3492
3493 @smallexample @c ada
3494 with Interfaces.C.Strings; use Interfaces.C.Strings;
3495 package Animals is
3496   type Carnivore is interface;
3497   pragma Convention (C_Plus_Plus, Carnivore);
3498   function Number_Of_Teeth (X : Carnivore)
3499      return Natural is abstract;
3500
3501   type Domestic is interface;
3502   pragma Convention (C_Plus_Plus, Set_Owner);
3503   procedure Set_Owner
3504     (X    : in out Domestic;
3505      Name : Chars_Ptr) is abstract;
3506
3507   type Animal is tagged record
3508     Age : Natural := 0;
3509   end record;
3510   pragma Import (C_Plus_Plus, Animal);
3511
3512   procedure Set_Age (X : in out Animal; Age : Integer);
3513   pragma Import (C_Plus_Plus, Set_Age);
3514
3515   function Age (X : Animal) return Integer;
3516   pragma Import (C_Plus_Plus, Age);
3517
3518   type Dog is new Animal and Carnivore and Domestic with record
3519     Tooth_Count : Natural;
3520     Owner       : String (1 .. 30);
3521   end record;
3522   pragma Import (C_Plus_Plus, Dog);
3523
3524   function Number_Of_Teeth (A : Dog) return Integer;
3525   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3526
3527   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3528   pragma Import (C_Plus_Plus, Set_Owner);
3529
3530   function New_Dog return Dog;
3531   pragma CPP_Constructor (New_Dog);
3532   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3533 end Animals;
3534 @end smallexample
3535
3536 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3537 interfacing with these C++ classes is easy. The only requirement is that all
3538 the primitives and components must be declared exactly in the same order in
3539 the two languages.
3540
3541 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3542 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3543 the arguments to the called primitives will be the same as for C++. For the
3544 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3545 to indicate that they have been defined on the C++ side; this is required
3546 because the dispatch table associated with these tagged types will be built
3547 in the C++ side and therefore will not contain the predefined Ada primitives
3548 which Ada would otherwise expect.
3549
3550 As the reader can see there is no need to indicate the C++ mangled names
3551 associated with each subprogram because it is assumed that all the calls to
3552 these primitives will be dispatching calls. The only exception is the
3553 constructor, which must be registered with the compiler by means of
3554 @code{pragma CPP_Constructor} and needs to provide its associated C++
3555 mangled name because the Ada compiler generates direct calls to it.
3556
3557 With the above packages we can now declare objects of type Dog on the Ada side
3558 and dispatch calls to the corresponding subprograms on the C++ side. We can
3559 also extend the tagged type Dog with further fields and primitives, and
3560 override some of its C++ primitives on the Ada side. For example, here we have
3561 a type derivation defined on the Ada side that inherits all the dispatching
3562 primitives of the ancestor from the C++ side.
3563
3564 @smallexample
3565 @b{with} Animals; @b{use} Animals;
3566 @b{package} Vaccinated_Animals @b{is}
3567   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3568   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3569 @b{end} Vaccinated_Animals;
3570 @end smallexample
3571
3572 It is important to note that, because of the ABI compatibility, the programmer
3573 does not need to add any further information to indicate either the object
3574 layout or the dispatch table entry associated with each dispatching operation.
3575
3576 Now let us define all the types and constructors on the Ada side and export
3577 them to C++, using the same hierarchy of our previous example:
3578
3579 @smallexample @c ada
3580 with Interfaces.C.Strings;
3581 use Interfaces.C.Strings;
3582 package Animals is
3583   type Carnivore is interface;
3584   pragma Convention (C_Plus_Plus, Carnivore);
3585   function Number_Of_Teeth (X : Carnivore)
3586      return Natural is abstract;
3587
3588   type Domestic is interface;
3589   pragma Convention (C_Plus_Plus, Set_Owner);
3590   procedure Set_Owner
3591     (X    : in out Domestic;
3592      Name : Chars_Ptr) is abstract;
3593
3594   type Animal is tagged record
3595     Age : Natural := 0;
3596   end record;
3597   pragma Convention (C_Plus_Plus, Animal);
3598
3599   procedure Set_Age (X : in out Animal; Age : Integer);
3600   pragma Export (C_Plus_Plus, Set_Age);
3601
3602   function Age (X : Animal) return Integer;
3603   pragma Export (C_Plus_Plus, Age);
3604
3605   type Dog is new Animal and Carnivore and Domestic with record
3606     Tooth_Count : Natural;
3607     Owner       : String (1 .. 30);
3608   end record;
3609   pragma Convention (C_Plus_Plus, Dog);
3610
3611   function Number_Of_Teeth (A : Dog) return Integer;
3612   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3613
3614   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3615   pragma Export (C_Plus_Plus, Set_Owner);
3616
3617   function New_Dog return Dog'Class;
3618   pragma Export (C_Plus_Plus, New_Dog);
3619 end Animals;
3620 @end smallexample
3621
3622 Compared with our previous example the only difference is the use of
3623 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3624 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3625 nothing else to be done; as explained above, the only requirement is that all
3626 the primitives and components are declared in exactly the same order.
3627
3628 For completeness, let us see a brief C++ main program that uses the
3629 declarations available in @code{animals.h} (presented in our first example) to
3630 import and use the declarations from the Ada side, properly initializing and
3631 finalizing the Ada run-time system along the way:
3632
3633 @smallexample
3634 @b{#include} "animals.h"
3635 @b{#include} <iostream>
3636 @b{using namespace} std;
3637
3638 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3639 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3640 void Check_Animal (Animal *obj)       @{@dots{}@}
3641 void Check_Dog (Dog *obj)             @{@dots{}@}
3642
3643 @b{extern} "C" @{
3644   void adainit (void);
3645   void adafinal (void);
3646   Dog* new_dog ();
3647 @}
3648
3649 void test ()
3650 @{
3651   Dog *obj = new_dog();  // Ada constructor
3652   Check_Carnivore (obj); // Check secondary DT
3653   Check_Domestic (obj);  // Check secondary DT
3654   Check_Animal (obj);    // Check primary DT
3655   Check_Dog (obj);       // Check primary DT
3656 @}
3657
3658 int main ()
3659 @{
3660   adainit ();  test();  adafinal ();
3661   return 0;
3662 @}
3663 @end smallexample
3664
3665 @node Comparison between GNAT and C/C++ Compilation Models
3666 @section Comparison between GNAT and C/C++ Compilation Models
3667
3668 @noindent
3669 The GNAT model of compilation is close to the C and C++ models. You can
3670 think of Ada specs as corresponding to header files in C. As in C, you
3671 don't need to compile specs; they are compiled when they are used. The
3672 Ada @code{with} is similar in effect to the @code{#include} of a C
3673 header.
3674
3675 One notable difference is that, in Ada, you may compile specs separately
3676 to check them for semantic and syntactic accuracy. This is not always
3677 possible with C headers because they are fragments of programs that have
3678 less specific syntactic or semantic rules.
3679
3680 The other major difference is the requirement for running the binder,
3681 which performs two important functions. First, it checks for
3682 consistency. In C or C++, the only defense against assembling
3683 inconsistent programs lies outside the compiler, in a makefile, for
3684 example. The binder satisfies the Ada requirement that it be impossible
3685 to construct an inconsistent program when the compiler is used in normal
3686 mode.
3687
3688 @cindex Elaboration order control
3689 The other important function of the binder is to deal with elaboration
3690 issues. There are also elaboration issues in C++ that are handled
3691 automatically. This automatic handling has the advantage of being
3692 simpler to use, but the C++ programmer has no control over elaboration.
3693 Where @code{gnatbind} might complain there was no valid order of
3694 elaboration, a C++ compiler would simply construct a program that
3695 malfunctioned at run time.
3696 @end ifclear
3697
3698 @node Comparison between GNAT and Conventional Ada Library Models
3699 @section Comparison between GNAT and Conventional Ada Library Models
3700
3701 @noindent
3702 This section is intended for Ada programmers who have
3703 used an Ada compiler implementing the traditional Ada library
3704 model, as described in the Ada Reference Manual.
3705
3706 @cindex GNAT library
3707 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3708 source files themselves acts as the library. Compiling Ada programs does
3709 not generate any centralized information, but rather an object file and
3710 a ALI file, which are of interest only to the binder and linker.
3711 In a traditional system, the compiler reads information not only from
3712 the source file being compiled, but also from the centralized library.
3713 This means that the effect of a compilation depends on what has been
3714 previously compiled. In particular:
3715
3716 @itemize @bullet
3717 @item
3718 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3719 to the version of the unit most recently compiled into the library.
3720
3721 @item
3722 Inlining is effective only if the necessary body has already been
3723 compiled into the library.
3724
3725 @item
3726 Compiling a unit may obsolete other units in the library.
3727 @end itemize
3728
3729 @noindent
3730 In GNAT, compiling one unit never affects the compilation of any other
3731 units because the compiler reads only source files. Only changes to source
3732 files can affect the results of a compilation. In particular:
3733
3734 @itemize @bullet
3735 @item
3736 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3737 to the source version of the unit that is currently accessible to the
3738 compiler.
3739
3740 @item
3741 @cindex Inlining
3742 Inlining requires the appropriate source files for the package or
3743 subprogram bodies to be available to the compiler. Inlining is always
3744 effective, independent of the order in which units are complied.
3745
3746 @item
3747 Compiling a unit never affects any other compilations. The editing of
3748 sources may cause previous compilations to be out of date if they
3749 depended on the source file being modified.
3750 @end itemize
3751
3752 @noindent
3753 The most important result of these differences is that order of compilation
3754 is never significant in GNAT. There is no situation in which one is
3755 required to do one compilation before another. What shows up as order of
3756 compilation requirements in the traditional Ada library becomes, in
3757 GNAT, simple source dependencies; in other words, there is only a set
3758 of rules saying what source files must be present when a file is
3759 compiled.
3760
3761 @ifset vms
3762 @node Placement of temporary files
3763 @section Placement of temporary files
3764 @cindex Temporary files (user control over placement)
3765
3766 @noindent
3767 GNAT creates temporary files in the directory designated by the environment
3768 variable @env{TMPDIR}.
3769 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3770 for detailed information on how environment variables are resolved.
3771 For most users the easiest way to make use of this feature is to simply
3772 define @env{TMPDIR} as a job level logical name).
3773 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3774 for compiler temporary files, then you can include something like the
3775 following command in your @file{LOGIN.COM} file:
3776
3777 @smallexample
3778 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3779 @end smallexample
3780
3781 @noindent
3782 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3783 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3784 designated by @env{TEMP}.
3785 If none of these environment variables are defined then GNAT uses the
3786 directory designated by the logical name @code{SYS$SCRATCH:}
3787 (by default the user's home directory). If all else fails
3788 GNAT uses the current directory for temporary files.
3789 @end ifset
3790
3791 @c *************************
3792 @node Compiling Using gcc
3793 @chapter Compiling Using @command{gcc}
3794
3795 @noindent
3796 This chapter discusses how to compile Ada programs using the @command{gcc}
3797 command. It also describes the set of switches
3798 that can be used to control the behavior of the compiler.
3799 @menu
3800 * Compiling Programs::
3801 * Switches for gcc::
3802 * Search Paths and the Run-Time Library (RTL)::
3803 * Order of Compilation Issues::
3804 * Examples::
3805 @end menu
3806
3807 @node Compiling Programs
3808 @section Compiling Programs
3809
3810 @noindent
3811 The first step in creating an executable program is to compile the units
3812 of the program using the @command{gcc} command. You must compile the
3813 following files:
3814
3815 @itemize @bullet
3816 @item
3817 the body file (@file{.adb}) for a library level subprogram or generic
3818 subprogram
3819
3820 @item
3821 the spec file (@file{.ads}) for a library level package or generic
3822 package that has no body
3823
3824 @item
3825 the body file (@file{.adb}) for a library level package
3826 or generic package that has a body
3827
3828 @end itemize
3829
3830 @noindent
3831 You need @emph{not} compile the following files
3832
3833 @itemize @bullet
3834
3835 @item
3836 the spec of a library unit which has a body
3837
3838 @item
3839 subunits
3840 @end itemize
3841
3842 @noindent
3843 because they are compiled as part of compiling related units. GNAT
3844 package specs
3845 when the corresponding body is compiled, and subunits when the parent is
3846 compiled.
3847
3848 @cindex cannot generate code
3849 If you attempt to compile any of these files, you will get one of the
3850 following error messages (where @var{fff} is the name of the file you compiled):
3851
3852 @smallexample
3853 cannot generate code for file @var{fff} (package spec)
3854 to check package spec, use -gnatc
3855
3856 cannot generate code for file @var{fff} (missing subunits)
3857 to check parent unit, use -gnatc
3858
3859 cannot generate code for file @var{fff} (subprogram spec)
3860 to check subprogram spec, use -gnatc
3861
3862 cannot generate code for file @var{fff} (subunit)
3863 to check subunit, use -gnatc
3864 @end smallexample
3865
3866 @noindent
3867 As indicated by the above error messages, if you want to submit
3868 one of these files to the compiler to check for correct semantics
3869 without generating code, then use the @option{-gnatc} switch.
3870
3871 The basic command for compiling a file containing an Ada unit is
3872
3873 @smallexample
3874 $ gcc -c @ovar{switches} @file{file name}
3875 @end smallexample
3876
3877 @noindent
3878 where @var{file name} is the name of the Ada file (usually
3879 having an extension
3880 @file{.ads} for a spec or @file{.adb} for a body).
3881 @ifclear vms
3882 You specify the
3883 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3884 @end ifclear
3885 The result of a successful compilation is an object file, which has the
3886 same name as the source file but an extension of @file{.o} and an Ada
3887 Library Information (ALI) file, which also has the same name as the
3888 source file, but with @file{.ali} as the extension. GNAT creates these
3889 two output files in the current directory, but you may specify a source
3890 file in any directory using an absolute or relative path specification
3891 containing the directory information.
3892
3893 @findex gnat1
3894 @command{gcc} is actually a driver program that looks at the extensions of
3895 the file arguments and loads the appropriate compiler. For example, the
3896 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3897 These programs are in directories known to the driver program (in some
3898 configurations via environment variables you set), but need not be in
3899 your path. The @command{gcc} driver also calls the assembler and any other
3900 utilities needed to complete the generation of the required object
3901 files.
3902
3903 It is possible to supply several file names on the same @command{gcc}
3904 command. This causes @command{gcc} to call the appropriate compiler for
3905 each file. For example, the following command lists three separate
3906 files to be compiled:
3907
3908 @smallexample
3909 $ gcc -c x.adb y.adb z.c
3910 @end smallexample
3911
3912 @noindent
3913 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3914 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3915 The compiler generates three object files @file{x.o}, @file{y.o} and
3916 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3917 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3918 @ifclear vms
3919 except for
3920 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3921 @end ifclear
3922
3923 @node Switches for gcc
3924 @section Switches for @command{gcc}
3925
3926 @noindent
3927 The @command{gcc} command accepts switches that control the
3928 compilation process. These switches are fully described in this section.
3929 First we briefly list all the switches, in alphabetical order, then we
3930 describe the switches in more detail in functionally grouped sections.
3931
3932 More switches exist for GCC than those documented here, especially
3933 for specific targets. However, their use is not recommended as
3934 they may change code generation in ways that are incompatible with
3935 the Ada run-time library, or can cause inconsistencies between
3936 compilation units.
3937
3938 @menu
3939 * Output and Error Message Control::
3940 * Warning Message Control::
3941 * Debugging and Assertion Control::
3942 * Validity Checking::
3943 * Style Checking::
3944 * Run-Time Checks::
3945 * Using gcc for Syntax Checking::
3946 * Using gcc for Semantic Checking::
3947 * Compiling Different Versions of Ada::
3948 * Character Set Control::
3949 * File Naming Control::
3950 * Subprogram Inlining Control::
3951 * Auxiliary Output Control::
3952 * Debugging Control::
3953 * Exception Handling Control::
3954 * Units to Sources Mapping Files::
3955 * Integrated Preprocessing::
3956 * Code Generation Control::
3957 @ifset vms
3958 * Return Codes::
3959 @end ifset
3960 @end menu
3961
3962 @table @option
3963 @c !sort!
3964 @ifclear vms
3965 @cindex @option{-b} (@command{gcc})
3966 @item -b @var{target}
3967 Compile your program to run on @var{target}, which is the name of a
3968 system configuration. You must have a GNAT cross-compiler built if
3969 @var{target} is not the same as your host system.
3970
3971 @item -B@var{dir}
3972 @cindex @option{-B} (@command{gcc})
3973 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3974 from @var{dir} instead of the default location. Only use this switch
3975 when multiple versions of the GNAT compiler are available.
3976 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3977 GNU Compiler Collection (GCC)}, for further details. You would normally
3978 use the @option{-b} or @option{-V} switch instead.
3979
3980 @item -c
3981 @cindex @option{-c} (@command{gcc})
3982 Compile. Always use this switch when compiling Ada programs.
3983
3984 Note: for some other languages when using @command{gcc}, notably in
3985 the case of C and C++, it is possible to use
3986 use @command{gcc} without a @option{-c} switch to
3987 compile and link in one step. In the case of GNAT, you
3988 cannot use this approach, because the binder must be run
3989 and @command{gcc} cannot be used to run the GNAT binder.
3990 @end ifclear
3991
3992 @item -fno-inline
3993 @cindex @option{-fno-inline} (@command{gcc})
3994 Suppresses all back-end inlining, even if other optimization or inlining
3995 switches are set.
3996 This includes suppression of inlining that results
3997 from the use of the pragma @code{Inline_Always}.
3998 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3999 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4000 effect if this switch is present.
4001
4002 @item -fno-inline-functions
4003 @cindex @option{-fno-inline-functions} (@command{gcc})
4004 Suppresses automatic inlining of simple subprograms, which is enabled
4005 if @option{-O3} is used.
4006
4007 @item -fno-inline-small-functions
4008 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4009 Suppresses automatic inlining of small subprograms, which is enabled
4010 if @option{-O2} is used.
4011
4012 @item -fno-inline-functions-called-once
4013 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4014 Suppresses inlining of subprograms local to the unit and called once
4015 from within it, which is enabled if @option{-O1} is used.
4016
4017 @item -fno-ivopts
4018 @cindex @option{-fno-ivopts} (@command{gcc})
4019 Suppresses high-level loop induction variable optimizations, which are
4020 enabled if @option{-O1} is used. These optimizations are generally
4021 profitable but, for some specific cases of loops with numerous uses
4022 of the iteration variable that follow a common pattern, they may end
4023 up destroying the regularity that could be exploited at a lower level
4024 and thus producing inferior code.
4025
4026 @item -fno-strict-aliasing
4027 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4028 Causes the compiler to avoid assumptions regarding non-aliasing
4029 of objects of different types. See
4030 @ref{Optimization and Strict Aliasing} for details.
4031
4032 @item -fstack-check
4033 @cindex @option{-fstack-check} (@command{gcc})
4034 Activates stack checking.
4035 See @ref{Stack Overflow Checking} for details.
4036
4037 @item -fstack-usage
4038 @cindex @option{-fstack-usage} (@command{gcc})
4039 Makes the compiler output stack usage information for the program, on a
4040 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4041
4042 @item -fcallgraph-info@r{[}=su@r{]}
4043 @cindex @option{-fcallgraph-info} (@command{gcc})
4044 Makes the compiler output callgraph information for the program, on a
4045 per-file basis.  The information is generated in the VCG format.  It can
4046 be decorated with stack-usage per-node information.
4047
4048 @item ^-g^/DEBUG^
4049 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4050 Generate debugging information. This information is stored in the object
4051 file and copied from there to the final executable file by the linker,
4052 where it can be read by the debugger. You must use the
4053 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4054
4055 @item -gnat83
4056 @cindex @option{-gnat83} (@command{gcc})
4057 Enforce Ada 83 restrictions.
4058
4059 @item -gnat95
4060 @cindex @option{-gnat95} (@command{gcc})
4061 Enforce Ada 95 restrictions.
4062
4063 @item -gnat05
4064 @cindex @option{-gnat05} (@command{gcc})
4065 Allow full Ada 2005 features.
4066
4067 @item -gnata
4068 @cindex @option{-gnata} (@command{gcc})
4069 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4070 activated. Note that these pragmas can also be controlled using the
4071 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4072 It also activates pragmas @code{Check}, @code{Precondition}, and
4073 @code{Postcondition}. Note that these pragmas can also be controlled
4074 using the configuration pragma @code{Check_Policy}.
4075
4076 @item -gnatA
4077 @cindex @option{-gnatA} (@command{gcc})
4078 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4079 it will be ignored.
4080
4081 @item -gnatb
4082 @cindex @option{-gnatb} (@command{gcc})
4083 Generate brief messages to @file{stderr} even if verbose mode set.
4084
4085 @item -gnatB
4086 @cindex @option{-gnatB} (@command{gcc})
4087 Assume no invalid (bad) values except for 'Valid attribute use
4088 (@pxref{Validity Checking}).
4089
4090 @item -gnatc
4091 @cindex @option{-gnatc} (@command{gcc})
4092 Check syntax and semantics only (no code generation attempted).
4093
4094 @item -gnatC
4095 @cindex @option{-gnatC} (@command{gcc})
4096 Generate CodePeer information (no code generation attempted).
4097 This switch will generate an intermediate representation suitable for
4098 use by CodePeer (@file{.scil} files). This switch is not compatible with
4099 code generation (it will, among other things, disable some switches such
4100 as -gnatn, and enable others such as -gnata).
4101
4102 @item -gnatd
4103 @cindex @option{-gnatd} (@command{gcc})
4104 Specify debug options for the compiler. The string of characters after
4105 the @option{-gnatd} specify the specific debug options. The possible
4106 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4107 compiler source file @file{debug.adb} for details of the implemented
4108 debug options. Certain debug options are relevant to applications
4109 programmers, and these are documented at appropriate points in this
4110 users guide.
4111
4112 @ifclear vms
4113 @item -gnatD
4114 @cindex @option{-gnatD[nn]} (@command{gcc})
4115 @end ifclear
4116 @ifset vms
4117 @item /XDEBUG /LXDEBUG=nnn
4118 @end ifset
4119 Create expanded source files for source level debugging. This switch
4120 also suppress generation of cross-reference information
4121 (see @option{-gnatx}).
4122
4123 @item -gnatec=@var{path}
4124 @cindex @option{-gnatec} (@command{gcc})
4125 Specify a configuration pragma file
4126 @ifclear vms
4127 (the equal sign is optional)
4128 @end ifclear
4129 (@pxref{The Configuration Pragmas Files}).
4130
4131 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4132 @cindex @option{-gnateD} (@command{gcc})
4133 Defines a symbol, associated with @var{value}, for preprocessing.
4134 (@pxref{Integrated Preprocessing}).
4135
4136 @item -gnatef
4137 @cindex @option{-gnatef} (@command{gcc})
4138 Display full source path name in brief error messages.
4139
4140 @item -gnateG
4141 @cindex @option{-gnateG} (@command{gcc})
4142 Save result of preprocessing in a text file.
4143
4144 @item -gnatem=@var{path}
4145 @cindex @option{-gnatem} (@command{gcc})
4146 Specify a mapping file
4147 @ifclear vms
4148 (the equal sign is optional)
4149 @end ifclear
4150 (@pxref{Units to Sources Mapping Files}).
4151
4152 @item -gnatep=@var{file}
4153 @cindex @option{-gnatep} (@command{gcc})
4154 Specify a preprocessing data file
4155 @ifclear vms
4156 (the equal sign is optional)
4157 @end ifclear
4158 (@pxref{Integrated Preprocessing}).
4159
4160 @item -gnateS
4161 @cindex @option{-gnateS} (@command{gcc})
4162 Generate SCO (Source Coverage Obligation) information in the ALI
4163 file. This information is used by advanced coverage tools. See
4164 unit @file{SCOs} in the compiler sources for details in files
4165 @file{scos.ads} and @file{scos.adb}.
4166
4167 @item -gnatE
4168 @cindex @option{-gnatE} (@command{gcc})
4169 Full dynamic elaboration checks.
4170
4171 @item -gnatf
4172 @cindex @option{-gnatf} (@command{gcc})
4173 Full errors. Multiple errors per line, all undefined references, do not
4174 attempt to suppress cascaded errors.
4175
4176 @item -gnatF
4177 @cindex @option{-gnatF} (@command{gcc})
4178 Externals names are folded to all uppercase.
4179
4180 @item ^-gnatg^/GNAT_INTERNAL^
4181 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4182 Internal GNAT implementation mode. This should not be used for
4183 applications programs, it is intended only for use by the compiler
4184 and its run-time library. For documentation, see the GNAT sources.
4185 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4186 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4187 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4188 so that all standard warnings and all standard style options are turned on.
4189 All warnings and style error messages are treated as errors.
4190
4191 @ifclear vms
4192 @item -gnatG=nn
4193 @cindex @option{-gnatG[nn]} (@command{gcc})
4194 @end ifclear
4195 @ifset vms
4196 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4197 @end ifset
4198 List generated expanded code in source form.
4199
4200 @item ^-gnath^/HELP^
4201 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4202 Output usage information. The output is written to @file{stdout}.
4203
4204 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4205 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4206 Identifier character set
4207 @ifclear vms
4208 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4209 @end ifclear
4210 For details of the possible selections for @var{c},
4211 see @ref{Character Set Control}.
4212
4213 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4214 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4215 Ignore representation clauses. When this switch is used,
4216 representation clauses are treated as comments. This is useful
4217 when initially porting code where you want to ignore rep clause
4218 problems, and also for compiling foreign code (particularly
4219 for use with ASIS). The representation clauses that are ignored
4220 are: enumeration_representation_clause, record_representation_clause,
4221 and attribute_definition_clause for the following attributes:
4222 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4223 Object_Size, Size, Small, Stream_Size, and Value_Size.
4224 Note that this option should be used only for compiling -- the
4225 code is likely to malfunction at run time.
4226
4227 @item -gnatjnn
4228 @cindex @option{-gnatjnn} (@command{gcc})
4229 Reformat error messages to fit on nn character lines
4230
4231 @item -gnatk=@var{n}
4232 @cindex @option{-gnatk} (@command{gcc})
4233 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4234
4235 @item -gnatl
4236 @cindex @option{-gnatl} (@command{gcc})
4237 Output full source listing with embedded error messages.
4238
4239 @item -gnatL
4240 @cindex @option{-gnatL} (@command{gcc})
4241 Used in conjunction with -gnatG or -gnatD to intersperse original
4242 source lines (as comment lines with line numbers) in the expanded
4243 source output.
4244
4245 @item -gnatm=@var{n}
4246 @cindex @option{-gnatm} (@command{gcc})
4247 Limit number of detected error or warning messages to @var{n}
4248 where @var{n} is in the range 1..999999. The default setting if
4249 no switch is given is 9999. If the number of warnings reaches this
4250 limit, then a message is output and further warnings are suppressed,
4251 but the compilation is continued. If the number of error messages
4252 reaches this limit, then a message is output and the compilation
4253 is abandoned. The equal sign here is optional. A value of zero
4254 means that no limit applies.
4255
4256 @item -gnatn
4257 @cindex @option{-gnatn} (@command{gcc})
4258 Activate inlining for subprograms for which
4259 pragma @code{inline} is specified. This inlining is performed
4260 by the GCC back-end.
4261
4262 @item -gnatN
4263 @cindex @option{-gnatN} (@command{gcc})
4264 Activate front end inlining for subprograms for which
4265 pragma @code{Inline} is specified. This inlining is performed
4266 by the front end and will be visible in the
4267 @option{-gnatG} output.
4268
4269 When using a gcc-based back end (in practice this means using any version
4270 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4271 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4272 Historically front end inlining was more extensive than the gcc back end
4273 inlining, but that is no longer the case.
4274
4275 @item -gnato
4276 @cindex @option{-gnato} (@command{gcc})
4277 Enable numeric overflow checking (which is not normally enabled by
4278 default). Note that division by zero is a separate check that is not
4279 controlled by this switch (division by zero checking is on by default).
4280
4281 @item -gnatp
4282 @cindex @option{-gnatp} (@command{gcc})
4283 Suppress all checks. See @ref{Run-Time Checks} for details.
4284
4285 @item -gnatP
4286 @cindex @option{-gnatP} (@command{gcc})
4287 Enable polling. This is required on some systems (notably Windows NT) to
4288 obtain asynchronous abort and asynchronous transfer of control capability.
4289 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4290 details.
4291
4292 @item -gnatq
4293 @cindex @option{-gnatq} (@command{gcc})
4294 Don't quit. Try semantics, even if parse errors.
4295
4296 @item -gnatQ
4297 @cindex @option{-gnatQ} (@command{gcc})
4298 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4299
4300 @item -gnatr
4301 @cindex @option{-gnatr} (@command{gcc})
4302 Treat pragma Restrictions as Restriction_Warnings.
4303
4304 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4305 @cindex @option{-gnatR} (@command{gcc})
4306 Output representation information for declared types and objects.
4307
4308 @item -gnats
4309 @cindex @option{-gnats} (@command{gcc})
4310 Syntax check only.
4311
4312 @item -gnatS
4313 @cindex @option{-gnatS} (@command{gcc})
4314 Print package Standard.
4315
4316 @item -gnatt
4317 @cindex @option{-gnatt} (@command{gcc})
4318 Generate tree output file.
4319
4320 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4321 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4322 All compiler tables start at @var{nnn} times usual starting size.
4323
4324 @item -gnatu
4325 @cindex @option{-gnatu} (@command{gcc})
4326 List units for this compilation.
4327
4328 @item -gnatU
4329 @cindex @option{-gnatU} (@command{gcc})
4330 Tag all error messages with the unique string ``error:''
4331
4332 @item -gnatv
4333 @cindex @option{-gnatv} (@command{gcc})
4334 Verbose mode. Full error output with source lines to @file{stdout}.
4335
4336 @item -gnatV
4337 @cindex @option{-gnatV} (@command{gcc})
4338 Control level of validity checking (@pxref{Validity Checking}).
4339
4340 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4341 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4342 Warning mode where
4343 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4344 the exact warnings that
4345 are enabled or disabled (@pxref{Warning Message Control}).
4346
4347 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4348 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4349 Wide character encoding method
4350 @ifclear vms
4351 (@var{e}=n/h/u/s/e/8).
4352 @end ifclear
4353 @ifset vms
4354 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4355 @end ifset
4356
4357 @item -gnatx
4358 @cindex @option{-gnatx} (@command{gcc})
4359 Suppress generation of cross-reference information.
4360
4361 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4362 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4363 Enable built-in style checks (@pxref{Style Checking}).
4364
4365 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4366 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4367 Distribution stub generation and compilation
4368 @ifclear vms
4369 (@var{m}=r/c for receiver/caller stubs).
4370 @end ifclear
4371 @ifset vms
4372 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4373 to be generated and compiled).
4374 @end ifset
4375
4376 @item ^-I^/SEARCH=^@var{dir}
4377 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4378 @cindex RTL
4379 Direct GNAT to search the @var{dir} directory for source files needed by
4380 the current compilation
4381 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4382
4383 @item ^-I-^/NOCURRENT_DIRECTORY^
4384 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4385 @cindex RTL
4386 Except for the source file named in the command line, do not look for source
4387 files in the directory containing the source file named in the command line
4388 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4389
4390 @ifclear vms
4391 @item -mbig-switch
4392 @cindex @option{-mbig-switch} (@command{gcc})
4393 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4394 This standard gcc switch causes the compiler to use larger offsets in its
4395 jump table representation for @code{case} statements.
4396 This may result in less efficient code, but is sometimes necessary
4397 (for example on HP-UX targets)
4398 @cindex HP-UX and @option{-mbig-switch} option
4399 in order to compile large and/or nested @code{case} statements.
4400
4401 @item -o @var{file}
4402 @cindex @option{-o} (@command{gcc})
4403 This switch is used in @command{gcc} to redirect the generated object file
4404 and its associated ALI file. Beware of this switch with GNAT, because it may
4405 cause the object file and ALI file to have different names which in turn
4406 may confuse the binder and the linker.
4407 @end ifclear
4408
4409 @item -nostdinc
4410 @cindex @option{-nostdinc} (@command{gcc})
4411 Inhibit the search of the default location for the GNAT Run Time
4412 Library (RTL) source files.
4413
4414 @item -nostdlib
4415 @cindex @option{-nostdlib} (@command{gcc})
4416 Inhibit the search of the default location for the GNAT Run Time
4417 Library (RTL) ALI files.
4418
4419 @ifclear vms
4420 @item -O@ovar{n}
4421 @cindex @option{-O} (@command{gcc})
4422 @var{n} controls the optimization level.
4423
4424 @table @asis
4425 @item n = 0
4426 No optimization, the default setting if no @option{-O} appears
4427
4428 @item n = 1
4429 Normal optimization, the default if you specify @option{-O} without
4430 an operand. A good compromise between code quality and compilation
4431 time.
4432
4433 @item n = 2
4434 Extensive optimization, may improve execution time, possibly at the cost of
4435 substantially increased compilation time.
4436
4437 @item n = 3
4438 Same as @option{-O2}, and also includes inline expansion for small subprograms
4439 in the same unit.
4440
4441 @item n = s
4442 Optimize space usage
4443 @end table
4444
4445 @noindent
4446 See also @ref{Optimization Levels}.
4447 @end ifclear
4448
4449 @ifset vms
4450 @item  /NOOPTIMIZE
4451 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4452 Equivalent to @option{/OPTIMIZE=NONE}.
4453 This is the default behavior in the absence of an @option{/OPTIMIZE}
4454 qualifier.
4455
4456 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4457 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4458 Selects the level of optimization for your program. The supported
4459 keywords are as follows:
4460 @table @code
4461 @item   ALL
4462 Perform most optimizations, including those that
4463 are expensive.
4464 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4465 without keyword options.
4466
4467 @item   NONE
4468 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4469
4470 @item SOME
4471 Perform some optimizations, but omit ones that are costly.
4472
4473 @item   DEVELOPMENT
4474 Same as @code{SOME}.
4475
4476 @item INLINING
4477 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4478 automatic inlining of small subprograms within a unit
4479
4480 @item   UNROLL_LOOPS
4481 Try to unroll loops. This keyword may be specified together with
4482 any keyword above other than @code{NONE}. Loop unrolling
4483 usually, but not always, improves the performance of programs.
4484
4485 @item SPACE
4486 Optimize space usage
4487 @end table
4488
4489 @noindent
4490 See also @ref{Optimization Levels}.
4491 @end ifset
4492
4493 @ifclear vms
4494 @item -pass-exit-codes
4495 @cindex @option{-pass-exit-codes} (@command{gcc})
4496 Catch exit codes from the compiler and use the most meaningful as
4497 exit status.
4498 @end ifclear
4499
4500 @item --RTS=@var{rts-path}
4501 @cindex @option{--RTS} (@command{gcc})
4502 Specifies the default location of the runtime library. Same meaning as the
4503 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4504
4505 @item ^-S^/ASM^
4506 @cindex @option{^-S^/ASM^} (@command{gcc})
4507 ^Used in place of @option{-c} to^Used to^
4508 cause the assembler source file to be
4509 generated, using @file{^.s^.S^} as the extension,
4510 instead of the object file.
4511 This may be useful if you need to examine the generated assembly code.
4512
4513 @item ^-fverbose-asm^/VERBOSE_ASM^
4514 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4515 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4516 to cause the generated assembly code file to be annotated with variable
4517 names, making it significantly easier to follow.
4518
4519 @item ^-v^/VERBOSE^
4520 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4521 Show commands generated by the @command{gcc} driver. Normally used only for
4522 debugging purposes or if you need to be sure what version of the
4523 compiler you are executing.
4524
4525 @ifclear vms
4526 @item -V @var{ver}
4527 @cindex @option{-V} (@command{gcc})
4528 Execute @var{ver} version of the compiler. This is the @command{gcc}
4529 version, not the GNAT version.
4530 @end ifclear
4531
4532 @item ^-w^/NO_BACK_END_WARNINGS^
4533 @cindex @option{-w} (@command{gcc})
4534 Turn off warnings generated by the back end of the compiler. Use of
4535 this switch also causes the default for front end warnings to be set
4536 to suppress (as though @option{-gnatws} had appeared at the start of
4537 the options).
4538
4539 @end table
4540
4541 @ifclear vms
4542 @c Combining qualifiers does not work on VMS
4543 You may combine a sequence of GNAT switches into a single switch. For
4544 example, the combined switch
4545
4546 @cindex Combining GNAT switches
4547 @smallexample
4548 -gnatofi3
4549 @end smallexample
4550
4551 @noindent
4552 is equivalent to specifying the following sequence of switches:
4553
4554 @smallexample
4555 -gnato -gnatf -gnati3
4556 @end smallexample
4557 @end ifclear
4558
4559 @noindent
4560 The following restrictions apply to the combination of switches
4561 in this manner:
4562
4563 @itemize @bullet
4564 @item
4565 The switch @option{-gnatc} if combined with other switches must come
4566 first in the string.
4567
4568 @item
4569 The switch @option{-gnats} if combined with other switches must come
4570 first in the string.
4571
4572 @item
4573 The switches
4574 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4575 may not be combined with any other switches.
4576
4577 @ifclear vms
4578 @item
4579 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4580 switch), then all further characters in the switch are interpreted
4581 as style modifiers (see description of @option{-gnaty}).
4582
4583 @item
4584 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4585 switch), then all further characters in the switch are interpreted
4586 as debug flags (see description of @option{-gnatd}).
4587
4588 @item
4589 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4590 switch), then all further characters in the switch are interpreted
4591 as warning mode modifiers (see description of @option{-gnatw}).
4592
4593 @item
4594 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4595 switch), then all further characters in the switch are interpreted
4596 as validity checking options (@pxref{Validity Checking}).
4597 @end ifclear
4598 @end itemize
4599
4600 @node Output and Error Message Control
4601 @subsection Output and Error Message Control
4602 @findex stderr
4603
4604 @noindent
4605 The standard default format for error messages is called ``brief format''.
4606 Brief format messages are written to @file{stderr} (the standard error
4607 file) and have the following form:
4608
4609 @smallexample
4610 e.adb:3:04: Incorrect spelling of keyword "function"
4611 e.adb:4:20: ";" should be "is"
4612 @end smallexample
4613
4614 @noindent
4615 The first integer after the file name is the line number in the file,
4616 and the second integer is the column number within the line.
4617 @ifclear vms
4618 @code{GPS} can parse the error messages
4619 and point to the referenced character.
4620 @end ifclear
4621 The following switches provide control over the error message
4622 format:
4623
4624 @table @option
4625 @c !sort!
4626 @item -gnatv
4627 @cindex @option{-gnatv} (@command{gcc})
4628 @findex stdout
4629 @ifclear vms
4630 The v stands for verbose.
4631 @end ifclear
4632 The effect of this setting is to write long-format error
4633 messages to @file{stdout} (the standard output file.
4634 The same program compiled with the
4635 @option{-gnatv} switch would generate:
4636
4637 @smallexample
4638 @cartouche
4639 3. funcion X (Q : Integer)
4640    |
4641 >>> Incorrect spelling of keyword "function"
4642 4. return Integer;
4643                  |
4644 >>> ";" should be "is"
4645 @end cartouche
4646 @end smallexample
4647
4648 @noindent
4649 The vertical bar indicates the location of the error, and the @samp{>>>}
4650 prefix can be used to search for error messages. When this switch is
4651 used the only source lines output are those with errors.
4652
4653 @item -gnatl
4654 @cindex @option{-gnatl} (@command{gcc})
4655 @ifclear vms
4656 The @code{l} stands for list.
4657 @end ifclear
4658 This switch causes a full listing of
4659 the file to be generated. In the case where a body is
4660 compiled, the corresponding spec is also listed, along
4661 with any subunits. Typical output from compiling a package
4662 body @file{p.adb} might look like:
4663
4664 @smallexample @c ada
4665 @cartouche
4666  Compiling: p.adb
4667
4668      1. package body p is
4669      2.    procedure a;
4670      3.    procedure a is separate;
4671      4. begin
4672      5.    null
4673                |
4674         >>> missing ";"
4675
4676      6. end;
4677
4678 Compiling: p.ads
4679
4680      1. package p is
4681      2.    pragma Elaborate_Body
4682                                 |
4683         >>> missing ";"
4684
4685      3. end p;
4686
4687 Compiling: p-a.adb
4688
4689      1. separate p
4690                 |
4691         >>> missing "("
4692
4693      2. procedure a is
4694      3. begin
4695      4.    null
4696                |
4697         >>> missing ";"
4698
4699      5. end;
4700 @end cartouche
4701 @end smallexample
4702
4703 @noindent
4704 @findex stderr
4705 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4706 standard output is redirected, a brief summary is written to
4707 @file{stderr} (standard error) giving the number of error messages and
4708 warning messages generated.
4709
4710 @item -^gnatl^OUTPUT_FILE^=file
4711 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4712 This has the same effect as @option{-gnatl} except that the output is
4713 written to a file instead of to standard output. If the given name
4714 @file{fname} does not start with a period, then it is the full name
4715 of the file to be written. If @file{fname} is an extension, it is
4716 appended to the name of the file being compiled. For example, if
4717 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4718 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4719
4720 @item -gnatU
4721 @cindex @option{-gnatU} (@command{gcc})
4722 This switch forces all error messages to be preceded by the unique
4723 string ``error:''. This means that error messages take a few more
4724 characters in space, but allows easy searching for and identification
4725 of error messages.
4726
4727 @item -gnatb
4728 @cindex @option{-gnatb} (@command{gcc})
4729 @ifclear vms
4730 The @code{b} stands for brief.
4731 @end ifclear
4732 This switch causes GNAT to generate the
4733 brief format error messages to @file{stderr} (the standard error
4734 file) as well as the verbose
4735 format message or full listing (which as usual is written to
4736 @file{stdout} (the standard output file).
4737
4738 @item -gnatm=@var{n}
4739 @cindex @option{-gnatm} (@command{gcc})
4740 @ifclear vms
4741 The @code{m} stands for maximum.
4742 @end ifclear
4743 @var{n} is a decimal integer in the
4744 range of 1 to 999999 and limits the number of error or warning
4745 messages to be generated. For example, using
4746 @option{-gnatm2} might yield
4747
4748 @smallexample
4749 e.adb:3:04: Incorrect spelling of keyword "function"
4750 e.adb:5:35: missing ".."
4751 fatal error: maximum number of errors detected
4752 compilation abandoned
4753 @end smallexample
4754
4755 @noindent
4756 The default setting if
4757 no switch is given is 9999. If the number of warnings reaches this
4758 limit, then a message is output and further warnings are suppressed,
4759 but the compilation is continued. If the number of error messages
4760 reaches this limit, then a message is output and the compilation
4761 is abandoned. A value of zero means that no limit applies.
4762
4763 @noindent
4764 Note that the equal sign is optional, so the switches
4765 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4766
4767 @item -gnatf
4768 @cindex @option{-gnatf} (@command{gcc})
4769 @cindex Error messages, suppressing
4770 @ifclear vms
4771 The @code{f} stands for full.
4772 @end ifclear
4773 Normally, the compiler suppresses error messages that are likely to be
4774 redundant. This switch causes all error
4775 messages to be generated. In particular, in the case of
4776 references to undefined variables. If a given variable is referenced
4777 several times, the normal format of messages is
4778 @smallexample
4779 e.adb:7:07: "V" is undefined (more references follow)
4780 @end smallexample
4781
4782 @noindent
4783 where the parenthetical comment warns that there are additional
4784 references to the variable @code{V}. Compiling the same program with the
4785 @option{-gnatf} switch yields
4786
4787 @smallexample
4788 e.adb:7:07: "V" is undefined
4789 e.adb:8:07: "V" is undefined
4790 e.adb:8:12: "V" is undefined
4791 e.adb:8:16: "V" is undefined
4792 e.adb:9:07: "V" is undefined
4793 e.adb:9:12: "V" is undefined
4794 @end smallexample
4795
4796 @noindent
4797 The @option{-gnatf} switch also generates additional information for
4798 some error messages.  Some examples are:
4799
4800 @itemize @bullet
4801 @item
4802 Details on possibly non-portable unchecked conversion
4803 @item
4804 List possible interpretations for ambiguous calls
4805 @item
4806 Additional details on incorrect parameters
4807 @end itemize
4808
4809 @item -gnatjnn
4810 @cindex @option{-gnatjnn} (@command{gcc})
4811 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4812 with continuation lines are treated as though the continuation lines were
4813 separate messages (and so a warning with two continuation lines counts as
4814 three warnings, and is listed as three separate messages).
4815
4816 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4817 messages are output in a different manner. A message and all its continuation
4818 lines are treated as a unit, and count as only one warning or message in the
4819 statistics totals. Furthermore, the message is reformatted so that no line
4820 is longer than nn characters.
4821
4822 @item -gnatq
4823 @cindex @option{-gnatq} (@command{gcc})
4824 @ifclear vms
4825 The @code{q} stands for quit (really ``don't quit'').
4826 @end ifclear
4827 In normal operation mode, the compiler first parses the program and
4828 determines if there are any syntax errors. If there are, appropriate
4829 error messages are generated and compilation is immediately terminated.
4830 This switch tells
4831 GNAT to continue with semantic analysis even if syntax errors have been
4832 found. This may enable the detection of more errors in a single run. On
4833 the other hand, the semantic analyzer is more likely to encounter some
4834 internal fatal error when given a syntactically invalid tree.
4835
4836 @item -gnatQ
4837 @cindex @option{-gnatQ} (@command{gcc})
4838 In normal operation mode, the @file{ALI} file is not generated if any
4839 illegalities are detected in the program. The use of @option{-gnatQ} forces
4840 generation of the @file{ALI} file. This file is marked as being in
4841 error, so it cannot be used for binding purposes, but it does contain
4842 reasonably complete cross-reference information, and thus may be useful
4843 for use by tools (e.g., semantic browsing tools or integrated development
4844 environments) that are driven from the @file{ALI} file. This switch
4845 implies @option{-gnatq}, since the semantic phase must be run to get a
4846 meaningful ALI file.
4847
4848 In addition, if @option{-gnatt} is also specified, then the tree file is
4849 generated even if there are illegalities. It may be useful in this case
4850 to also specify @option{-gnatq} to ensure that full semantic processing
4851 occurs. The resulting tree file can be processed by ASIS, for the purpose
4852 of providing partial information about illegal units, but if the error
4853 causes the tree to be badly malformed, then ASIS may crash during the
4854 analysis.
4855
4856 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4857 being in error, @command{gnatmake} will attempt to recompile the source when it
4858 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4859
4860 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4861 since ALI files are never generated if @option{-gnats} is set.
4862
4863 @end table
4864
4865 @node Warning Message Control
4866 @subsection Warning Message Control
4867 @cindex Warning messages
4868 @noindent
4869 In addition to error messages, which correspond to illegalities as defined
4870 in the Ada Reference Manual, the compiler detects two kinds of warning
4871 situations.
4872
4873 First, the compiler considers some constructs suspicious and generates a
4874 warning message to alert you to a possible error. Second, if the
4875 compiler detects a situation that is sure to raise an exception at
4876 run time, it generates a warning message. The following shows an example
4877 of warning messages:
4878 @smallexample
4879 e.adb:4:24: warning: creation of object may raise Storage_Error
4880 e.adb:10:17: warning: static value out of range
4881 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4882 @end smallexample
4883
4884 @noindent
4885 GNAT considers a large number of situations as appropriate
4886 for the generation of warning messages. As always, warnings are not
4887 definite indications of errors. For example, if you do an out-of-range
4888 assignment with the deliberate intention of raising a
4889 @code{Constraint_Error} exception, then the warning that may be
4890 issued does not indicate an error. Some of the situations for which GNAT
4891 issues warnings (at least some of the time) are given in the following
4892 list. This list is not complete, and new warnings are often added to
4893 subsequent versions of GNAT. The list is intended to give a general idea
4894 of the kinds of warnings that are generated.
4895
4896 @itemize @bullet
4897 @item
4898 Possible infinitely recursive calls
4899
4900 @item
4901 Out-of-range values being assigned
4902
4903 @item
4904 Possible order of elaboration problems
4905
4906 @item
4907 Assertions (pragma Assert) that are sure to fail
4908
4909 @item
4910 Unreachable code
4911
4912 @item
4913 Address clauses with possibly unaligned values, or where an attempt is
4914 made to overlay a smaller variable with a larger one.
4915
4916 @item
4917 Fixed-point type declarations with a null range
4918
4919 @item
4920 Direct_IO or Sequential_IO instantiated with a type that has access values
4921
4922 @item
4923 Variables that are never assigned a value
4924
4925 @item
4926 Variables that are referenced before being initialized
4927
4928 @item
4929 Task entries with no corresponding @code{accept} statement
4930
4931 @item
4932 Duplicate accepts for the same task entry in a @code{select}
4933
4934 @item
4935 Objects that take too much storage
4936
4937 @item
4938 Unchecked conversion between types of differing sizes
4939
4940 @item
4941 Missing @code{return} statement along some execution path in a function
4942
4943 @item
4944 Incorrect (unrecognized) pragmas
4945
4946 @item
4947 Incorrect external names
4948
4949 @item
4950 Allocation from empty storage pool
4951
4952 @item
4953 Potentially blocking operation in protected type
4954
4955 @item
4956 Suspicious parenthesization of expressions
4957
4958 @item
4959 Mismatching bounds in an aggregate
4960
4961 @item
4962 Attempt to return local value by reference
4963
4964 @item
4965 Premature instantiation of a generic body
4966
4967 @item
4968 Attempt to pack aliased components
4969
4970 @item
4971 Out of bounds array subscripts
4972
4973 @item
4974 Wrong length on string assignment
4975
4976 @item
4977 Violations of style rules if style checking is enabled
4978
4979 @item
4980 Unused @code{with} clauses
4981
4982 @item
4983 @code{Bit_Order} usage that does not have any effect
4984
4985 @item
4986 @code{Standard.Duration} used to resolve universal fixed expression
4987
4988 @item
4989 Dereference of possibly null value
4990
4991 @item
4992 Declaration that is likely to cause storage error
4993
4994 @item
4995 Internal GNAT unit @code{with}'ed by application unit
4996
4997 @item
4998 Values known to be out of range at compile time
4999
5000 @item
5001 Unreferenced labels and variables
5002
5003 @item
5004 Address overlays that could clobber memory
5005
5006 @item
5007 Unexpected initialization when address clause present
5008
5009 @item
5010 Bad alignment for address clause
5011
5012 @item
5013 Useless type conversions
5014
5015 @item
5016 Redundant assignment statements and other redundant constructs
5017
5018 @item
5019 Useless exception handlers
5020
5021 @item
5022 Accidental hiding of name by child unit
5023
5024 @item
5025 Access before elaboration detected at compile time
5026
5027 @item
5028 A range in a @code{for} loop that is known to be null or might be null
5029
5030 @end itemize
5031
5032 @noindent
5033 The following section lists compiler switches that are available
5034 to control the handling of warning messages. It is also possible
5035 to exercise much finer control over what warnings are issued and
5036 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5037 gnat_rm, GNAT Reference manual}.
5038
5039 @table @option
5040 @c !sort!
5041 @item -gnatwa
5042 @emph{Activate all optional errors.}
5043 @cindex @option{-gnatwa} (@command{gcc})
5044 This switch activates most optional warning messages, see remaining list
5045 in this section for details on optional warning messages that can be
5046 individually controlled.  The warnings that are not turned on by this
5047 switch are
5048 @option{-gnatwd} (implicit dereferencing),
5049 @option{-gnatwh} (hiding),
5050 @option{-gnatwl} (elaboration warnings),
5051 @option{-gnatw.o} (warn on values set by out parameters ignored)
5052 and @option{-gnatwt} (tracking of deleted conditional code).
5053 All other optional warnings are turned on.
5054
5055 @item -gnatwA
5056 @emph{Suppress all optional errors.}
5057 @cindex @option{-gnatwA} (@command{gcc})
5058 This switch suppresses all optional warning messages, see remaining list
5059 in this section for details on optional warning messages that can be
5060 individually controlled.
5061
5062 @item -gnatw.a
5063 @emph{Activate warnings on failing assertions.}
5064 @cindex @option{-gnatw.a} (@command{gcc})
5065 @cindex Assert failures
5066 This switch activates warnings for assertions where the compiler can tell at
5067 compile time that the assertion will fail. Note that this warning is given
5068 even if assertions are disabled. The default is that such warnings are
5069 generated.
5070
5071 @item -gnatw.A
5072 @emph{Suppress warnings on failing assertions.}
5073 @cindex @option{-gnatw.A} (@command{gcc})
5074 @cindex Assert failures
5075 This switch suppresses warnings for assertions where the compiler can tell at
5076 compile time that the assertion will fail.
5077
5078 @item -gnatwb
5079 @emph{Activate warnings on bad fixed values.}
5080 @cindex @option{-gnatwb} (@command{gcc})
5081 @cindex Bad fixed values
5082 @cindex Fixed-point Small value
5083 @cindex Small value
5084 This switch activates warnings for static fixed-point expressions whose
5085 value is not an exact multiple of Small. Such values are implementation
5086 dependent, since an implementation is free to choose either of the multiples
5087 that surround the value. GNAT always chooses the closer one, but this is not
5088 required behavior, and it is better to specify a value that is an exact
5089 multiple, ensuring predictable execution. The default is that such warnings
5090 are not generated.
5091
5092 @item -gnatwB
5093 @emph{Suppress warnings on bad fixed values.}
5094 @cindex @option{-gnatwB} (@command{gcc})
5095 This switch suppresses warnings for static fixed-point expressions whose
5096 value is not an exact multiple of Small.
5097
5098 @item -gnatw.b
5099 @emph{Activate warnings on biased representation.}
5100 @cindex @option{-gnatw.b} (@command{gcc})
5101 @cindex Biased representation
5102 This switch activates warnings when a size clause, value size clause, component
5103 clause, or component size clause forces the use of biased representation for an
5104 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5105 to represent 10/11). The default is that such warnings are generated.
5106
5107 @item -gnatw.B
5108 @emph{Suppress warnings on biased representation.}
5109 @cindex @option{-gnatwB} (@command{gcc})
5110 This switch suppresses warnings for representation clauses that force the use
5111 of biased representation.
5112
5113 @item -gnatwc
5114 @emph{Activate warnings on conditionals.}
5115 @cindex @option{-gnatwc} (@command{gcc})
5116 @cindex Conditionals, constant
5117 This switch activates warnings for conditional expressions used in
5118 tests that are known to be True or False at compile time. The default
5119 is that such warnings are not generated.
5120 Note that this warning does
5121 not get issued for the use of boolean variables or constants whose
5122 values are known at compile time, since this is a standard technique
5123 for conditional compilation in Ada, and this would generate too many
5124 false positive warnings.
5125
5126 This warning option also activates a special test for comparisons using
5127 the operators ``>='' and`` <=''.
5128 If the compiler can tell that only the equality condition is possible,
5129 then it will warn that the ``>'' or ``<'' part of the test
5130 is useless and that the operator could be replaced by ``=''.
5131 An example would be comparing a @code{Natural} variable <= 0.
5132
5133 This warning option also generates warnings if
5134 one or both tests is optimized away in a membership test for integer
5135 values if the result can be determined at compile time. Range tests on
5136 enumeration types are not included, since it is common for such tests
5137 to include an end point.
5138
5139 This warning can also be turned on using @option{-gnatwa}.
5140
5141 @item -gnatwC
5142 @emph{Suppress warnings on conditionals.}
5143 @cindex @option{-gnatwC} (@command{gcc})
5144 This switch suppresses warnings for conditional expressions used in
5145 tests that are known to be True or False at compile time.
5146
5147 @item -gnatw.c
5148 @emph{Activate warnings on missing component clauses.}
5149 @cindex @option{-gnatw.c} (@command{gcc})
5150 @cindex Component clause, missing
5151 This switch activates warnings for record components where a record
5152 representation clause is present and has component clauses for the
5153 majority, but not all, of the components. A warning is given for each
5154 component for which no component clause is present.
5155
5156 This warning can also be turned on using @option{-gnatwa}.
5157
5158 @item -gnatw.C
5159 @emph{Suppress warnings on missing component clauses.}
5160 @cindex @option{-gnatwC} (@command{gcc})
5161 This switch suppresses warnings for record components that are
5162 missing a component clause in the situation described above.
5163
5164 @item -gnatwd
5165 @emph{Activate warnings on implicit dereferencing.}
5166 @cindex @option{-gnatwd} (@command{gcc})
5167 If this switch is set, then the use of a prefix of an access type
5168 in an indexed component, slice, or selected component without an
5169 explicit @code{.all} will generate a warning. With this warning
5170 enabled, access checks occur only at points where an explicit
5171 @code{.all} appears in the source code (assuming no warnings are
5172 generated as a result of this switch). The default is that such
5173 warnings are not generated.
5174 Note that @option{-gnatwa} does not affect the setting of
5175 this warning option.
5176
5177 @item -gnatwD
5178 @emph{Suppress warnings on implicit dereferencing.}
5179 @cindex @option{-gnatwD} (@command{gcc})
5180 @cindex Implicit dereferencing
5181 @cindex Dereferencing, implicit
5182 This switch suppresses warnings for implicit dereferences in
5183 indexed components, slices, and selected components.
5184
5185 @item -gnatwe
5186 @emph{Treat warnings as errors.}
5187 @cindex @option{-gnatwe} (@command{gcc})
5188 @cindex Warnings, treat as error
5189 This switch causes warning messages to be treated as errors.
5190 The warning string still appears, but the warning messages are counted
5191 as errors, and prevent the generation of an object file.
5192
5193 @item -gnatw.e
5194 @emph{Activate every optional warning}
5195 @cindex @option{-gnatw.e} (@command{gcc})
5196 @cindex Warnings, activate every optional warning
5197 This switch activates all optional warnings, including those which
5198 are not activated by @code{-gnatwa}.
5199
5200 @item -gnatwf
5201 @emph{Activate warnings on unreferenced formals.}
5202 @cindex @option{-gnatwf} (@command{gcc})
5203 @cindex Formals, unreferenced
5204 This switch causes a warning to be generated if a formal parameter
5205 is not referenced in the body of the subprogram. This warning can
5206 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5207 default is that these warnings are not generated.
5208
5209 @item -gnatwF
5210 @emph{Suppress warnings on unreferenced formals.}
5211 @cindex @option{-gnatwF} (@command{gcc})
5212 This switch suppresses warnings for unreferenced formal
5213 parameters. Note that the
5214 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5215 effect of warning on unreferenced entities other than subprogram
5216 formals.
5217
5218 @item -gnatwg
5219 @emph{Activate warnings on unrecognized pragmas.}
5220 @cindex @option{-gnatwg} (@command{gcc})
5221 @cindex Pragmas, unrecognized
5222 This switch causes a warning to be generated if an unrecognized
5223 pragma is encountered. Apart from issuing this warning, the
5224 pragma is ignored and has no effect. This warning can
5225 also be turned on using @option{-gnatwa}. The default
5226 is that such warnings are issued (satisfying the Ada Reference
5227 Manual requirement that such warnings appear).
5228
5229 @item -gnatwG
5230 @emph{Suppress warnings on unrecognized pragmas.}
5231 @cindex @option{-gnatwG} (@command{gcc})
5232 This switch suppresses warnings for unrecognized pragmas.
5233
5234 @item -gnatwh
5235 @emph{Activate warnings on hiding.}
5236 @cindex @option{-gnatwh} (@command{gcc})
5237 @cindex Hiding of Declarations
5238 This switch activates warnings on hiding declarations.
5239 A declaration is considered hiding
5240 if it is for a non-overloadable entity, and it declares an entity with the
5241 same name as some other entity that is directly or use-visible. The default
5242 is that such warnings are not generated.
5243 Note that @option{-gnatwa} does not affect the setting of this warning option.
5244
5245 @item -gnatwH
5246 @emph{Suppress warnings on hiding.}
5247 @cindex @option{-gnatwH} (@command{gcc})
5248 This switch suppresses warnings on hiding declarations.
5249
5250 @item -gnatwi
5251 @emph{Activate warnings on implementation units.}
5252 @cindex @option{-gnatwi} (@command{gcc})
5253 This switch activates warnings for a @code{with} of an internal GNAT
5254 implementation unit, defined as any unit from the @code{Ada},
5255 @code{Interfaces}, @code{GNAT},
5256 ^^@code{DEC},^ or @code{System}
5257 hierarchies that is not
5258 documented in either the Ada Reference Manual or the GNAT
5259 Programmer's Reference Manual. Such units are intended only
5260 for internal implementation purposes and should not be @code{with}'ed
5261 by user programs. The default is that such warnings are generated
5262 This warning can also be turned on using @option{-gnatwa}.
5263
5264 @item -gnatwI
5265 @emph{Disable warnings on implementation units.}
5266 @cindex @option{-gnatwI} (@command{gcc})
5267 This switch disables warnings for a @code{with} of an internal GNAT
5268 implementation unit.
5269
5270 @item -gnatwj
5271 @emph{Activate warnings on obsolescent features (Annex J).}
5272 @cindex @option{-gnatwj} (@command{gcc})
5273 @cindex Features, obsolescent
5274 @cindex Obsolescent features
5275 If this warning option is activated, then warnings are generated for
5276 calls to subprograms marked with @code{pragma Obsolescent} and
5277 for use of features in Annex J of the Ada Reference Manual. In the
5278 case of Annex J, not all features are flagged. In particular use
5279 of the renamed packages (like @code{Text_IO}) and use of package
5280 @code{ASCII} are not flagged, since these are very common and
5281 would generate many annoying positive warnings. The default is that
5282 such warnings are not generated. This warning is also turned on by
5283 the use of @option{-gnatwa}.
5284
5285 In addition to the above cases, warnings are also generated for
5286 GNAT features that have been provided in past versions but which
5287 have been superseded (typically by features in the new Ada standard).
5288 For example, @code{pragma Ravenscar} will be flagged since its
5289 function is replaced by @code{pragma Profile(Ravenscar)}.
5290
5291 Note that this warning option functions differently from the
5292 restriction @code{No_Obsolescent_Features} in two respects.
5293 First, the restriction applies only to annex J features.
5294 Second, the restriction does flag uses of package @code{ASCII}.
5295
5296 @item -gnatwJ
5297 @emph{Suppress warnings on obsolescent features (Annex J).}
5298 @cindex @option{-gnatwJ} (@command{gcc})
5299 This switch disables warnings on use of obsolescent features.
5300
5301 @item -gnatwk
5302 @emph{Activate warnings on variables that could be constants.}
5303 @cindex @option{-gnatwk} (@command{gcc})
5304 This switch activates warnings for variables that are initialized but
5305 never modified, and then could be declared constants. The default is that
5306 such warnings are not given.
5307 This warning can also be turned on using @option{-gnatwa}.
5308
5309 @item -gnatwK
5310 @emph{Suppress warnings on variables that could be constants.}
5311 @cindex @option{-gnatwK} (@command{gcc})
5312 This switch disables warnings on variables that could be declared constants.
5313
5314 @item -gnatwl
5315 @emph{Activate warnings for elaboration pragmas.}
5316 @cindex @option{-gnatwl} (@command{gcc})
5317 @cindex Elaboration, warnings
5318 This switch activates warnings on missing
5319 @code{Elaborate_All} and @code{Elaborate} pragmas.
5320 See the section in this guide on elaboration checking for details on
5321 when such pragmas should be used. In dynamic elaboration mode, this switch
5322 generations warnings about the need to add elaboration pragmas. Note however,
5323 that if you blindly follow these warnings, and add @code{Elaborate_All}
5324 warnings wherever they are recommended, you basically end up with the
5325 equivalent of the static elaboration model, which may not be what you want for
5326 legacy code for which the static model does not work.
5327
5328 For the static model, the messages generated are labeled "info:" (for
5329 information messages). They are not warnings to add elaboration pragmas,
5330 merely informational messages showing what implicit elaboration pragmas
5331 have been added, for use in analyzing elaboration circularity problems.
5332
5333 Warnings are also generated if you
5334 are using the static mode of elaboration, and a @code{pragma Elaborate}
5335 is encountered. The default is that such warnings
5336 are not generated.
5337 This warning is not automatically turned on by the use of @option{-gnatwa}.
5338
5339 @item -gnatwL
5340 @emph{Suppress warnings for elaboration pragmas.}
5341 @cindex @option{-gnatwL} (@command{gcc})
5342 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5343 See the section in this guide on elaboration checking for details on
5344 when such pragmas should be used.
5345
5346 @item -gnatwm
5347 @emph{Activate warnings on modified but unreferenced variables.}
5348 @cindex @option{-gnatwm} (@command{gcc})
5349 This switch activates warnings for variables that are assigned (using
5350 an initialization value or with one or more assignment statements) but
5351 whose value is never read. The warning is suppressed for volatile
5352 variables and also for variables that are renamings of other variables
5353 or for which an address clause is given.
5354 This warning can also be turned on using @option{-gnatwa}.
5355 The default is that these warnings are not given.
5356
5357 @item -gnatwM
5358 @emph{Disable warnings on modified but unreferenced variables.}
5359 @cindex @option{-gnatwM} (@command{gcc})
5360 This switch disables warnings for variables that are assigned or
5361 initialized, but never read.
5362
5363 @item -gnatw.m
5364 @emph{Activate warnings on suspicious modulus values.}
5365 @cindex @option{-gnatw.m} (@command{gcc})
5366 This switch activates warnings for modulus values that seem suspicious.
5367 The cases caught are where the size is the same as the modulus (e.g.
5368 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5369 with no size clause. The guess in both cases is that 2**x was intended
5370 rather than x. The default is that these warnings are given.
5371
5372 @item -gnatw.M
5373 @emph{Disable warnings on suspicious modulus values.}
5374 @cindex @option{-gnatw.M} (@command{gcc})
5375 This switch disables warnings for suspicious modulus values.
5376
5377 @item -gnatwn
5378 @emph{Set normal warnings mode.}
5379 @cindex @option{-gnatwn} (@command{gcc})
5380 This switch sets normal warning mode, in which enabled warnings are
5381 issued and treated as warnings rather than errors. This is the default
5382 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5383 an explicit @option{-gnatws} or
5384 @option{-gnatwe}. It also cancels the effect of the
5385 implicit @option{-gnatwe} that is activated by the
5386 use of @option{-gnatg}.
5387
5388 @item -gnatwo
5389 @emph{Activate warnings on address clause overlays.}
5390 @cindex @option{-gnatwo} (@command{gcc})
5391 @cindex Address Clauses, warnings
5392 This switch activates warnings for possibly unintended initialization
5393 effects of defining address clauses that cause one variable to overlap
5394 another. The default is that such warnings are generated.
5395 This warning can also be turned on using @option{-gnatwa}.
5396
5397 @item -gnatwO
5398 @emph{Suppress warnings on address clause overlays.}
5399 @cindex @option{-gnatwO} (@command{gcc})
5400 This switch suppresses warnings on possibly unintended initialization
5401 effects of defining address clauses that cause one variable to overlap
5402 another.
5403
5404 @item -gnatw.o
5405 @emph{Activate warnings on modified but unreferenced out parameters.}
5406 @cindex @option{-gnatw.o} (@command{gcc})
5407 This switch activates warnings for variables that are modified by using
5408 them as actuals for a call to a procedure with an out mode formal, where
5409 the resulting assigned value is never read. It is applicable in the case
5410 where there is more than one out mode formal. If there is only one out
5411 mode formal, the warning is issued by default (controlled by -gnatwu).
5412 The warning is suppressed for volatile
5413 variables and also for variables that are renamings of other variables
5414 or for which an address clause is given.
5415 The default is that these warnings are not given. Note that this warning
5416 is not included in -gnatwa, it must be activated explicitly.
5417
5418 @item -gnatw.O
5419 @emph{Disable warnings on modified but unreferenced out parameters.}
5420 @cindex @option{-gnatw.O} (@command{gcc})
5421 This switch suppresses warnings for variables that are modified by using
5422 them as actuals for a call to a procedure with an out mode formal, where
5423 the resulting assigned value is never read.
5424
5425 @item -gnatwp
5426 @emph{Activate warnings on ineffective pragma Inlines.}
5427 @cindex @option{-gnatwp} (@command{gcc})
5428 @cindex Inlining, warnings
5429 This switch activates warnings for failure of front end inlining
5430 (activated by @option{-gnatN}) to inline a particular call. There are
5431 many reasons for not being able to inline a call, including most
5432 commonly that the call is too complex to inline. The default is
5433 that such warnings are not given.
5434 This warning can also be turned on using @option{-gnatwa}.
5435 Warnings on ineffective inlining by the gcc back-end can be activated
5436 separately, using the gcc switch -Winline.
5437
5438 @item -gnatwP
5439 @emph{Suppress warnings on ineffective pragma Inlines.}
5440 @cindex @option{-gnatwP} (@command{gcc})
5441 This switch suppresses warnings on ineffective pragma Inlines. If the
5442 inlining mechanism cannot inline a call, it will simply ignore the
5443 request silently.
5444
5445 @item -gnatw.p
5446 @emph{Activate warnings on parameter ordering.}
5447 @cindex @option{-gnatw.p} (@command{gcc})
5448 @cindex Parameter order, warnings
5449 This switch activates warnings for cases of suspicious parameter
5450 ordering when the list of arguments are all simple identifiers that
5451 match the names of the formals, but are in a different order. The
5452 warning is suppressed if any use of named parameter notation is used,
5453 so this is the appropriate way to suppress a false positive (and
5454 serves to emphasize that the "misordering" is deliberate). The
5455 default is
5456 that such warnings are not given.
5457 This warning can also be turned on using @option{-gnatwa}.
5458
5459 @item -gnatw.P
5460 @emph{Suppress warnings on parameter ordering.}
5461 @cindex @option{-gnatw.P} (@command{gcc})
5462 This switch suppresses warnings on cases of suspicious parameter
5463 ordering.
5464
5465 @item -gnatwq
5466 @emph{Activate warnings on questionable missing parentheses.}
5467 @cindex @option{-gnatwq} (@command{gcc})
5468 @cindex Parentheses, warnings
5469 This switch activates warnings for cases where parentheses are not used and
5470 the result is potential ambiguity from a readers point of view. For example
5471 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5472 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5473 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5474 follow the rule of always parenthesizing to make the association clear, and
5475 this warning switch warns if such parentheses are not present. The default
5476 is that these warnings are given.
5477 This warning can also be turned on using @option{-gnatwa}.
5478
5479 @item -gnatwQ
5480 @emph{Suppress warnings on questionable missing parentheses.}
5481 @cindex @option{-gnatwQ} (@command{gcc})
5482 This switch suppresses warnings for cases where the association is not
5483 clear and the use of parentheses is preferred.
5484
5485 @item -gnatwr
5486 @emph{Activate warnings on redundant constructs.}
5487 @cindex @option{-gnatwr} (@command{gcc})
5488 This switch activates warnings for redundant constructs. The following
5489 is the current list of constructs regarded as redundant:
5490
5491 @itemize @bullet
5492 @item
5493 Assignment of an item to itself.
5494 @item
5495 Type conversion that converts an expression to its own type.
5496 @item
5497 Use of the attribute @code{Base} where @code{typ'Base} is the same
5498 as @code{typ}.
5499 @item
5500 Use of pragma @code{Pack} when all components are placed by a record
5501 representation clause.
5502 @item
5503 Exception handler containing only a reraise statement (raise with no
5504 operand) which has no effect.
5505 @item
5506 Use of the operator abs on an operand that is known at compile time
5507 to be non-negative
5508 @item
5509 Comparison of boolean expressions to an explicit True value.
5510 @end itemize
5511
5512 This warning can also be turned on using @option{-gnatwa}.
5513 The default is that warnings for redundant constructs are not given.
5514
5515 @item -gnatwR
5516 @emph{Suppress warnings on redundant constructs.}
5517 @cindex @option{-gnatwR} (@command{gcc})
5518 This switch suppresses warnings for redundant constructs.
5519
5520 @item -gnatw.r
5521 @emph{Activate warnings for object renaming function.}
5522 @cindex @option{-gnatw.r} (@command{gcc})
5523 This switch activates warnings for an object renaming that renames a
5524 function call, which is equivalent to a constant declaration (as
5525 opposed to renaming the function itself).  The default is that these
5526 warnings are given.  This warning can also be turned on using
5527 @option{-gnatwa}.
5528
5529 @item -gnatw.R
5530 @emph{Suppress warnings for object renaming function.}
5531 @cindex @option{-gnatwT} (@command{gcc})
5532 This switch suppresses warnings for object renaming function.
5533
5534 @item -gnatws
5535 @emph{Suppress all warnings.}
5536 @cindex @option{-gnatws} (@command{gcc})
5537 This switch completely suppresses the
5538 output of all warning messages from the GNAT front end.
5539 Note that it does not suppress warnings from the @command{gcc} back end.
5540 To suppress these back end warnings as well, use the switch @option{-w}
5541 in addition to @option{-gnatws}.
5542
5543 @item -gnatwt
5544 @emph{Activate warnings for tracking of deleted conditional code.}
5545 @cindex @option{-gnatwt} (@command{gcc})
5546 @cindex Deactivated code, warnings
5547 @cindex Deleted code, warnings
5548 This switch activates warnings for tracking of code in conditionals (IF and
5549 CASE statements) that is detected to be dead code which cannot be executed, and
5550 which is removed by the front end. This warning is off by default, and is not
5551 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5552 useful for detecting deactivated code in certified applications.
5553
5554 @item -gnatwT
5555 @emph{Suppress warnings for tracking of deleted conditional code.}
5556 @cindex @option{-gnatwT} (@command{gcc})
5557 This switch suppresses warnings for tracking of deleted conditional code.
5558
5559 @item -gnatwu
5560 @emph{Activate warnings on unused entities.}
5561 @cindex @option{-gnatwu} (@command{gcc})
5562 This switch activates warnings to be generated for entities that
5563 are declared but not referenced, and for units that are @code{with}'ed
5564 and not
5565 referenced. In the case of packages, a warning is also generated if
5566 no entities in the package are referenced. This means that if the package
5567 is referenced but the only references are in @code{use}
5568 clauses or @code{renames}
5569 declarations, a warning is still generated. A warning is also generated
5570 for a generic package that is @code{with}'ed but never instantiated.
5571 In the case where a package or subprogram body is compiled, and there
5572 is a @code{with} on the corresponding spec
5573 that is only referenced in the body,
5574 a warning is also generated, noting that the
5575 @code{with} can be moved to the body. The default is that
5576 such warnings are not generated.
5577 This switch also activates warnings on unreferenced formals
5578 (it includes the effect of @option{-gnatwf}).
5579 This warning can also be turned on using @option{-gnatwa}.
5580
5581 @item -gnatwU
5582 @emph{Suppress warnings on unused entities.}
5583 @cindex @option{-gnatwU} (@command{gcc})
5584 This switch suppresses warnings for unused entities and packages.
5585 It also turns off warnings on unreferenced formals (and thus includes
5586 the effect of @option{-gnatwF}).
5587
5588 @item -gnatwv
5589 @emph{Activate warnings on unassigned variables.}
5590 @cindex @option{-gnatwv} (@command{gcc})
5591 @cindex Unassigned variable warnings
5592 This switch activates warnings for access to variables which
5593 may not be properly initialized. The default is that
5594 such warnings are generated.
5595 This warning can also be turned on using @option{-gnatwa}.
5596
5597 @item -gnatwV
5598 @emph{Suppress warnings on unassigned variables.}
5599 @cindex @option{-gnatwV} (@command{gcc})
5600 This switch suppresses warnings for access to variables which
5601 may not be properly initialized.
5602 For variables of a composite type, the warning can also be suppressed in
5603 Ada 2005 by using a default initialization with a box. For example, if
5604 Table is an array of records whose components are only partially uninitialized,
5605 then the following code:
5606
5607 @smallexample @c ada
5608    Tab : Table := (others => <>);
5609 @end smallexample
5610
5611 will suppress warnings on subsequent statements that access components
5612 of variable Tab.
5613
5614 @item -gnatww
5615 @emph{Activate warnings on wrong low bound assumption.}
5616 @cindex @option{-gnatww} (@command{gcc})
5617 @cindex String indexing warnings
5618 This switch activates warnings for indexing an unconstrained string parameter
5619 with a literal or S'Length. This is a case where the code is assuming that the
5620 low bound is one, which is in general not true (for example when a slice is
5621 passed). The default is that such warnings are generated.
5622 This warning can also be turned on using @option{-gnatwa}.
5623
5624 @item -gnatwW
5625 @emph{Suppress warnings on wrong low bound assumption.}
5626 @cindex @option{-gnatwW} (@command{gcc})
5627 This switch suppresses warnings for indexing an unconstrained string parameter
5628 with a literal or S'Length. Note that this warning can also be suppressed
5629 in a particular case by adding an
5630 assertion that the lower bound is 1,
5631 as shown in the following example.
5632
5633 @smallexample @c ada
5634    procedure K (S : String) is
5635       pragma Assert (S'First = 1);
5636       @dots{}
5637 @end smallexample
5638
5639 @item -gnatw.w
5640 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5641 @cindex @option{-gnatw.w} (@command{gcc})
5642 @cindex Warnings Off control
5643 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5644 where either the pragma is entirely useless (because it suppresses no
5645 warnings), or it could be replaced by @code{pragma Unreferenced} or
5646 @code{pragma Unmodified}.The default is that these warnings are not given.
5647 Note that this warning is not included in -gnatwa, it must be
5648 activated explicitly.
5649
5650 @item -gnatw.W
5651 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5652 @cindex @option{-gnatw.W} (@command{gcc})
5653 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5654
5655 @item -gnatwx
5656 @emph{Activate warnings on Export/Import pragmas.}
5657 @cindex @option{-gnatwx} (@command{gcc})
5658 @cindex Export/Import pragma warnings
5659 This switch activates warnings on Export/Import pragmas when
5660 the compiler detects a possible conflict between the Ada and
5661 foreign language calling sequences. For example, the use of
5662 default parameters in a convention C procedure is dubious
5663 because the C compiler cannot supply the proper default, so
5664 a warning is issued. The default is that such warnings are
5665 generated.
5666 This warning can also be turned on using @option{-gnatwa}.
5667
5668 @item -gnatwX
5669 @emph{Suppress warnings on Export/Import pragmas.}
5670 @cindex @option{-gnatwX} (@command{gcc})
5671 This switch suppresses warnings on Export/Import pragmas.
5672 The sense of this is that you are telling the compiler that
5673 you know what you are doing in writing the pragma, and it
5674 should not complain at you.
5675
5676 @item -gnatw.x
5677 @emph{Activate warnings for No_Exception_Propagation mode.}
5678 @cindex @option{-gnatwm} (@command{gcc})
5679 This switch activates warnings for exception usage when pragma Restrictions
5680 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5681 explicit exception raises which are not covered by a local handler, and for
5682 exception handlers which do not cover a local raise. The default is that these
5683 warnings are not given.
5684
5685 @item -gnatw.X
5686 @emph{Disable warnings for No_Exception_Propagation mode.}
5687 This switch disables warnings for exception usage when pragma Restrictions
5688 (No_Exception_Propagation) is in effect.
5689
5690 @item -gnatwy
5691 @emph{Activate warnings for Ada 2005 compatibility issues.}
5692 @cindex @option{-gnatwy} (@command{gcc})
5693 @cindex Ada 2005 compatibility issues warnings
5694 For the most part Ada 2005 is upwards compatible with Ada 95,
5695 but there are some exceptions (for example the fact that
5696 @code{interface} is now a reserved word in Ada 2005). This
5697 switch activates several warnings to help in identifying
5698 and correcting such incompatibilities. The default is that
5699 these warnings are generated. Note that at one point Ada 2005
5700 was called Ada 0Y, hence the choice of character.
5701 This warning can also be turned on using @option{-gnatwa}.
5702
5703 @item -gnatwY
5704 @emph{Disable warnings for Ada 2005 compatibility issues.}
5705 @cindex @option{-gnatwY} (@command{gcc})
5706 @cindex Ada 2005 compatibility issues warnings
5707 This switch suppresses several warnings intended to help in identifying
5708 incompatibilities between Ada 95 and Ada 2005.
5709
5710 @item -gnatwz
5711 @emph{Activate warnings on unchecked conversions.}
5712 @cindex @option{-gnatwz} (@command{gcc})
5713 @cindex Unchecked_Conversion warnings
5714 This switch activates warnings for unchecked conversions
5715 where the types are known at compile time to have different
5716 sizes. The default
5717 is that such warnings are generated. Warnings are also
5718 generated for subprogram pointers with different conventions,
5719 and, on VMS only, for data pointers with different conventions.
5720 This warning can also be turned on using @option{-gnatwa}.
5721
5722 @item -gnatwZ
5723 @emph{Suppress warnings on unchecked conversions.}
5724 @cindex @option{-gnatwZ} (@command{gcc})
5725 This switch suppresses warnings for unchecked conversions
5726 where the types are known at compile time to have different
5727 sizes or conventions.
5728
5729 @item ^-Wunused^WARNINGS=UNUSED^
5730 @cindex @option{-Wunused}
5731 The warnings controlled by the @option{-gnatw} switch are generated by
5732 the front end of the compiler. The @option{GCC} back end can provide
5733 additional warnings and they are controlled by the @option{-W} switch.
5734 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5735 warnings for entities that are declared but not referenced.
5736
5737 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5738 @cindex @option{-Wuninitialized}
5739 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5740 the back end warning for uninitialized variables. This switch must be
5741 used in conjunction with an optimization level greater than zero.
5742
5743 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5744 @cindex @option{-Wall}
5745 This switch enables all the above warnings from the @option{GCC} back end.
5746 The code generator detects a number of warning situations that are missed
5747 by the @option{GNAT} front end, and this switch can be used to activate them.
5748 The use of this switch also sets the default front end warning mode to
5749 @option{-gnatwa}, that is, most front end warnings activated as well.
5750
5751 @item ^-w^/NO_BACK_END_WARNINGS^
5752 @cindex @option{-w}
5753 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5754 The use of this switch also sets the default front end warning mode to
5755 @option{-gnatws}, that is, front end warnings suppressed as well.
5756
5757 @end table
5758
5759 @noindent
5760 @ifclear vms
5761 A string of warning parameters can be used in the same parameter. For example:
5762
5763 @smallexample
5764 -gnatwaLe
5765 @end smallexample
5766
5767 @noindent
5768 will turn on all optional warnings except for elaboration pragma warnings,
5769 and also specify that warnings should be treated as errors.
5770 @end ifclear
5771 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5772
5773 @table @option
5774 @c !sort!
5775 @item -gnatwC
5776 @item -gnatwD
5777 @item -gnatwF
5778 @item -gnatwg
5779 @item -gnatwH
5780 @item -gnatwi
5781 @item -gnatwJ
5782 @item -gnatwK
5783 @item -gnatwL
5784 @item -gnatwM
5785 @item -gnatwn
5786 @item -gnatwo
5787 @item -gnatwP
5788 @item -gnatwR
5789 @item -gnatwU
5790 @item -gnatwv
5791 @item -gnatwz
5792 @item -gnatwx
5793
5794 @end table
5795
5796 @node Debugging and Assertion Control
5797 @subsection Debugging and Assertion Control
5798
5799 @table @option
5800 @item -gnata
5801 @cindex @option{-gnata} (@command{gcc})
5802 @findex Assert
5803 @findex Debug
5804 @cindex Assertions
5805
5806 @noindent
5807 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5808 are ignored. This switch, where @samp{a} stands for assert, causes
5809 @code{Assert} and @code{Debug} pragmas to be activated.
5810
5811 The pragmas have the form:
5812
5813 @smallexample
5814 @cartouche
5815    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5816                       @var{static-string-expression}@r{]})
5817    @b{pragma} Debug (@var{procedure call})
5818 @end cartouche
5819 @end smallexample
5820
5821 @noindent
5822 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5823 If the result is @code{True}, the pragma has no effect (other than
5824 possible side effects from evaluating the expression). If the result is
5825 @code{False}, the exception @code{Assert_Failure} declared in the package
5826 @code{System.Assertions} is
5827 raised (passing @var{static-string-expression}, if present, as the
5828 message associated with the exception). If no string expression is
5829 given the default is a string giving the file name and line number
5830 of the pragma.
5831
5832 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5833 @code{pragma Debug} may appear within a declaration sequence, allowing
5834 debugging procedures to be called between declarations.
5835
5836 @ifset vms
5837 @item /DEBUG@r{[}=debug-level@r{]}
5838 @itemx  /NODEBUG
5839 Specifies how much debugging information is to be included in
5840 the resulting object file where 'debug-level' is one of the following:
5841 @table @code
5842 @item   TRACEBACK
5843 Include both debugger symbol records and traceback
5844 the object file.
5845 This is the default setting.
5846 @item   ALL
5847 Include both debugger symbol records and traceback in
5848 object file.
5849 @item   NONE
5850 Excludes both debugger symbol records and traceback
5851 the object file. Same as /NODEBUG.
5852 @item   SYMBOLS
5853 Includes only debugger symbol records in the object
5854 file. Note that this doesn't include traceback information.
5855 @end table
5856 @end ifset
5857 @end table
5858
5859 @node Validity Checking
5860 @subsection Validity Checking
5861 @findex Validity Checking
5862
5863 @noindent
5864 The Ada Reference Manual defines the concept of invalid values (see
5865 RM 13.9.1). The primary source of invalid values is uninitialized
5866 variables. A scalar variable that is left uninitialized may contain
5867 an invalid value; the concept of invalid does not apply to access or
5868 composite types.
5869
5870 It is an error to read an invalid value, but the RM does not require
5871 run-time checks to detect such errors, except for some minimal
5872 checking to prevent erroneous execution (i.e. unpredictable
5873 behavior). This corresponds to the @option{-gnatVd} switch below,
5874 which is the default. For example, by default, if the expression of a
5875 case statement is invalid, it will raise Constraint_Error rather than
5876 causing a wild jump, and if an array index on the left-hand side of an
5877 assignment is invalid, it will raise Constraint_Error rather than
5878 overwriting an arbitrary memory location.
5879
5880 The @option{-gnatVa} may be used to enable additional validity checks,
5881 which are not required by the RM. These checks are often very
5882 expensive (which is why the RM does not require them). These checks
5883 are useful in tracking down uninitialized variables, but they are
5884 not usually recommended for production builds.
5885
5886 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5887 control; you can enable whichever validity checks you desire. However,
5888 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5889 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5890 sufficient for non-debugging use.
5891
5892 The @option{-gnatB} switch tells the compiler to assume that all
5893 values are valid (that is, within their declared subtype range)
5894 except in the context of a use of the Valid attribute. This means
5895 the compiler can generate more efficient code, since the range
5896 of values is better known at compile time. However, an uninitialized
5897 variable can cause wild jumps and memory corruption in this mode.
5898
5899 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5900 checking mode as described below.
5901 @ifclear vms
5902 The @code{x} argument is a string of letters that
5903 indicate validity checks that are performed or not performed in addition
5904 to the default checks required by Ada as described above.
5905 @end ifclear
5906 @ifset vms
5907 The options allowed for this qualifier
5908 indicate validity checks that are performed or not performed in addition
5909 to the default checks required by Ada as described above.
5910 @end ifset
5911
5912 @table @option
5913 @c !sort!
5914 @item -gnatVa
5915 @emph{All validity checks.}
5916 @cindex @option{-gnatVa} (@command{gcc})
5917 All validity checks are turned on.
5918 @ifclear vms
5919 That is, @option{-gnatVa} is
5920 equivalent to @option{gnatVcdfimorst}.
5921 @end ifclear
5922
5923 @item -gnatVc
5924 @emph{Validity checks for copies.}
5925 @cindex @option{-gnatVc} (@command{gcc})
5926 The right hand side of assignments, and the initializing values of
5927 object declarations are validity checked.
5928
5929 @item -gnatVd
5930 @emph{Default (RM) validity checks.}
5931 @cindex @option{-gnatVd} (@command{gcc})
5932 Some validity checks are done by default following normal Ada semantics
5933 (RM 13.9.1 (9-11)).
5934 A check is done in case statements that the expression is within the range
5935 of the subtype. If it is not, Constraint_Error is raised.
5936 For assignments to array components, a check is done that the expression used
5937 as index is within the range. If it is not, Constraint_Error is raised.
5938 Both these validity checks may be turned off using switch @option{-gnatVD}.
5939 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5940 switch @option{-gnatVd} will leave the checks turned on.
5941 Switch @option{-gnatVD} should be used only if you are sure that all such
5942 expressions have valid values. If you use this switch and invalid values
5943 are present, then the program is erroneous, and wild jumps or memory
5944 overwriting may occur.
5945
5946 @item -gnatVe
5947 @emph{Validity checks for elementary components.}
5948 @cindex @option{-gnatVe} (@command{gcc})
5949 In the absence of this switch, assignments to record or array components are
5950 not validity checked, even if validity checks for assignments generally
5951 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5952 require valid data, but assignment of individual components does. So for
5953 example, there is a difference between copying the elements of an array with a
5954 slice assignment, compared to assigning element by element in a loop. This
5955 switch allows you to turn off validity checking for components, even when they
5956 are assigned component by component.
5957
5958 @item -gnatVf
5959 @emph{Validity checks for floating-point values.}
5960 @cindex @option{-gnatVf} (@command{gcc})
5961 In the absence of this switch, validity checking occurs only for discrete
5962 values. If @option{-gnatVf} is specified, then validity checking also applies
5963 for floating-point values, and NaNs and infinities are considered invalid,
5964 as well as out of range values for constrained types. Note that this means
5965 that standard IEEE infinity mode is not allowed. The exact contexts
5966 in which floating-point values are checked depends on the setting of other
5967 options. For example,
5968 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5969 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5970 (the order does not matter) specifies that floating-point parameters of mode
5971 @code{in} should be validity checked.
5972
5973 @item -gnatVi
5974 @emph{Validity checks for @code{in} mode parameters}
5975 @cindex @option{-gnatVi} (@command{gcc})
5976 Arguments for parameters of mode @code{in} are validity checked in function
5977 and procedure calls at the point of call.
5978
5979 @item -gnatVm
5980 @emph{Validity checks for @code{in out} mode parameters.}
5981 @cindex @option{-gnatVm} (@command{gcc})
5982 Arguments for parameters of mode @code{in out} are validity checked in
5983 procedure calls at the point of call. The @code{'m'} here stands for
5984 modify, since this concerns parameters that can be modified by the call.
5985 Note that there is no specific option to test @code{out} parameters,
5986 but any reference within the subprogram will be tested in the usual
5987 manner, and if an invalid value is copied back, any reference to it
5988 will be subject to validity checking.
5989
5990 @item -gnatVn
5991 @emph{No validity checks.}
5992 @cindex @option{-gnatVn} (@command{gcc})
5993 This switch turns off all validity checking, including the default checking
5994 for case statements and left hand side subscripts. Note that the use of
5995 the switch @option{-gnatp} suppresses all run-time checks, including
5996 validity checks, and thus implies @option{-gnatVn}. When this switch
5997 is used, it cancels any other @option{-gnatV} previously issued.
5998
5999 @item -gnatVo
6000 @emph{Validity checks for operator and attribute operands.}
6001 @cindex @option{-gnatVo} (@command{gcc})
6002 Arguments for predefined operators and attributes are validity checked.
6003 This includes all operators in package @code{Standard},
6004 the shift operators defined as intrinsic in package @code{Interfaces}
6005 and operands for attributes such as @code{Pos}. Checks are also made
6006 on individual component values for composite comparisons, and on the
6007 expressions in type conversions and qualified expressions. Checks are
6008 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6009
6010 @item -gnatVp
6011 @emph{Validity checks for parameters.}
6012 @cindex @option{-gnatVp} (@command{gcc})
6013 This controls the treatment of parameters within a subprogram (as opposed
6014 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6015 of parameters on a call. If either of these call options is used, then
6016 normally an assumption is made within a subprogram that the input arguments
6017 have been validity checking at the point of call, and do not need checking
6018 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6019 is not made, and parameters are not assumed to be valid, so their validity
6020 will be checked (or rechecked) within the subprogram.
6021
6022 @item -gnatVr
6023 @emph{Validity checks for function returns.}
6024 @cindex @option{-gnatVr} (@command{gcc})
6025 The expression in @code{return} statements in functions is validity
6026 checked.
6027
6028 @item -gnatVs
6029 @emph{Validity checks for subscripts.}
6030 @cindex @option{-gnatVs} (@command{gcc})
6031 All subscripts expressions are checked for validity, whether they appear
6032 on the right side or left side (in default mode only left side subscripts
6033 are validity checked).
6034
6035 @item -gnatVt
6036 @emph{Validity checks for tests.}
6037 @cindex @option{-gnatVt} (@command{gcc})
6038 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6039 statements are checked, as well as guard expressions in entry calls.
6040
6041 @end table
6042
6043 @noindent
6044 The @option{-gnatV} switch may be followed by
6045 ^a string of letters^a list of options^
6046 to turn on a series of validity checking options.
6047 For example,
6048 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6049 specifies that in addition to the default validity checking, copies and
6050 function return expressions are to be validity checked.
6051 In order to make it easier
6052 to specify the desired combination of effects,
6053 @ifclear vms
6054 the upper case letters @code{CDFIMORST} may
6055 be used to turn off the corresponding lower case option.
6056 @end ifclear
6057 @ifset vms
6058 the prefix @code{NO} on an option turns off the corresponding validity
6059 checking:
6060 @itemize @bullet
6061 @item @code{NOCOPIES}
6062 @item @code{NODEFAULT}
6063 @item @code{NOFLOATS}
6064 @item @code{NOIN_PARAMS}
6065 @item @code{NOMOD_PARAMS}
6066 @item @code{NOOPERANDS}
6067 @item @code{NORETURNS}
6068 @item @code{NOSUBSCRIPTS}
6069 @item @code{NOTESTS}
6070 @end itemize
6071 @end ifset
6072 Thus
6073 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6074 turns on all validity checking options except for
6075 checking of @code{@b{in out}} procedure arguments.
6076
6077 The specification of additional validity checking generates extra code (and
6078 in the case of @option{-gnatVa} the code expansion can be substantial).
6079 However, these additional checks can be very useful in detecting
6080 uninitialized variables, incorrect use of unchecked conversion, and other
6081 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6082 is useful in conjunction with the extra validity checking, since this
6083 ensures that wherever possible uninitialized variables have invalid values.
6084
6085 See also the pragma @code{Validity_Checks} which allows modification of
6086 the validity checking mode at the program source level, and also allows for
6087 temporary disabling of validity checks.
6088
6089 @node Style Checking
6090 @subsection Style Checking
6091 @findex Style checking
6092
6093 @noindent
6094 The @option{-gnaty^x^(option,option,@dots{})^} switch
6095 @cindex @option{-gnaty} (@command{gcc})
6096 causes the compiler to
6097 enforce specified style rules. A limited set of style rules has been used
6098 in writing the GNAT sources themselves. This switch allows user programs
6099 to activate all or some of these checks. If the source program fails a
6100 specified style check, an appropriate warning message is given, preceded by
6101 the character sequence ``(style)''.
6102 @ifset vms
6103 @code{(option,option,@dots{})} is a sequence of keywords
6104 @end ifset
6105 @ifclear vms
6106 The string @var{x} is a sequence of letters or digits
6107 @end ifclear
6108 indicating the particular style
6109 checks to be performed. The following checks are defined:
6110
6111 @table @option
6112 @c !sort!
6113 @item 0-9
6114 @emph{Specify indentation level.}
6115 If a digit from 1-9 appears
6116 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6117 then proper indentation is checked, with the digit indicating the
6118 indentation level required. A value of zero turns off this style check.
6119 The general style of required indentation is as specified by
6120 the examples in the Ada Reference Manual. Full line comments must be
6121 aligned with the @code{--} starting on a column that is a multiple of
6122 the alignment level, or they may be aligned the same way as the following
6123 non-blank line (this is useful when full line comments appear in the middle
6124 of a statement.
6125
6126 @item ^a^ATTRIBUTE^
6127 @emph{Check attribute casing.}
6128 Attribute names, including the case of keywords such as @code{digits}
6129 used as attributes names, must be written in mixed case, that is, the
6130 initial letter and any letter following an underscore must be uppercase.
6131 All other letters must be lowercase.
6132
6133 @item ^A^ARRAY_INDEXES^
6134 @emph{Use of array index numbers in array attributes.}
6135 When using the array attributes First, Last, Range,
6136 or Length, the index number must be omitted for one-dimensional arrays
6137 and is required for multi-dimensional arrays.
6138
6139 @item ^b^BLANKS^
6140 @emph{Blanks not allowed at statement end.}
6141 Trailing blanks are not allowed at the end of statements. The purpose of this
6142 rule, together with h (no horizontal tabs), is to enforce a canonical format
6143 for the use of blanks to separate source tokens.
6144
6145 @item ^B^BOOLEAN_OPERATORS^
6146 @emph{Check Boolean operators.}
6147 The use of AND/OR operators is not permitted except in the cases of modular
6148 operands, array operands, and simple stand-alone boolean variables or
6149 boolean constants. In all other cases AND THEN/OR ELSE are required.
6150
6151 @item ^c^COMMENTS^
6152 @emph{Check comments.}
6153 Comments must meet the following set of rules:
6154
6155 @itemize @bullet
6156
6157 @item
6158 The ``@code{--}'' that starts the column must either start in column one,
6159 or else at least one blank must precede this sequence.
6160
6161 @item
6162 Comments that follow other tokens on a line must have at least one blank
6163 following the ``@code{--}'' at the start of the comment.
6164
6165 @item
6166 Full line comments must have two blanks following the ``@code{--}'' that
6167 starts the comment, with the following exceptions.
6168
6169 @item
6170 A line consisting only of the ``@code{--}'' characters, possibly preceded
6171 by blanks is permitted.
6172
6173 @item
6174 A comment starting with ``@code{--x}'' where @code{x} is a special character
6175 is permitted.
6176 This allows proper processing of the output generated by specialized tools
6177 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6178 annotation
6179 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6180 special character is defined as being in one of the ASCII ranges
6181 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6182 Note that this usage is not permitted
6183 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6184
6185 @item
6186 A line consisting entirely of minus signs, possibly preceded by blanks, is
6187 permitted. This allows the construction of box comments where lines of minus
6188 signs are used to form the top and bottom of the box.
6189
6190 @item
6191 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6192 least one blank follows the initial ``@code{--}''. Together with the preceding
6193 rule, this allows the construction of box comments, as shown in the following
6194 example:
6195 @smallexample
6196 ---------------------------
6197 -- This is a box comment --
6198 -- with two text lines.  --
6199 ---------------------------
6200 @end smallexample
6201 @end itemize
6202
6203 @item ^d^DOS_LINE_ENDINGS^
6204 @emph{Check no DOS line terminators present.}
6205 All lines must be terminated by a single ASCII.LF
6206 character (in particular the DOS line terminator sequence CR/LF is not
6207 allowed).
6208
6209 @item ^e^END^
6210 @emph{Check end/exit labels.}
6211 Optional labels on @code{end} statements ending subprograms and on
6212 @code{exit} statements exiting named loops, are required to be present.
6213
6214 @item ^f^VTABS^
6215 @emph{No form feeds or vertical tabs.}
6216 Neither form feeds nor vertical tab characters are permitted
6217 in the source text.
6218
6219 @item ^g^GNAT^
6220 @emph{GNAT style mode}
6221 The set of style check switches is set to match that used by the GNAT sources.
6222 This may be useful when developing code that is eventually intended to be
6223 incorporated into GNAT. For further details, see GNAT sources.
6224
6225 @item ^h^HTABS^
6226 @emph{No horizontal tabs.}
6227 Horizontal tab characters are not permitted in the source text.
6228 Together with the b (no blanks at end of line) check, this
6229 enforces a canonical form for the use of blanks to separate
6230 source tokens.
6231
6232 @item ^i^IF_THEN^
6233 @emph{Check if-then layout.}
6234 The keyword @code{then} must appear either on the same
6235 line as corresponding @code{if}, or on a line on its own, lined
6236 up under the @code{if} with at least one non-blank line in between
6237 containing all or part of the condition to be tested.
6238
6239 @item ^I^IN_MODE^
6240 @emph{check mode IN keywords}
6241 Mode @code{in} (the default mode) is not
6242 allowed to be given explicitly. @code{in out} is fine,
6243 but not @code{in} on its own.
6244
6245 @item ^k^KEYWORD^
6246 @emph{Check keyword casing.}
6247 All keywords must be in lower case (with the exception of keywords
6248 such as @code{digits} used as attribute names to which this check
6249 does not apply).
6250
6251 @item ^l^LAYOUT^
6252 @emph{Check layout.}
6253 Layout of statement and declaration constructs must follow the
6254 recommendations in the Ada Reference Manual, as indicated by the
6255 form of the syntax rules. For example an @code{else} keyword must
6256 be lined up with the corresponding @code{if} keyword.
6257
6258 There are two respects in which the style rule enforced by this check
6259 option are more liberal than those in the Ada Reference Manual. First
6260 in the case of record declarations, it is permissible to put the
6261 @code{record} keyword on the same line as the @code{type} keyword, and
6262 then the @code{end} in @code{end record} must line up under @code{type}.
6263 This is also permitted when the type declaration is split on two lines.
6264 For example, any of the following three layouts is acceptable:
6265
6266 @smallexample @c ada
6267 @cartouche
6268 type q is record
6269    a : integer;
6270    b : integer;
6271 end record;
6272
6273 type q is
6274    record
6275       a : integer;
6276       b : integer;
6277    end record;
6278
6279 type q is
6280    record
6281       a : integer;
6282       b : integer;
6283 end record;
6284
6285 @end cartouche
6286 @end smallexample
6287
6288 @noindent
6289 Second, in the case of a block statement, a permitted alternative
6290 is to put the block label on the same line as the @code{declare} or
6291 @code{begin} keyword, and then line the @code{end} keyword up under
6292 the block label. For example both the following are permitted:
6293
6294 @smallexample @c ada
6295 @cartouche
6296 Block : declare
6297    A : Integer := 3;
6298 begin
6299    Proc (A, A);
6300 end Block;
6301
6302 Block :
6303    declare
6304       A : Integer := 3;
6305    begin
6306       Proc (A, A);
6307    end Block;
6308 @end cartouche
6309 @end smallexample
6310
6311 @noindent
6312 The same alternative format is allowed for loops. For example, both of
6313 the following are permitted:
6314
6315 @smallexample @c ada
6316 @cartouche
6317 Clear : while J < 10 loop
6318    A (J) := 0;
6319 end loop Clear;
6320
6321 Clear :
6322    while J < 10 loop
6323       A (J) := 0;
6324    end loop Clear;
6325 @end cartouche
6326 @end smallexample
6327
6328 @item ^Lnnn^MAX_NESTING=nnn^
6329 @emph{Set maximum nesting level}
6330 The maximum level of nesting of constructs (including subprograms, loops,
6331 blocks, packages, and conditionals) may not exceed the given value
6332 @option{nnn}. A value of zero disconnects this style check.
6333
6334 @item ^m^LINE_LENGTH^
6335 @emph{Check maximum line length.}
6336 The length of source lines must not exceed 79 characters, including
6337 any trailing blanks. The value of 79 allows convenient display on an
6338 80 character wide device or window, allowing for possible special
6339 treatment of 80 character lines. Note that this count is of
6340 characters in the source text. This means that a tab character counts
6341 as one character in this count but a wide character sequence counts as
6342 a single character (however many bytes are needed in the encoding).
6343
6344 @item ^Mnnn^MAX_LENGTH=nnn^
6345 @emph{Set maximum line length.}
6346 The length of lines must not exceed the
6347 given value @option{nnn}. The maximum value that can be specified is 32767.
6348
6349 @item ^n^STANDARD_CASING^
6350 @emph{Check casing of entities in Standard.}
6351 Any identifier from Standard must be cased
6352 to match the presentation in the Ada Reference Manual (for example,
6353 @code{Integer} and @code{ASCII.NUL}).
6354
6355 @item ^N^NONE^
6356 @emph{Turn off all style checks}
6357 All style check options are turned off.
6358
6359 @item ^o^ORDERED_SUBPROGRAMS^
6360 @emph{Check order of subprogram bodies.}
6361 All subprogram bodies in a given scope
6362 (e.g.@: a package body) must be in alphabetical order. The ordering
6363 rule uses normal Ada rules for comparing strings, ignoring casing
6364 of letters, except that if there is a trailing numeric suffix, then
6365 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6366 before Junk10).
6367
6368 @item ^O^OVERRIDING_INDICATORS^
6369 @emph{Check that overriding subprograms are explicitly marked as such.}
6370 The declaration of a primitive operation of a type extension that overrides
6371 an inherited operation must carry an overriding indicator.
6372
6373 @item ^p^PRAGMA^
6374 @emph{Check pragma casing.}
6375 Pragma names must be written in mixed case, that is, the
6376 initial letter and any letter following an underscore must be uppercase.
6377 All other letters must be lowercase.
6378
6379 @item ^r^REFERENCES^
6380 @emph{Check references.}
6381 All identifier references must be cased in the same way as the
6382 corresponding declaration. No specific casing style is imposed on
6383 identifiers. The only requirement is for consistency of references
6384 with declarations.
6385
6386 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6387 @emph{Check no statements after THEN/ELSE.}
6388 No statements are allowed
6389 on the same line as a THEN or ELSE keyword following the
6390 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6391 and a special exception allows a pragma to appear after ELSE.
6392
6393 @item ^s^SPECS^
6394 @emph{Check separate specs.}
6395 Separate declarations (``specs'') are required for subprograms (a
6396 body is not allowed to serve as its own declaration). The only
6397 exception is that parameterless library level procedures are
6398 not required to have a separate declaration. This exception covers
6399 the most frequent form of main program procedures.
6400
6401 @item ^t^TOKEN^
6402 @emph{Check token spacing.}
6403 The following token spacing rules are enforced:
6404
6405 @itemize @bullet
6406
6407 @item
6408 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6409
6410 @item
6411 The token @code{=>} must be surrounded by spaces.
6412
6413 @item
6414 The token @code{<>} must be preceded by a space or a left parenthesis.
6415
6416 @item
6417 Binary operators other than @code{**} must be surrounded by spaces.
6418 There is no restriction on the layout of the @code{**} binary operator.
6419
6420 @item
6421 Colon must be surrounded by spaces.
6422
6423 @item
6424 Colon-equal (assignment, initialization) must be surrounded by spaces.
6425
6426 @item
6427 Comma must be the first non-blank character on the line, or be
6428 immediately preceded by a non-blank character, and must be followed
6429 by a space.
6430
6431 @item
6432 If the token preceding a left parenthesis ends with a letter or digit, then
6433 a space must separate the two tokens.
6434
6435 @item
6436 A right parenthesis must either be the first non-blank character on
6437 a line, or it must be preceded by a non-blank character.
6438
6439 @item
6440 A semicolon must not be preceded by a space, and must not be followed by
6441 a non-blank character.
6442
6443 @item
6444 A unary plus or minus may not be followed by a space.
6445
6446 @item
6447 A vertical bar must be surrounded by spaces.
6448 @end itemize
6449
6450 @item ^u^UNNECESSARY_BLANK_LINES^
6451 @emph{Check unnecessary blank lines.}
6452 Unnecessary blank lines are not allowed. A blank line is considered
6453 unnecessary if it appears at the end of the file, or if more than
6454 one blank line occurs in sequence.
6455
6456 @item ^x^XTRA_PARENS^
6457 @emph{Check extra parentheses.}
6458 Unnecessary extra level of parentheses (C-style) are not allowed
6459 around conditions in @code{if} statements, @code{while} statements and
6460 @code{exit} statements.
6461
6462 @item ^y^ALL_BUILTIN^
6463 @emph{Set all standard style check options}
6464 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6465 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6466 @option{-gnatyS}, @option{-gnatyLnnn},
6467 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6468
6469 @ifclear vms
6470 @item -
6471 @emph{Remove style check options}
6472 This causes any subsequent options in the string to act as canceling the
6473 corresponding style check option. To cancel maximum nesting level control,
6474 use @option{L} parameter witout any integer value after that, because any
6475 digit following @option{-} in the parameter string of the @option{-gnaty}
6476 option will be threated as canceling indentation check. The same is true
6477 for @option{M} parameter. @option{y} and @option{N} parameters are not
6478 allowed after @option{-}.
6479
6480 @item +
6481 This causes any subsequent options in the string to enable the corresponding
6482 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6483 if any.
6484 @end ifclear
6485
6486 @ifset vms
6487 @item NOxxx
6488 @emph{Removing style check options}
6489 If the name of a style check is preceded by @option{NO} then the corresponding
6490 style check is turned off. For example @option{NOCOMMENTS} turns off style
6491 checking for comments.
6492 @end ifset
6493 @end table
6494
6495 @noindent
6496 In the above rules, appearing in column one is always permitted, that is,
6497 counts as meeting either a requirement for a required preceding space,
6498 or as meeting a requirement for no preceding space.
6499
6500 Appearing at the end of a line is also always permitted, that is, counts
6501 as meeting either a requirement for a following space, or as meeting
6502 a requirement for no following space.
6503
6504 @noindent
6505 If any of these style rules is violated, a message is generated giving
6506 details on the violation. The initial characters of such messages are
6507 always ``@code{(style)}''. Note that these messages are treated as warning
6508 messages, so they normally do not prevent the generation of an object
6509 file. The @option{-gnatwe} switch can be used to treat warning messages,
6510 including style messages, as fatal errors.
6511
6512 The switch
6513 @ifclear vms
6514 @option{-gnaty} on its own (that is not
6515 followed by any letters or digits), then the effect is equivalent
6516 to the use of @option{-gnatyy}, as described above, that is all
6517 built-in standard style check options are enabled.
6518
6519 @end ifclear
6520 @ifset vms
6521 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6522 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6523 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6524 @end ifset
6525
6526
6527
6528 The switch
6529 @ifclear vms
6530 @option{-gnatyN}
6531 @end ifclear
6532 @ifset vms
6533 /STYLE_CHECKS=NONE
6534 @end ifset
6535 clears any previously set style checks.
6536
6537 @node Run-Time Checks
6538 @subsection Run-Time Checks
6539 @cindex Division by zero
6540 @cindex Access before elaboration
6541 @cindex Checks, division by zero
6542 @cindex Checks, access before elaboration
6543 @cindex Checks, stack overflow checking
6544
6545 @noindent
6546 By default, the following checks are suppressed: integer overflow
6547 checks, stack overflow checks, and checks for access before
6548 elaboration on subprogram calls. All other checks, including range
6549 checks and array bounds checks, are turned on by default. The
6550 following @command{gcc} switches refine this default behavior.
6551
6552 @table @option
6553 @c !sort!
6554 @item -gnatp
6555 @cindex @option{-gnatp} (@command{gcc})
6556 @cindex Suppressing checks
6557 @cindex Checks, suppressing
6558 @findex Suppress
6559 This switch causes the unit to be compiled
6560 as though @code{pragma Suppress (All_checks)}
6561 had been present in the source. Validity checks are also eliminated (in
6562 other words @option{-gnatp} also implies @option{-gnatVn}.
6563 Use this switch to improve the performance
6564 of the code at the expense of safety in the presence of invalid data or
6565 program bugs.
6566
6567 Note that when checks are suppressed, the compiler is allowed, but not
6568 required, to omit the checking code. If the run-time cost of the
6569 checking code is zero or near-zero, the compiler will generate it even
6570 if checks are suppressed. In particular, if the compiler can prove
6571 that a certain check will necessarily fail, it will generate code to
6572 do an unconditional ``raise'', even if checks are suppressed. The
6573 compiler warns in this case. Another case in which checks may not be
6574 eliminated is when they are embedded in certain run time routines such
6575 as math library routines.
6576
6577 Of course, run-time checks are omitted whenever the compiler can prove
6578 that they will not fail, whether or not checks are suppressed.
6579
6580 Note that if you suppress a check that would have failed, program
6581 execution is erroneous, which means the behavior is totally
6582 unpredictable. The program might crash, or print wrong answers, or
6583 do anything else. It might even do exactly what you wanted it to do
6584 (and then it might start failing mysteriously next week or next
6585 year). The compiler will generate code based on the assumption that
6586 the condition being checked is true, which can result in disaster if
6587 that assumption is wrong.
6588
6589 @item -gnato
6590 @cindex @option{-gnato} (@command{gcc})
6591 @cindex Overflow checks
6592 @cindex Check, overflow
6593 Enables overflow checking for integer operations.
6594 This causes GNAT to generate slower and larger executable
6595 programs by adding code to check for overflow (resulting in raising
6596 @code{Constraint_Error} as required by standard Ada
6597 semantics). These overflow checks correspond to situations in which
6598 the true value of the result of an operation may be outside the base
6599 range of the result type. The following example shows the distinction:
6600
6601 @smallexample @c ada
6602 X1 : Integer := "Integer'Last";
6603 X2 : Integer range 1 .. 5 := "5";
6604 X3 : Integer := "Integer'Last";
6605 X4 : Integer range 1 .. 5 := "5";
6606 F  : Float := "2.0E+20";
6607 @dots{}
6608 X1 := X1 + 1;
6609 X2 := X2 + 1;
6610 X3 := Integer (F);
6611 X4 := Integer (F);
6612 @end smallexample
6613
6614 @noindent
6615 Note that if explicit values are assigned at compile time, the
6616 compiler may be able to detect overflow at compile time, in which case
6617 no actual run-time checking code is required, and Constraint_Error
6618 will be raised unconditionally, with or without
6619 @option{-gnato}. That's why the assigned values in the above fragment
6620 are in quotes, the meaning is "assign a value not known to the
6621 compiler that happens to be equal to ...". The remaining discussion
6622 assumes that the compiler cannot detect the values at compile time.
6623
6624 Here the first addition results in a value that is outside the base range
6625 of Integer, and hence requires an overflow check for detection of the
6626 constraint error. Thus the first assignment to @code{X1} raises a
6627 @code{Constraint_Error} exception only if @option{-gnato} is set.
6628
6629 The second increment operation results in a violation of the explicit
6630 range constraint; such range checks are performed by default, and are
6631 unaffected by @option{-gnato}.
6632
6633 The two conversions of @code{F} both result in values that are outside
6634 the base range of type @code{Integer} and thus will raise
6635 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6636 The fact that the result of the second conversion is assigned to
6637 variable @code{X4} with a restricted range is irrelevant, since the problem
6638 is in the conversion, not the assignment.
6639
6640 Basically the rule is that in the default mode (@option{-gnato} not
6641 used), the generated code assures that all integer variables stay
6642 within their declared ranges, or within the base range if there is
6643 no declared range. This prevents any serious problems like indexes
6644 out of range for array operations.
6645
6646 What is not checked in default mode is an overflow that results in
6647 an in-range, but incorrect value. In the above example, the assignments
6648 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6649 range of the target variable, but the result is wrong in the sense that
6650 it is too large to be represented correctly. Typically the assignment
6651 to @code{X1} will result in wrap around to the largest negative number.
6652 The conversions of @code{F} will result in some @code{Integer} value
6653 and if that integer value is out of the @code{X4} range then the
6654 subsequent assignment would generate an exception.
6655
6656 @findex Machine_Overflows
6657 Note that the @option{-gnato} switch does not affect the code generated
6658 for any floating-point operations; it applies only to integer
6659 semantics).
6660 For floating-point, GNAT has the @code{Machine_Overflows}
6661 attribute set to @code{False} and the normal mode of operation is to
6662 generate IEEE NaN and infinite values on overflow or invalid operations
6663 (such as dividing 0.0 by 0.0).
6664
6665 The reason that we distinguish overflow checking from other kinds of
6666 range constraint checking is that a failure of an overflow check, unlike
6667 for example the failure of a range check, can result in an incorrect
6668 value, but cannot cause random memory destruction (like an out of range
6669 subscript), or a wild jump (from an out of range case value). Overflow
6670 checking is also quite expensive in time and space, since in general it
6671 requires the use of double length arithmetic.
6672
6673 Note again that @option{-gnato} is off by default, so overflow checking is
6674 not performed in default mode. This means that out of the box, with the
6675 default settings, GNAT does not do all the checks expected from the
6676 language description in the Ada Reference Manual. If you want all constraint
6677 checks to be performed, as described in this Manual, then you must
6678 explicitly use the -gnato switch either on the @command{gnatmake} or
6679 @command{gcc} command.
6680
6681 @item -gnatE
6682 @cindex @option{-gnatE} (@command{gcc})
6683 @cindex Elaboration checks
6684 @cindex Check, elaboration
6685 Enables dynamic checks for access-before-elaboration
6686 on subprogram calls and generic instantiations.
6687 Note that @option{-gnatE} is not necessary for safety, because in the
6688 default mode, GNAT ensures statically that the checks would not fail.
6689 For full details of the effect and use of this switch,
6690 @xref{Compiling Using gcc}.
6691
6692 @item -fstack-check
6693 @cindex @option{-fstack-check} (@command{gcc})
6694 @cindex Stack Overflow Checking
6695 @cindex Checks, stack overflow checking
6696 Activates stack overflow checking. For full details of the effect and use of
6697 this switch see @ref{Stack Overflow Checking}.
6698 @end table
6699
6700 @findex Unsuppress
6701 @noindent
6702 The setting of these switches only controls the default setting of the
6703 checks. You may modify them using either @code{Suppress} (to remove
6704 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6705 the program source.
6706
6707 @node Using gcc for Syntax Checking
6708 @subsection Using @command{gcc} for Syntax Checking
6709 @table @option
6710 @item -gnats
6711 @cindex @option{-gnats} (@command{gcc})
6712 @ifclear vms
6713
6714 @noindent
6715 The @code{s} stands for ``syntax''.
6716 @end ifclear
6717
6718 Run GNAT in syntax checking only mode. For
6719 example, the command
6720
6721 @smallexample
6722 $ gcc -c -gnats x.adb
6723 @end smallexample
6724
6725 @noindent
6726 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6727 series of files in a single command
6728 @ifclear vms
6729 , and can use wild cards to specify such a group of files.
6730 Note that you must specify the @option{-c} (compile
6731 only) flag in addition to the @option{-gnats} flag.
6732 @end ifclear
6733 .
6734 You may use other switches in conjunction with @option{-gnats}. In
6735 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6736 format of any generated error messages.
6737
6738 When the source file is empty or contains only empty lines and/or comments,
6739 the output is a warning:
6740
6741 @smallexample
6742 $ gcc -c -gnats -x ada toto.txt
6743 toto.txt:1:01: warning: empty file, contains no compilation units
6744 $
6745 @end smallexample
6746
6747 Otherwise, the output is simply the error messages, if any. No object file or
6748 ALI file is generated by a syntax-only compilation. Also, no units other
6749 than the one specified are accessed. For example, if a unit @code{X}
6750 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6751 check only mode does not access the source file containing unit
6752 @code{Y}.
6753
6754 @cindex Multiple units, syntax checking
6755 Normally, GNAT allows only a single unit in a source file. However, this
6756 restriction does not apply in syntax-check-only mode, and it is possible
6757 to check a file containing multiple compilation units concatenated
6758 together. This is primarily used by the @code{gnatchop} utility
6759 (@pxref{Renaming Files Using gnatchop}).
6760 @end table
6761
6762 @node Using gcc for Semantic Checking
6763 @subsection Using @command{gcc} for Semantic Checking
6764 @table @option
6765 @item -gnatc
6766 @cindex @option{-gnatc} (@command{gcc})
6767
6768 @ifclear vms
6769 @noindent
6770 The @code{c} stands for ``check''.
6771 @end ifclear
6772 Causes the compiler to operate in semantic check mode,
6773 with full checking for all illegalities specified in the
6774 Ada Reference Manual, but without generation of any object code
6775 (no object file is generated).
6776
6777 Because dependent files must be accessed, you must follow the GNAT
6778 semantic restrictions on file structuring to operate in this mode:
6779
6780 @itemize @bullet
6781 @item
6782 The needed source files must be accessible
6783 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6784
6785 @item
6786 Each file must contain only one compilation unit.
6787
6788 @item
6789 The file name and unit name must match (@pxref{File Naming Rules}).
6790 @end itemize
6791
6792 The output consists of error messages as appropriate. No object file is
6793 generated. An @file{ALI} file is generated for use in the context of
6794 cross-reference tools, but this file is marked as not being suitable
6795 for binding (since no object file is generated).
6796 The checking corresponds exactly to the notion of
6797 legality in the Ada Reference Manual.
6798
6799 Any unit can be compiled in semantics-checking-only mode, including
6800 units that would not normally be compiled (subunits,
6801 and specifications where a separate body is present).
6802 @end table
6803
6804 @node Compiling Different Versions of Ada
6805 @subsection Compiling Different Versions of Ada
6806
6807 @noindent
6808 The switches described in this section allow you to explicitly specify
6809 the version of the Ada language that your programs are written in.
6810 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6811 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6812 indicate Ada 83 compatibility mode.
6813
6814 @table @option
6815 @cindex Compatibility with Ada 83
6816
6817 @item -gnat83 (Ada 83 Compatibility Mode)
6818 @cindex @option{-gnat83} (@command{gcc})
6819 @cindex ACVC, Ada 83 tests
6820 @cindex Ada 83 mode
6821
6822 @noindent
6823 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6824 specifies that the program is to be compiled in Ada 83 mode. With
6825 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6826 semantics where this can be done easily.
6827 It is not possible to guarantee this switch does a perfect
6828 job; some subtle tests, such as are
6829 found in earlier ACVC tests (and that have been removed from the ACATS suite
6830 for Ada 95), might not compile correctly.
6831 Nevertheless, this switch may be useful in some circumstances, for example
6832 where, due to contractual reasons, existing code needs to be maintained
6833 using only Ada 83 features.
6834
6835 With few exceptions (most notably the need to use @code{<>} on
6836 @cindex Generic formal parameters
6837 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6838 reserved words, and the use of packages
6839 with optional bodies), it is not necessary to specify the
6840 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6841 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6842 a correct Ada 83 program is usually also a correct program
6843 in these later versions of the language standard.
6844 For further information, please refer to @ref{Compatibility and Porting Guide}.
6845
6846 @item -gnat95 (Ada 95 mode)
6847 @cindex @option{-gnat95} (@command{gcc})
6848 @cindex Ada 95 mode
6849
6850 @noindent
6851 This switch directs the compiler to implement the Ada 95 version of the
6852 language.
6853 Since Ada 95 is almost completely upwards
6854 compatible with Ada 83, Ada 83 programs may generally be compiled using
6855 this switch (see the description of the @option{-gnat83} switch for further
6856 information about Ada 83 mode).
6857 If an Ada 2005 program is compiled in Ada 95 mode,
6858 uses of the new Ada 2005 features will cause error
6859 messages or warnings.
6860
6861 This switch also can be used to cancel the effect of a previous
6862 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6863
6864 @item -gnat05 (Ada 2005 mode)
6865 @cindex @option{-gnat05} (@command{gcc})
6866 @cindex Ada 2005 mode
6867
6868 @noindent
6869 This switch directs the compiler to implement the Ada 2005 version of the
6870 language.
6871 Since Ada 2005 is almost completely upwards
6872 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6873 may generally be compiled using this switch (see the description of the
6874 @option{-gnat83} and @option{-gnat95} switches for further
6875 information).
6876
6877 For information about the approved ``Ada Issues'' that have been incorporated
6878 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6879 Included with GNAT releases is a file @file{features-ada0y} that describes
6880 the set of implemented Ada 2005 features.
6881 @end table
6882
6883
6884 @node Character Set Control
6885 @subsection Character Set Control
6886 @table @option
6887 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6888 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6889
6890 @noindent
6891 Normally GNAT recognizes the Latin-1 character set in source program
6892 identifiers, as described in the Ada Reference Manual.
6893 This switch causes
6894 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6895 single character ^^or word^ indicating the character set, as follows:
6896
6897 @table @code
6898 @item 1
6899 ISO 8859-1 (Latin-1) identifiers
6900
6901 @item 2
6902 ISO 8859-2 (Latin-2) letters allowed in identifiers
6903
6904 @item 3
6905 ISO 8859-3 (Latin-3) letters allowed in identifiers
6906
6907 @item 4
6908 ISO 8859-4 (Latin-4) letters allowed in identifiers
6909
6910 @item 5
6911 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6912
6913 @item 9
6914 ISO 8859-15 (Latin-9) letters allowed in identifiers
6915
6916 @item ^p^PC^
6917 IBM PC letters (code page 437) allowed in identifiers
6918
6919 @item ^8^PC850^
6920 IBM PC letters (code page 850) allowed in identifiers
6921
6922 @item ^f^FULL_UPPER^
6923 Full upper-half codes allowed in identifiers
6924
6925 @item ^n^NO_UPPER^
6926 No upper-half codes allowed in identifiers
6927
6928 @item ^w^WIDE^
6929 Wide-character codes (that is, codes greater than 255)
6930 allowed in identifiers
6931 @end table
6932
6933 @xref{Foreign Language Representation}, for full details on the
6934 implementation of these character sets.
6935
6936 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6937 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6938 Specify the method of encoding for wide characters.
6939 @var{e} is one of the following:
6940
6941 @table @code
6942
6943 @item ^h^HEX^
6944 Hex encoding (brackets coding also recognized)
6945
6946 @item ^u^UPPER^
6947 Upper half encoding (brackets encoding also recognized)
6948
6949 @item ^s^SHIFT_JIS^
6950 Shift/JIS encoding (brackets encoding also recognized)
6951
6952 @item ^e^EUC^
6953 EUC encoding (brackets encoding also recognized)
6954
6955 @item ^8^UTF8^
6956 UTF-8 encoding (brackets encoding also recognized)
6957
6958 @item ^b^BRACKETS^
6959 Brackets encoding only (default value)
6960 @end table
6961 For full details on these encoding
6962 methods see @ref{Wide Character Encodings}.
6963 Note that brackets coding is always accepted, even if one of the other
6964 options is specified, so for example @option{-gnatW8} specifies that both
6965 brackets and UTF-8 encodings will be recognized. The units that are
6966 with'ed directly or indirectly will be scanned using the specified
6967 representation scheme, and so if one of the non-brackets scheme is
6968 used, it must be used consistently throughout the program. However,
6969 since brackets encoding is always recognized, it may be conveniently
6970 used in standard libraries, allowing these libraries to be used with
6971 any of the available coding schemes.
6972 scheme.
6973
6974 If no @option{-gnatW?} parameter is present, then the default
6975 representation is normally Brackets encoding only. However, if the
6976 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6977 byte order mark or BOM for UTF-8), then these three characters are
6978 skipped and the default representation for the file is set to UTF-8.
6979
6980 Note that the wide character representation that is specified (explicitly
6981 or by default) for the main program also acts as the default encoding used
6982 for Wide_Text_IO files if not specifically overridden by a WCEM form
6983 parameter.
6984
6985 @end table
6986 @node File Naming Control
6987 @subsection File Naming Control
6988
6989 @table @option
6990 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6991 @cindex @option{-gnatk} (@command{gcc})
6992 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6993 1-999, indicates the maximum allowable length of a file name (not
6994 including the @file{.ads} or @file{.adb} extension). The default is not
6995 to enable file name krunching.
6996
6997 For the source file naming rules, @xref{File Naming Rules}.
6998 @end table
6999
7000 @node Subprogram Inlining Control
7001 @subsection Subprogram Inlining Control
7002
7003 @table @option
7004 @c !sort!
7005 @item -gnatn
7006 @cindex @option{-gnatn} (@command{gcc})
7007 @ifclear vms
7008 The @code{n} here is intended to suggest the first syllable of the
7009 word ``inline''.
7010 @end ifclear
7011 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7012 inlining to actually occur, optimization must be enabled. To enable
7013 inlining of subprograms specified by pragma @code{Inline},
7014 you must also specify this switch.
7015 In the absence of this switch, GNAT does not attempt
7016 inlining and does not need to access the bodies of
7017 subprograms for which @code{pragma Inline} is specified if they are not
7018 in the current unit.
7019
7020 If you specify this switch the compiler will access these bodies,
7021 creating an extra source dependency for the resulting object file, and
7022 where possible, the call will be inlined.
7023 For further details on when inlining is possible
7024 see @ref{Inlining of Subprograms}.
7025
7026 @item -gnatN
7027 @cindex @option{-gnatN} (@command{gcc})
7028 This switch activates front-end inlining which also
7029 generates additional dependencies.
7030
7031 When using a gcc-based back end (in practice this means using any version
7032 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7033 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7034 Historically front end inlining was more extensive than the gcc back end
7035 inlining, but that is no longer the case.
7036 @end table
7037
7038 @node Auxiliary Output Control
7039 @subsection Auxiliary Output Control
7040
7041 @table @option
7042 @item -gnatt
7043 @cindex @option{-gnatt} (@command{gcc})
7044 @cindex Writing internal trees
7045 @cindex Internal trees, writing to file
7046 Causes GNAT to write the internal tree for a unit to a file (with the
7047 extension @file{.adt}.
7048 This not normally required, but is used by separate analysis tools.
7049 Typically
7050 these tools do the necessary compilations automatically, so you should
7051 not have to specify this switch in normal operation.
7052 Note that the combination of switches @option{-gnatct}
7053 generates a tree in the form required by ASIS applications.
7054
7055 @item -gnatu
7056 @cindex @option{-gnatu} (@command{gcc})
7057 Print a list of units required by this compilation on @file{stdout}.
7058 The listing includes all units on which the unit being compiled depends
7059 either directly or indirectly.
7060
7061 @ifclear vms
7062 @item -pass-exit-codes
7063 @cindex @option{-pass-exit-codes} (@command{gcc})
7064 If this switch is not used, the exit code returned by @command{gcc} when
7065 compiling multiple files indicates whether all source files have
7066 been successfully used to generate object files or not.
7067
7068 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7069 exit status and allows an integrated development environment to better
7070 react to a compilation failure. Those exit status are:
7071
7072 @table @asis
7073 @item 5
7074 There was an error in at least one source file.
7075 @item 3
7076 At least one source file did not generate an object file.
7077 @item 2
7078 The compiler died unexpectedly (internal error for example).
7079 @item 0
7080 An object file has been generated for every source file.
7081 @end table
7082 @end ifclear
7083 @end table
7084
7085 @node Debugging Control
7086 @subsection Debugging Control
7087
7088 @table @option
7089 @c !sort!
7090 @cindex Debugging options
7091 @ifclear vms
7092 @item -gnatd@var{x}
7093 @cindex @option{-gnatd} (@command{gcc})
7094 Activate internal debugging switches. @var{x} is a letter or digit, or
7095 string of letters or digits, which specifies the type of debugging
7096 outputs desired. Normally these are used only for internal development
7097 or system debugging purposes. You can find full documentation for these
7098 switches in the body of the @code{Debug} unit in the compiler source
7099 file @file{debug.adb}.
7100 @end ifclear
7101
7102 @item -gnatG[=nn]
7103 @cindex @option{-gnatG} (@command{gcc})
7104 This switch causes the compiler to generate auxiliary output containing
7105 a pseudo-source listing of the generated expanded code. Like most Ada
7106 compilers, GNAT works by first transforming the high level Ada code into
7107 lower level constructs. For example, tasking operations are transformed
7108 into calls to the tasking run-time routines. A unique capability of GNAT
7109 is to list this expanded code in a form very close to normal Ada source.
7110 This is very useful in understanding the implications of various Ada
7111 usage on the efficiency of the generated code. There are many cases in
7112 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7113 generate a lot of run-time code. By using @option{-gnatG} you can identify
7114 these cases, and consider whether it may be desirable to modify the coding
7115 approach to improve efficiency.
7116
7117 The optional parameter @code{nn} if present after -gnatG specifies an
7118 alternative maximum line length that overrides the normal default of 72.
7119 This value is in the range 40-999999, values less than 40 being silently
7120 reset to 40. The equal sign is optional.
7121
7122 The format of the output is very similar to standard Ada source, and is
7123 easily understood by an Ada programmer. The following special syntactic
7124 additions correspond to low level features used in the generated code that
7125 do not have any exact analogies in pure Ada source form. The following
7126 is a partial list of these special constructions. See the spec
7127 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7128
7129 If the switch @option{-gnatL} is used in conjunction with
7130 @cindex @option{-gnatL} (@command{gcc})
7131 @option{-gnatG}, then the original source lines are interspersed
7132 in the expanded source (as comment lines with the original line number).
7133
7134 @table @code
7135 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7136 Shows the storage pool being used for an allocator.
7137
7138 @item at end @var{procedure-name};
7139 Shows the finalization (cleanup) procedure for a scope.
7140
7141 @item (if @var{expr} then @var{expr} else @var{expr})
7142 Conditional expression equivalent to the @code{x?y:z} construction in C.
7143
7144 @item @var{target}^^^(@var{source})
7145 A conversion with floating-point truncation instead of rounding.
7146
7147 @item @var{target}?(@var{source})
7148 A conversion that bypasses normal Ada semantic checking. In particular
7149 enumeration types and fixed-point types are treated simply as integers.
7150
7151 @item @var{target}?^^^(@var{source})
7152 Combines the above two cases.
7153
7154 @item @var{x} #/ @var{y}
7155 @itemx @var{x} #mod @var{y}
7156 @itemx @var{x} #* @var{y}
7157 @itemx @var{x} #rem @var{y}
7158 A division or multiplication of fixed-point values which are treated as
7159 integers without any kind of scaling.
7160
7161 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7162 Shows the storage pool associated with a @code{free} statement.
7163
7164 @item [subtype or type declaration]
7165 Used to list an equivalent declaration for an internally generated
7166 type that is referenced elsewhere in the listing.
7167
7168 @item freeze @var{type-name} @ovar{actions}
7169 Shows the point at which @var{type-name} is frozen, with possible
7170 associated actions to be performed at the freeze point.
7171
7172 @item reference @var{itype}
7173 Reference (and hence definition) to internal type @var{itype}.
7174
7175 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7176 Intrinsic function call.
7177
7178 @item @var{label-name} : label
7179 Declaration of label @var{labelname}.
7180
7181 @item #$ @var{subprogram-name}
7182 An implicit call to a run-time support routine
7183 (to meet the requirement of H.3.1(9) in a
7184 convenient manner).
7185
7186 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7187 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7188 @var{expr}, but handled more efficiently).
7189
7190 @item [constraint_error]
7191 Raise the @code{Constraint_Error} exception.
7192
7193 @item @var{expression}'reference
7194 A pointer to the result of evaluating @var{expression}.
7195
7196 @item @var{target-type}!(@var{source-expression})
7197 An unchecked conversion of @var{source-expression} to @var{target-type}.
7198
7199 @item [@var{numerator}/@var{denominator}]
7200 Used to represent internal real literals (that) have no exact
7201 representation in base 2-16 (for example, the result of compile time
7202 evaluation of the expression 1.0/27.0).
7203 @end table
7204
7205 @item -gnatD[=nn]
7206 @cindex @option{-gnatD} (@command{gcc})
7207 When used in conjunction with @option{-gnatG}, this switch causes
7208 the expanded source, as described above for
7209 @option{-gnatG} to be written to files with names
7210 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7211 instead of to the standard output file. For
7212 example, if the source file name is @file{hello.adb}, then a file
7213 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7214 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7215 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7216 you to do source level debugging using the generated code which is
7217 sometimes useful for complex code, for example to find out exactly
7218 which part of a complex construction raised an exception. This switch
7219 also suppress generation of cross-reference information (see
7220 @option{-gnatx}) since otherwise the cross-reference information
7221 would refer to the @file{^.dg^.DG^} file, which would cause
7222 confusion since this is not the original source file.
7223
7224 Note that @option{-gnatD} actually implies @option{-gnatG}
7225 automatically, so it is not necessary to give both options.
7226 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7227
7228 If the switch @option{-gnatL} is used in conjunction with
7229 @cindex @option{-gnatL} (@command{gcc})
7230 @option{-gnatDG}, then the original source lines are interspersed
7231 in the expanded source (as comment lines with the original line number).
7232
7233 The optional parameter @code{nn} if present after -gnatD specifies an
7234 alternative maximum line length that overrides the normal default of 72.
7235 This value is in the range 40-999999, values less than 40 being silently
7236 reset to 40. The equal sign is optional.
7237
7238 @item -gnatr
7239 @cindex @option{-gnatr} (@command{gcc})
7240 @cindex pragma Restrictions
7241 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7242 so that violation of restrictions causes warnings rather than illegalities.
7243 This is useful during the development process when new restrictions are added
7244 or investigated. The switch also causes pragma Profile to be treated as
7245 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7246 restriction warnings rather than restrictions.
7247
7248 @ifclear vms
7249 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7250 @cindex @option{-gnatR} (@command{gcc})
7251 This switch controls output from the compiler of a listing showing
7252 representation information for declared types and objects. For
7253 @option{-gnatR0}, no information is output (equivalent to omitting
7254 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7255 so @option{-gnatR} with no parameter has the same effect), size and alignment
7256 information is listed for declared array and record types. For
7257 @option{-gnatR2}, size and alignment information is listed for all
7258 declared types and objects. Finally @option{-gnatR3} includes symbolic
7259 expressions for values that are computed at run time for
7260 variant records. These symbolic expressions have a mostly obvious
7261 format with #n being used to represent the value of the n'th
7262 discriminant. See source files @file{repinfo.ads/adb} in the
7263 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7264 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7265 the output is to a file with the name @file{^file.rep^file_REP^} where
7266 file is the name of the corresponding source file.
7267 @end ifclear
7268 @ifset vms
7269 @item /REPRESENTATION_INFO
7270 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7271 This qualifier controls output from the compiler of a listing showing
7272 representation information for declared types and objects. For
7273 @option{/REPRESENTATION_INFO=NONE}, no information is output
7274 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7275 @option{/REPRESENTATION_INFO} without option is equivalent to
7276 @option{/REPRESENTATION_INFO=ARRAYS}.
7277 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7278 information is listed for declared array and record types. For
7279 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7280 is listed for all expression information for values that are computed
7281 at run time for variant records. These symbolic expressions have a mostly
7282 obvious format with #n being used to represent the value of the n'th
7283 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7284 @code{GNAT} sources for full details on the format of
7285 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7286 If _FILE is added at the end of an option
7287 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7288 then the output is to a file with the name @file{file_REP} where
7289 file is the name of the corresponding source file.
7290 @end ifset
7291 Note that it is possible for record components to have zero size. In
7292 this case, the component clause uses an obvious extension of permitted
7293 Ada syntax, for example @code{at 0 range 0 .. -1}.
7294
7295 Representation information requires that code be generated (since it is the
7296 code generator that lays out complex data structures). If an attempt is made
7297 to output representation information when no code is generated, for example
7298 when a subunit is compiled on its own, then no information can be generated
7299 and the compiler outputs a message to this effect.
7300
7301 @item -gnatS
7302 @cindex @option{-gnatS} (@command{gcc})
7303 The use of the switch @option{-gnatS} for an
7304 Ada compilation will cause the compiler to output a
7305 representation of package Standard in a form very
7306 close to standard Ada. It is not quite possible to
7307 do this entirely in standard Ada (since new
7308 numeric base types cannot be created in standard
7309 Ada), but the output is easily
7310 readable to any Ada programmer, and is useful to
7311 determine the characteristics of target dependent
7312 types in package Standard.
7313
7314 @item -gnatx
7315 @cindex @option{-gnatx} (@command{gcc})
7316 Normally the compiler generates full cross-referencing information in
7317 the @file{ALI} file. This information is used by a number of tools,
7318 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7319 suppresses this information. This saves some space and may slightly
7320 speed up compilation, but means that these tools cannot be used.
7321 @end table
7322
7323 @node Exception Handling Control
7324 @subsection Exception Handling Control
7325
7326 @noindent
7327 GNAT uses two methods for handling exceptions at run-time. The
7328 @code{setjmp/longjmp} method saves the context when entering
7329 a frame with an exception handler. Then when an exception is
7330 raised, the context can be restored immediately, without the
7331 need for tracing stack frames. This method provides very fast
7332 exception propagation, but introduces significant overhead for
7333 the use of exception handlers, even if no exception is raised.
7334
7335 The other approach is called ``zero cost'' exception handling.
7336 With this method, the compiler builds static tables to describe
7337 the exception ranges. No dynamic code is required when entering
7338 a frame containing an exception handler. When an exception is
7339 raised, the tables are used to control a back trace of the
7340 subprogram invocation stack to locate the required exception
7341 handler. This method has considerably poorer performance for
7342 the propagation of exceptions, but there is no overhead for
7343 exception handlers if no exception is raised. Note that in this
7344 mode and in the context of mixed Ada and C/C++ programming,
7345 to propagate an exception through a C/C++ code, the C/C++ code
7346 must be compiled with the @option{-funwind-tables} GCC's
7347 option.
7348
7349 The following switches may be used to control which of the
7350 two exception handling methods is used.
7351
7352 @table @option
7353 @c !sort!
7354
7355 @item --RTS=sjlj
7356 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7357 This switch causes the setjmp/longjmp run-time (when available) to be used
7358 for exception handling. If the default
7359 mechanism for the target is zero cost exceptions, then
7360 this switch can be used to modify this default, and must be
7361 used for all units in the partition.
7362 This option is rarely used. One case in which it may be
7363 advantageous is if you have an application where exception
7364 raising is common and the overall performance of the
7365 application is improved by favoring exception propagation.
7366
7367 @item --RTS=zcx
7368 @cindex @option{--RTS=zcx} (@command{gnatmake})
7369 @cindex Zero Cost Exceptions
7370 This switch causes the zero cost approach to be used
7371 for exception handling. If this is the default mechanism for the
7372 target (see below), then this switch is unneeded. If the default
7373 mechanism for the target is setjmp/longjmp exceptions, then
7374 this switch can be used to modify this default, and must be
7375 used for all units in the partition.
7376 This option can only be used if the zero cost approach
7377 is available for the target in use, otherwise it will generate an error.
7378 @end table
7379
7380 @noindent
7381 The same option @option{--RTS} must be used both for @command{gcc}
7382 and @command{gnatbind}. Passing this option to @command{gnatmake}
7383 (@pxref{Switches for gnatmake}) will ensure the required consistency
7384 through the compilation and binding steps.
7385
7386 @node Units to Sources Mapping Files
7387 @subsection Units to Sources Mapping Files
7388
7389 @table @option
7390
7391 @item -gnatem^^=^@var{path}
7392 @cindex @option{-gnatem} (@command{gcc})
7393 A mapping file is a way to communicate to the compiler two mappings:
7394 from unit names to file names (without any directory information) and from
7395 file names to path names (with full directory information). These mappings
7396 are used by the compiler to short-circuit the path search.
7397
7398 The use of mapping files is not required for correct operation of the
7399 compiler, but mapping files can improve efficiency, particularly when
7400 sources are read over a slow network connection. In normal operation,
7401 you need not be concerned with the format or use of mapping files,
7402 and the @option{-gnatem} switch is not a switch that you would use
7403 explicitly. it is intended only for use by automatic tools such as
7404 @command{gnatmake} running under the project file facility. The
7405 description here of the format of mapping files is provided
7406 for completeness and for possible use by other tools.
7407
7408 A mapping file is a sequence of sets of three lines. In each set,
7409 the first line is the unit name, in lower case, with ``@code{%s}''
7410 appended for
7411 specs and ``@code{%b}'' appended for bodies; the second line is the
7412 file name; and the third line is the path name.
7413
7414 Example:
7415 @smallexample
7416    main%b
7417    main.2.ada
7418    /gnat/project1/sources/main.2.ada
7419 @end smallexample
7420
7421 When the switch @option{-gnatem} is specified, the compiler will create
7422 in memory the two mappings from the specified file. If there is any problem
7423 (nonexistent file, truncated file or duplicate entries), no mapping will
7424 be created.
7425
7426 Several @option{-gnatem} switches may be specified; however, only the last
7427 one on the command line will be taken into account.
7428
7429 When using a project file, @command{gnatmake} create a temporary mapping file
7430 and communicates it to the compiler using this switch.
7431
7432 @end table
7433
7434 @node Integrated Preprocessing
7435 @subsection Integrated Preprocessing
7436
7437 @noindent
7438 GNAT sources may be preprocessed immediately before compilation.
7439 In this case, the actual
7440 text of the source is not the text of the source file, but is derived from it
7441 through a process called preprocessing. Integrated preprocessing is specified
7442 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7443 indicates, through a text file, the preprocessing data to be used.
7444 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7445
7446 @noindent
7447 Note that when integrated preprocessing is used, the output from the
7448 preprocessor is not written to any external file. Instead it is passed
7449 internally to the compiler. If you need to preserve the result of
7450 preprocessing in a file, then you should use @command{gnatprep}
7451 to perform the desired preprocessing in stand-alone mode.
7452
7453 @noindent
7454 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7455 used when Integrated Preprocessing is used. The reason is that preprocessing
7456 with another Preprocessing Data file without changing the sources will
7457 not trigger recompilation without this switch.
7458
7459 @noindent
7460 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7461 always trigger recompilation for sources that are preprocessed,
7462 because @command{gnatmake} cannot compute the checksum of the source after
7463 preprocessing.
7464
7465 @noindent
7466 The actual preprocessing function is described in details in section
7467 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7468 preprocessing is triggered and parameterized.
7469
7470 @table @code
7471
7472 @item -gnatep=@var{file}
7473 @cindex @option{-gnatep} (@command{gcc})
7474 This switch indicates to the compiler the file name (without directory
7475 information) of the preprocessor data file to use. The preprocessor data file
7476 should be found in the source directories.
7477
7478 @noindent
7479 A preprocessing data file is a text file with significant lines indicating
7480 how should be preprocessed either a specific source or all sources not
7481 mentioned in other lines. A significant line is a nonempty, non-comment line.
7482 Comments are similar to Ada comments.
7483
7484 @noindent
7485 Each significant line starts with either a literal string or the character '*'.
7486 A literal string is the file name (without directory information) of the source
7487 to preprocess. A character '*' indicates the preprocessing for all the sources
7488 that are not specified explicitly on other lines (order of the lines is not
7489 significant). It is an error to have two lines with the same file name or two
7490 lines starting with the character '*'.
7491
7492 @noindent
7493 After the file name or the character '*', another optional literal string
7494 indicating the file name of the definition file to be used for preprocessing
7495 (@pxref{Form of Definitions File}). The definition files are found by the
7496 compiler in one of the source directories. In some cases, when compiling
7497 a source in a directory other than the current directory, if the definition
7498 file is in the current directory, it may be necessary to add the current
7499 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7500 the compiler would not find the definition file.
7501
7502 @noindent
7503 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7504 be found. Those ^switches^switches^ are:
7505
7506 @table @code
7507
7508 @item -b
7509 Causes both preprocessor lines and the lines deleted by
7510 preprocessing to be replaced by blank lines, preserving the line number.
7511 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7512 it cancels the effect of @option{-c}.
7513
7514 @item -c
7515 Causes both preprocessor lines and the lines deleted
7516 by preprocessing to be retained as comments marked
7517 with the special string ``@code{--! }''.
7518
7519 @item -Dsymbol=value
7520 Define or redefine a symbol, associated with value. A symbol is an Ada
7521 identifier, or an Ada reserved word, with the exception of @code{if},
7522 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7523 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7524 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7525 same name defined in a definition file.
7526
7527 @item -s
7528 Causes a sorted list of symbol names and values to be
7529 listed on the standard output file.
7530
7531 @item -u
7532 Causes undefined symbols to be treated as having the value @code{FALSE}
7533 in the context
7534 of a preprocessor test. In the absence of this option, an undefined symbol in
7535 a @code{#if} or @code{#elsif} test will be treated as an error.
7536
7537 @end table
7538
7539 @noindent
7540 Examples of valid lines in a preprocessor data file:
7541
7542 @smallexample
7543   "toto.adb"  "prep.def" -u
7544   --  preprocess "toto.adb", using definition file "prep.def",
7545   --  undefined symbol are False.
7546
7547   * -c -DVERSION=V101
7548   --  preprocess all other sources without a definition file;
7549   --  suppressed lined are commented; symbol VERSION has the value V101.
7550
7551   "titi.adb" "prep2.def" -s
7552   --  preprocess "titi.adb", using definition file "prep2.def";
7553   --  list all symbols with their values.
7554 @end smallexample
7555
7556 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7557 @cindex @option{-gnateD} (@command{gcc})
7558 Define or redefine a preprocessing symbol, associated with value. If no value
7559 is given on the command line, then the value of the symbol is @code{True}.
7560 A symbol is an identifier, following normal Ada (case-insensitive)
7561 rules for its syntax, and value is any sequence (including an empty sequence)
7562 of characters from the set (letters, digits, period, underline).
7563 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7564 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7565
7566 @noindent
7567 A symbol declared with this ^switch^switch^ on the command line replaces a
7568 symbol with the same name either in a definition file or specified with a
7569 ^switch^switch^ -D in the preprocessor data file.
7570
7571 @noindent
7572 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7573
7574 @item -gnateG
7575 When integrated preprocessing is performed and the preprocessor modifies
7576 the source text, write the result of this preprocessing into a file
7577 <source>^.prep^_prep^.
7578
7579 @end table
7580
7581 @node Code Generation Control
7582 @subsection Code Generation Control
7583
7584 @noindent
7585
7586 The GCC technology provides a wide range of target dependent
7587 @option{-m} switches for controlling
7588 details of code generation with respect to different versions of
7589 architectures. This includes variations in instruction sets (e.g.@:
7590 different members of the power pc family), and different requirements
7591 for optimal arrangement of instructions (e.g.@: different members of
7592 the x86 family). The list of available @option{-m} switches may be
7593 found in the GCC documentation.
7594
7595 Use of these @option{-m} switches may in some cases result in improved
7596 code performance.
7597
7598 The GNAT Pro technology is tested and qualified without any
7599 @option{-m} switches,
7600 so generally the most reliable approach is to avoid the use of these
7601 switches. However, we generally expect most of these switches to work
7602 successfully with GNAT Pro, and many customers have reported successful
7603 use of these options.
7604
7605 Our general advice is to avoid the use of @option{-m} switches unless
7606 special needs lead to requirements in this area. In particular,
7607 there is no point in using @option{-m} switches to improve performance
7608 unless you actually see a performance improvement.
7609
7610 @ifset vms
7611 @node Return Codes
7612 @subsection Return Codes
7613 @cindex Return Codes
7614 @cindex @option{/RETURN_CODES=VMS}
7615
7616 @noindent
7617 On VMS, GNAT compiled programs return POSIX-style codes by default,
7618 e.g.@: @option{/RETURN_CODES=POSIX}.
7619
7620 To enable VMS style return codes, use GNAT BIND and LINK with the option
7621 @option{/RETURN_CODES=VMS}. For example:
7622
7623 @smallexample
7624 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7625 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7626 @end smallexample
7627
7628 @noindent
7629 Programs built with /RETURN_CODES=VMS are suitable to be called in
7630 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7631 are suitable for spawning with appropriate GNAT RTL routines.
7632
7633 @end ifset
7634
7635 @node Search Paths and the Run-Time Library (RTL)
7636 @section Search Paths and the Run-Time Library (RTL)
7637
7638 @noindent
7639 With the GNAT source-based library system, the compiler must be able to
7640 find source files for units that are needed by the unit being compiled.
7641 Search paths are used to guide this process.
7642
7643 The compiler compiles one source file whose name must be given
7644 explicitly on the command line. In other words, no searching is done
7645 for this file. To find all other source files that are needed (the most
7646 common being the specs of units), the compiler examines the following
7647 directories, in the following order:
7648
7649 @enumerate
7650 @item
7651 The directory containing the source file of the main unit being compiled
7652 (the file name on the command line).
7653
7654 @item
7655 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7656 @command{gcc} command line, in the order given.
7657
7658 @item
7659 @findex ADA_PRJ_INCLUDE_FILE
7660 Each of the directories listed in the text file whose name is given
7661 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7662
7663 @noindent
7664 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7665 driver when project files are used. It should not normally be set
7666 by other means.
7667
7668 @item
7669 @findex ADA_INCLUDE_PATH
7670 Each of the directories listed in the value of the
7671 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7672 @ifclear vms
7673 Construct this value
7674 exactly as the @env{PATH} environment variable: a list of directory
7675 names separated by colons (semicolons when working with the NT version).
7676 @end ifclear
7677 @ifset vms
7678 Normally, define this value as a logical name containing a comma separated
7679 list of directory names.
7680
7681 This variable can also be defined by means of an environment string
7682 (an argument to the HP C exec* set of functions).
7683
7684 Logical Name:
7685 @smallexample
7686 DEFINE ANOTHER_PATH FOO:[BAG]
7687 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7688 @end smallexample
7689
7690 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7691 first, followed by the standard Ada
7692 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7693 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7694 (Text_IO, Sequential_IO, etc)
7695 instead of the standard Ada packages. Thus, in order to get the standard Ada
7696 packages by default, ADA_INCLUDE_PATH must be redefined.
7697 @end ifset
7698
7699 @item
7700 The content of the @file{ada_source_path} file which is part of the GNAT
7701 installation tree and is used to store standard libraries such as the
7702 GNAT Run Time Library (RTL) source files.
7703 @ifclear vms
7704 @ref{Installing a library}
7705 @end ifclear
7706 @end enumerate
7707
7708 @noindent
7709 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7710 inhibits the use of the directory
7711 containing the source file named in the command line. You can still
7712 have this directory on your search path, but in this case it must be
7713 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7714
7715 Specifying the switch @option{-nostdinc}
7716 inhibits the search of the default location for the GNAT Run Time
7717 Library (RTL) source files.
7718
7719 The compiler outputs its object files and ALI files in the current
7720 working directory.
7721 @ifclear vms
7722 Caution: The object file can be redirected with the @option{-o} switch;
7723 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7724 so the @file{ALI} file will not go to the right place. Therefore, you should
7725 avoid using the @option{-o} switch.
7726 @end ifclear
7727
7728 @findex System.IO
7729 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7730 children make up the GNAT RTL, together with the simple @code{System.IO}
7731 package used in the @code{"Hello World"} example. The sources for these units
7732 are needed by the compiler and are kept together in one directory. Not
7733 all of the bodies are needed, but all of the sources are kept together
7734 anyway. In a normal installation, you need not specify these directory
7735 names when compiling or binding. Either the environment variables or
7736 the built-in defaults cause these files to be found.
7737
7738 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7739 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7740 consisting of child units of @code{GNAT}. This is a collection of generally
7741 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7742 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7743
7744 Besides simplifying access to the RTL, a major use of search paths is
7745 in compiling sources from multiple directories. This can make
7746 development environments much more flexible.
7747
7748 @node Order of Compilation Issues
7749 @section Order of Compilation Issues
7750
7751 @noindent
7752 If, in our earlier example, there was a spec for the @code{hello}
7753 procedure, it would be contained in the file @file{hello.ads}; yet this
7754 file would not have to be explicitly compiled. This is the result of the
7755 model we chose to implement library management. Some of the consequences
7756 of this model are as follows:
7757
7758 @itemize @bullet
7759 @item
7760 There is no point in compiling specs (except for package
7761 specs with no bodies) because these are compiled as needed by clients. If
7762 you attempt a useless compilation, you will receive an error message.
7763 It is also useless to compile subunits because they are compiled as needed
7764 by the parent.
7765
7766 @item
7767 There are no order of compilation requirements: performing a
7768 compilation never obsoletes anything. The only way you can obsolete
7769 something and require recompilations is to modify one of the
7770 source files on which it depends.
7771
7772 @item
7773 There is no library as such, apart from the ALI files
7774 (@pxref{The Ada Library Information Files}, for information on the format
7775 of these files). For now we find it convenient to create separate ALI files,
7776 but eventually the information therein may be incorporated into the object
7777 file directly.
7778
7779 @item
7780 When you compile a unit, the source files for the specs of all units
7781 that it @code{with}'s, all its subunits, and the bodies of any generics it
7782 instantiates must be available (reachable by the search-paths mechanism
7783 described above), or you will receive a fatal error message.
7784 @end itemize
7785
7786 @node Examples
7787 @section Examples
7788
7789 @noindent
7790 The following are some typical Ada compilation command line examples:
7791
7792 @table @code
7793 @item $ gcc -c xyz.adb
7794 Compile body in file @file{xyz.adb} with all default options.
7795
7796 @ifclear vms
7797 @item $ gcc -c -O2 -gnata xyz-def.adb
7798 @end ifclear
7799 @ifset vms
7800 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7801 @end ifset
7802
7803 Compile the child unit package in file @file{xyz-def.adb} with extensive
7804 optimizations, and pragma @code{Assert}/@code{Debug} statements
7805 enabled.
7806
7807 @item $ gcc -c -gnatc abc-def.adb
7808 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7809 mode.
7810 @end table
7811
7812 @node Binding Using gnatbind
7813 @chapter Binding Using @code{gnatbind}
7814 @findex gnatbind
7815
7816 @menu
7817 * Running gnatbind::
7818 * Switches for gnatbind::
7819 * Command-Line Access::
7820 * Search Paths for gnatbind::
7821 * Examples of gnatbind Usage::
7822 @end menu
7823
7824 @noindent
7825 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7826 to bind compiled GNAT objects.
7827
7828 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7829 driver (see @ref{The GNAT Driver and Project Files}).
7830
7831 The @code{gnatbind} program performs four separate functions:
7832
7833 @enumerate
7834 @item
7835 Checks that a program is consistent, in accordance with the rules in
7836 Chapter 10 of the Ada Reference Manual. In particular, error
7837 messages are generated if a program uses inconsistent versions of a
7838 given unit.
7839
7840 @item
7841 Checks that an acceptable order of elaboration exists for the program
7842 and issues an error message if it cannot find an order of elaboration
7843 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7844
7845 @item
7846 Generates a main program incorporating the given elaboration order.
7847 This program is a small Ada package (body and spec) that
7848 must be subsequently compiled
7849 using the GNAT compiler. The necessary compilation step is usually
7850 performed automatically by @command{gnatlink}. The two most important
7851 functions of this program
7852 are to call the elaboration routines of units in an appropriate order
7853 and to call the main program.
7854
7855 @item
7856 Determines the set of object files required by the given main program.
7857 This information is output in the forms of comments in the generated program,
7858 to be read by the @command{gnatlink} utility used to link the Ada application.
7859 @end enumerate
7860
7861 @node Running gnatbind
7862 @section Running @code{gnatbind}
7863
7864 @noindent
7865 The form of the @code{gnatbind} command is
7866
7867 @smallexample
7868 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7869 @end smallexample
7870
7871 @noindent
7872 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7873 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7874 package in two files whose names are
7875 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7876 For example, if given the
7877 parameter @file{hello.ali}, for a main program contained in file
7878 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7879 and @file{b~hello.adb}.
7880
7881 When doing consistency checking, the binder takes into consideration
7882 any source files it can locate. For example, if the binder determines
7883 that the given main program requires the package @code{Pack}, whose
7884 @file{.ALI}
7885 file is @file{pack.ali} and whose corresponding source spec file is
7886 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7887 (using the same search path conventions as previously described for the
7888 @command{gcc} command). If it can locate this source file, it checks that
7889 the time stamps
7890 or source checksums of the source and its references to in @file{ALI} files
7891 match. In other words, any @file{ALI} files that mentions this spec must have
7892 resulted from compiling this version of the source file (or in the case
7893 where the source checksums match, a version close enough that the
7894 difference does not matter).
7895
7896 @cindex Source files, use by binder
7897 The effect of this consistency checking, which includes source files, is
7898 that the binder ensures that the program is consistent with the latest
7899 version of the source files that can be located at bind time. Editing a
7900 source file without compiling files that depend on the source file cause
7901 error messages to be generated by the binder.
7902
7903 For example, suppose you have a main program @file{hello.adb} and a
7904 package @code{P}, from file @file{p.ads} and you perform the following
7905 steps:
7906
7907 @enumerate
7908 @item
7909 Enter @code{gcc -c hello.adb} to compile the main program.
7910
7911 @item
7912 Enter @code{gcc -c p.ads} to compile package @code{P}.
7913
7914 @item
7915 Edit file @file{p.ads}.
7916
7917 @item
7918 Enter @code{gnatbind hello}.
7919 @end enumerate
7920
7921 @noindent
7922 At this point, the file @file{p.ali} contains an out-of-date time stamp
7923 because the file @file{p.ads} has been edited. The attempt at binding
7924 fails, and the binder generates the following error messages:
7925
7926 @smallexample
7927 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7928 error: "p.ads" has been modified and must be recompiled
7929 @end smallexample
7930
7931 @noindent
7932 Now both files must be recompiled as indicated, and then the bind can
7933 succeed, generating a main program. You need not normally be concerned
7934 with the contents of this file, but for reference purposes a sample
7935 binder output file is given in @ref{Example of Binder Output File}.
7936
7937 In most normal usage, the default mode of @command{gnatbind} which is to
7938 generate the main package in Ada, as described in the previous section.
7939 In particular, this means that any Ada programmer can read and understand
7940 the generated main program. It can also be debugged just like any other
7941 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7942 @command{gnatbind} and @command{gnatlink}.
7943
7944 However for some purposes it may be convenient to generate the main
7945 program in C rather than Ada. This may for example be helpful when you
7946 are generating a mixed language program with the main program in C. The
7947 GNAT compiler itself is an example.
7948 The use of the @option{^-C^/BIND_FILE=C^} switch
7949 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7950 be generated in C (and compiled using the gnu C compiler).
7951
7952 @node Switches for gnatbind
7953 @section Switches for @command{gnatbind}
7954
7955 @noindent
7956 The following switches are available with @code{gnatbind}; details will
7957 be presented in subsequent sections.
7958
7959 @menu
7960 * Consistency-Checking Modes::
7961 * Binder Error Message Control::
7962 * Elaboration Control::
7963 * Output Control::
7964 * Binding with Non-Ada Main Programs::
7965 * Binding Programs with No Main Subprogram::
7966 @end menu
7967
7968 @table @option
7969 @c !sort!
7970
7971 @item --version
7972 @cindex @option{--version} @command{gnatbind}
7973 Display Copyright and version, then exit disregarding all other options.
7974
7975 @item --help
7976 @cindex @option{--help} @command{gnatbind}
7977 If @option{--version} was not used, display usage, then exit disregarding
7978 all other options.
7979
7980 @item -a
7981 @cindex @option{-a} @command{gnatbind}
7982 Indicates that, if supported by the platform, the adainit procedure should
7983 be treated as an initialisation routine by the linker (a constructor). This
7984 is intended to be used by the Project Manager to automatically initialize
7985 shared Stand-Alone Libraries.
7986
7987 @item ^-aO^/OBJECT_SEARCH^
7988 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7989 Specify directory to be searched for ALI files.
7990
7991 @item ^-aI^/SOURCE_SEARCH^
7992 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7993 Specify directory to be searched for source file.
7994
7995 @item ^-A^/BIND_FILE=ADA^
7996 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7997 Generate binder program in Ada (default)
7998
7999 @item ^-b^/REPORT_ERRORS=BRIEF^
8000 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8001 Generate brief messages to @file{stderr} even if verbose mode set.
8002
8003 @item ^-c^/NOOUTPUT^
8004 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8005 Check only, no generation of binder output file.
8006
8007 @item ^-C^/BIND_FILE=C^
8008 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
8009 Generate binder program in C
8010
8011 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8012 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8013 This switch can be used to change the default task stack size value
8014 to a specified size @var{nn}, which is expressed in bytes by default, or
8015 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8016 with @var{m}.
8017 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8018 in effect, to completing all task specs with
8019 @smallexample @c ada
8020    pragma Storage_Size (nn);
8021 @end smallexample
8022 When they do not already have such a pragma.
8023
8024 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8025 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8026 This switch can be used to change the default secondary stack size value
8027 to a specified size @var{nn}, which is expressed in bytes by default, or
8028 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8029 with @var{m}.
8030
8031 The secondary stack is used to deal with functions that return a variable
8032 sized result, for example a function returning an unconstrained
8033 String. There are two ways in which this secondary stack is allocated.
8034
8035 For most targets, the secondary stack is growing on demand and is allocated
8036 as a chain of blocks in the heap. The -D option is not very
8037 relevant. It only give some control over the size of the allocated
8038 blocks (whose size is the minimum of the default secondary stack size value,
8039 and the actual size needed for the current allocation request).
8040
8041 For certain targets, notably VxWorks 653,
8042 the secondary stack is allocated by carving off a fixed ratio chunk of the
8043 primary task stack. The -D option is used to define the
8044 size of the environment task's secondary stack.
8045
8046 @item ^-e^/ELABORATION_DEPENDENCIES^
8047 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8048 Output complete list of elaboration-order dependencies.
8049
8050 @item ^-E^/STORE_TRACEBACKS^
8051 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8052 Store tracebacks in exception occurrences when the target supports it.
8053 This is the default with the zero cost exception mechanism.
8054 @ignore
8055 @c The following may get moved to an appendix
8056 This option is currently supported on the following targets:
8057 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8058 @end ignore
8059 See also the packages @code{GNAT.Traceback} and
8060 @code{GNAT.Traceback.Symbolic} for more information.
8061 @ifclear vms
8062 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8063 @command{gcc} option.
8064 @end ifclear
8065
8066 @item ^-F^/FORCE_ELABS_FLAGS^
8067 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8068 Force the checks of elaboration flags. @command{gnatbind} does not normally
8069 generate checks of elaboration flags for the main executable, except when
8070 a Stand-Alone Library is used. However, there are cases when this cannot be
8071 detected by gnatbind. An example is importing an interface of a Stand-Alone
8072 Library through a pragma Import and only specifying through a linker switch
8073 this Stand-Alone Library. This switch is used to guarantee that elaboration
8074 flag checks are generated.
8075
8076 @item ^-h^/HELP^
8077 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8078 Output usage (help) information
8079
8080 @item ^-I^/SEARCH^
8081 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8082 Specify directory to be searched for source and ALI files.
8083
8084 @item ^-I-^/NOCURRENT_DIRECTORY^
8085 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8086 Do not look for sources in the current directory where @code{gnatbind} was
8087 invoked, and do not look for ALI files in the directory containing the
8088 ALI file named in the @code{gnatbind} command line.
8089
8090 @item ^-l^/ORDER_OF_ELABORATION^
8091 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8092 Output chosen elaboration order.
8093
8094 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8095 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8096 Bind the units for library building. In this case the adainit and
8097 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8098 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8099 ^@var{xxx}final^@var{XXX}FINAL^.
8100 Implies ^-n^/NOCOMPILE^.
8101 @ifclear vms
8102 (@xref{GNAT and Libraries}, for more details.)
8103 @end ifclear
8104 @ifset vms
8105 On OpenVMS, these init and final procedures are exported in uppercase
8106 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8107 the init procedure will be "TOTOINIT" and the exported name of the final
8108 procedure will be "TOTOFINAL".
8109 @end ifset
8110
8111 @item ^-Mxyz^/RENAME_MAIN=xyz^
8112 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8113 Rename generated main program from main to xyz. This option is
8114 supported on cross environments only.
8115
8116 @item ^-m^/ERROR_LIMIT=^@var{n}
8117 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8118 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8119 in the range 1..999999. The default value if no switch is
8120 given is 9999. If the number of warnings reaches this limit, then a
8121 message is output and further warnings are suppressed, the bind
8122 continues in this case. If the number of errors reaches this
8123 limit, then a message is output and the bind is abandoned.
8124 A value of zero means that no limit is enforced. The equal
8125 sign is optional.
8126
8127 @ifset unw
8128 Furthermore, under Windows, the sources pointed to by the libraries path
8129 set in the registry are not searched for.
8130 @end ifset
8131
8132 @item ^-n^/NOMAIN^
8133 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8134 No main program.
8135
8136 @item -nostdinc
8137 @cindex @option{-nostdinc} (@command{gnatbind})
8138 Do not look for sources in the system default directory.
8139
8140 @item -nostdlib
8141 @cindex @option{-nostdlib} (@command{gnatbind})
8142 Do not look for library files in the system default directory.
8143
8144 @item --RTS=@var{rts-path}
8145 @cindex @option{--RTS} (@code{gnatbind})
8146 Specifies the default location of the runtime library. Same meaning as the
8147 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8148
8149 @item ^-o ^/OUTPUT=^@var{file}
8150 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8151 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8152 Note that if this option is used, then linking must be done manually,
8153 gnatlink cannot be used.
8154
8155 @item ^-O^/OBJECT_LIST^
8156 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8157 Output object list.
8158
8159 @item ^-p^/PESSIMISTIC_ELABORATION^
8160 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8161 Pessimistic (worst-case) elaboration order
8162
8163 @item ^-R^-R^
8164 @cindex @option{^-R^-R^} (@command{gnatbind})
8165 Output closure source list.
8166
8167 @item ^-s^/READ_SOURCES=ALL^
8168 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8169 Require all source files to be present.
8170
8171 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8172 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8173 Specifies the value to be used when detecting uninitialized scalar
8174 objects with pragma Initialize_Scalars.
8175 The @var{xxx} ^string specified with the switch^option^ may be either
8176 @itemize @bullet
8177 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8178 @item ``@option{^lo^LOW^}'' for the lowest possible value
8179 @item ``@option{^hi^HIGH^}'' for the highest possible value
8180 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8181 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8182 @end itemize
8183
8184 In addition, you can specify @option{-Sev} to indicate that the value is
8185 to be set at run time. In this case, the program will look for an environment
8186 @cindex GNAT_INIT_SCALARS
8187 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8188 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8189 If no environment variable is found, or if it does not have a valid value,
8190 then the default is @option{in} (invalid values).
8191
8192 @ifclear vms
8193 @item -static
8194 @cindex @option{-static} (@code{gnatbind})
8195 Link against a static GNAT run time.
8196
8197 @item -shared
8198 @cindex @option{-shared} (@code{gnatbind})
8199 Link against a shared GNAT run time when available.
8200 @end ifclear
8201
8202 @item ^-t^/NOTIME_STAMP_CHECK^
8203 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8204 Tolerate time stamp and other consistency errors
8205
8206 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8207 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8208 Set the time slice value to @var{n} milliseconds. If the system supports
8209 the specification of a specific time slice value, then the indicated value
8210 is used. If the system does not support specific time slice values, but
8211 does support some general notion of round-robin scheduling, then any
8212 nonzero value will activate round-robin scheduling.
8213
8214 A value of zero is treated specially. It turns off time
8215 slicing, and in addition, indicates to the tasking run time that the
8216 semantics should match as closely as possible the Annex D
8217 requirements of the Ada RM, and in particular sets the default
8218 scheduling policy to @code{FIFO_Within_Priorities}.
8219
8220 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8221 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8222 Enable dynamic stack usage, with @var{n} results stored and displayed
8223 at program termination. A result is generated when a task
8224 terminates. Results that can't be stored are displayed on the fly, at
8225 task termination. This option is currently not supported on Itanium
8226 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8227
8228 @item ^-v^/REPORT_ERRORS=VERBOSE^
8229 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8230 Verbose mode. Write error messages, header, summary output to
8231 @file{stdout}.
8232
8233 @ifclear vms
8234 @item -w@var{x}
8235 @cindex @option{-w} (@code{gnatbind})
8236 Warning mode (@var{x}=s/e for suppress/treat as error)
8237 @end ifclear
8238
8239 @ifset vms
8240 @item /WARNINGS=NORMAL
8241 @cindex @option{/WARNINGS} (@code{gnatbind})
8242 Normal warnings mode. Warnings are issued but ignored
8243
8244 @item /WARNINGS=SUPPRESS
8245 @cindex @option{/WARNINGS} (@code{gnatbind})
8246 All warning messages are suppressed
8247
8248 @item /WARNINGS=ERROR
8249 @cindex @option{/WARNINGS} (@code{gnatbind})
8250 Warning messages are treated as fatal errors
8251 @end ifset
8252
8253 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8254 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8255 Override default wide character encoding for standard Text_IO files.
8256
8257 @item ^-x^/READ_SOURCES=NONE^
8258 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8259 Exclude source files (check object consistency only).
8260
8261 @ifset vms
8262 @item /READ_SOURCES=AVAILABLE
8263 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8264 Default mode, in which sources are checked for consistency only if
8265 they are available.
8266 @end ifset
8267
8268 @item ^-y^/ENABLE_LEAP_SECONDS^
8269 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8270 Enable leap seconds support in @code{Ada.Calendar} and its children.
8271
8272 @item ^-z^/ZERO_MAIN^
8273 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8274 No main subprogram.
8275 @end table
8276
8277 @ifclear vms
8278 @noindent
8279 You may obtain this listing of switches by running @code{gnatbind} with
8280 no arguments.
8281 @end ifclear
8282
8283 @node Consistency-Checking Modes
8284 @subsection Consistency-Checking Modes
8285
8286 @noindent
8287 As described earlier, by default @code{gnatbind} checks
8288 that object files are consistent with one another and are consistent
8289 with any source files it can locate. The following switches control binder
8290 access to sources.
8291
8292 @table @option
8293 @c !sort!
8294 @item ^-s^/READ_SOURCES=ALL^
8295 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8296 Require source files to be present. In this mode, the binder must be
8297 able to locate all source files that are referenced, in order to check
8298 their consistency. In normal mode, if a source file cannot be located it
8299 is simply ignored. If you specify this switch, a missing source
8300 file is an error.
8301
8302 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8303 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8304 Override default wide character encoding for standard Text_IO files.
8305 Normally the default wide character encoding method used for standard
8306 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8307 the main source input (see description of switch
8308 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8309 use of this switch for the binder (which has the same set of
8310 possible arguments) overrides this default as specified.
8311
8312 @item ^-x^/READ_SOURCES=NONE^
8313 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8314 Exclude source files. In this mode, the binder only checks that ALI
8315 files are consistent with one another. Source files are not accessed.
8316 The binder runs faster in this mode, and there is still a guarantee that
8317 the resulting program is self-consistent.
8318 If a source file has been edited since it was last compiled, and you
8319 specify this switch, the binder will not detect that the object
8320 file is out of date with respect to the source file. Note that this is the
8321 mode that is automatically used by @command{gnatmake} because in this
8322 case the checking against sources has already been performed by
8323 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8324
8325 @ifset vms
8326 @item /READ_SOURCES=AVAILABLE
8327 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8328 This is the default mode in which source files are checked if they are
8329 available, and ignored if they are not available.
8330 @end ifset
8331 @end table
8332
8333 @node Binder Error Message Control
8334 @subsection Binder Error Message Control
8335
8336 @noindent
8337 The following switches provide control over the generation of error
8338 messages from the binder:
8339
8340 @table @option
8341 @c !sort!
8342 @item ^-v^/REPORT_ERRORS=VERBOSE^
8343 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8344 Verbose mode. In the normal mode, brief error messages are generated to
8345 @file{stderr}. If this switch is present, a header is written
8346 to @file{stdout} and any error messages are directed to @file{stdout}.
8347 All that is written to @file{stderr} is a brief summary message.
8348
8349 @item ^-b^/REPORT_ERRORS=BRIEF^
8350 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8351 Generate brief error messages to @file{stderr} even if verbose mode is
8352 specified. This is relevant only when used with the
8353 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8354
8355 @ifclear vms
8356 @item -m@var{n}
8357 @cindex @option{-m} (@code{gnatbind})
8358 Limits the number of error messages to @var{n}, a decimal integer in the
8359 range 1-999. The binder terminates immediately if this limit is reached.
8360
8361 @item -M@var{xxx}
8362 @cindex @option{-M} (@code{gnatbind})
8363 Renames the generated main program from @code{main} to @code{xxx}.
8364 This is useful in the case of some cross-building environments, where
8365 the actual main program is separate from the one generated
8366 by @code{gnatbind}.
8367 @end ifclear
8368
8369 @item ^-ws^/WARNINGS=SUPPRESS^
8370 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8371 @cindex Warnings
8372 Suppress all warning messages.
8373
8374 @item ^-we^/WARNINGS=ERROR^
8375 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8376 Treat any warning messages as fatal errors.
8377
8378 @ifset vms
8379 @item /WARNINGS=NORMAL
8380 Standard mode with warnings generated, but warnings do not get treated
8381 as errors.
8382 @end ifset
8383
8384 @item ^-t^/NOTIME_STAMP_CHECK^
8385 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8386 @cindex Time stamp checks, in binder
8387 @cindex Binder consistency checks
8388 @cindex Consistency checks, in binder
8389 The binder performs a number of consistency checks including:
8390
8391 @itemize @bullet
8392 @item
8393 Check that time stamps of a given source unit are consistent
8394 @item
8395 Check that checksums of a given source unit are consistent
8396 @item
8397 Check that consistent versions of @code{GNAT} were used for compilation
8398 @item
8399 Check consistency of configuration pragmas as required
8400 @end itemize
8401
8402 @noindent
8403 Normally failure of such checks, in accordance with the consistency
8404 requirements of the Ada Reference Manual, causes error messages to be
8405 generated which abort the binder and prevent the output of a binder
8406 file and subsequent link to obtain an executable.
8407
8408 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8409 into warnings, so that
8410 binding and linking can continue to completion even in the presence of such
8411 errors. The result may be a failed link (due to missing symbols), or a
8412 non-functional executable which has undefined semantics.
8413 @emph{This means that
8414 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8415 with extreme care.}
8416 @end table
8417
8418 @node Elaboration Control
8419 @subsection Elaboration Control
8420
8421 @noindent
8422 The following switches provide additional control over the elaboration
8423 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8424
8425 @table @option
8426 @item ^-p^/PESSIMISTIC_ELABORATION^
8427 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8428 Normally the binder attempts to choose an elaboration order that is
8429 likely to minimize the likelihood of an elaboration order error resulting
8430 in raising a @code{Program_Error} exception. This switch reverses the
8431 action of the binder, and requests that it deliberately choose an order
8432 that is likely to maximize the likelihood of an elaboration error.
8433 This is useful in ensuring portability and avoiding dependence on
8434 accidental fortuitous elaboration ordering.
8435
8436 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8437 switch if dynamic
8438 elaboration checking is used (@option{-gnatE} switch used for compilation).
8439 This is because in the default static elaboration mode, all necessary
8440 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8441 These implicit pragmas are still respected by the binder in
8442 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8443 safe elaboration order is assured.
8444 @end table
8445
8446 @node Output Control
8447 @subsection Output Control
8448
8449 @noindent
8450 The following switches allow additional control over the output
8451 generated by the binder.
8452
8453 @table @option
8454 @c !sort!
8455
8456 @item ^-A^/BIND_FILE=ADA^
8457 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8458 Generate binder program in Ada (default). The binder program is named
8459 @file{b~@var{mainprog}.adb} by default. This can be changed with
8460 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8461
8462 @item ^-c^/NOOUTPUT^
8463 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8464 Check only. Do not generate the binder output file. In this mode the
8465 binder performs all error checks but does not generate an output file.
8466
8467 @item ^-C^/BIND_FILE=C^
8468 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8469 Generate binder program in C. The binder program is named
8470 @file{b_@var{mainprog}.c}.
8471 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8472 option.
8473
8474 @item ^-e^/ELABORATION_DEPENDENCIES^
8475 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8476 Output complete list of elaboration-order dependencies, showing the
8477 reason for each dependency. This output can be rather extensive but may
8478 be useful in diagnosing problems with elaboration order. The output is
8479 written to @file{stdout}.
8480
8481 @item ^-h^/HELP^
8482 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8483 Output usage information. The output is written to @file{stdout}.
8484
8485 @item ^-K^/LINKER_OPTION_LIST^
8486 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8487 Output linker options to @file{stdout}. Includes library search paths,
8488 contents of pragmas Ident and Linker_Options, and libraries added
8489 by @code{gnatbind}.
8490
8491 @item ^-l^/ORDER_OF_ELABORATION^
8492 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8493 Output chosen elaboration order. The output is written to @file{stdout}.
8494
8495 @item ^-O^/OBJECT_LIST^
8496 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8497 Output full names of all the object files that must be linked to provide
8498 the Ada component of the program. The output is written to @file{stdout}.
8499 This list includes the files explicitly supplied and referenced by the user
8500 as well as implicitly referenced run-time unit files. The latter are
8501 omitted if the corresponding units reside in shared libraries. The
8502 directory names for the run-time units depend on the system configuration.
8503
8504 @item ^-o ^/OUTPUT=^@var{file}
8505 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8506 Set name of output file to @var{file} instead of the normal
8507 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8508 binder generated body filename. In C mode you would normally give
8509 @var{file} an extension of @file{.c} because it will be a C source program.
8510 Note that if this option is used, then linking must be done manually.
8511 It is not possible to use gnatlink in this case, since it cannot locate
8512 the binder file.
8513
8514 @item ^-r^/RESTRICTION_LIST^
8515 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8516 Generate list of @code{pragma Restrictions} that could be applied to
8517 the current unit. This is useful for code audit purposes, and also may
8518 be used to improve code generation in some cases.
8519
8520 @end table
8521
8522 @node Binding with Non-Ada Main Programs
8523 @subsection Binding with Non-Ada Main Programs
8524
8525 @noindent
8526 In our description so far we have assumed that the main
8527 program is in Ada, and that the task of the binder is to generate a
8528 corresponding function @code{main} that invokes this Ada main
8529 program. GNAT also supports the building of executable programs where
8530 the main program is not in Ada, but some of the called routines are
8531 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8532 The following switch is used in this situation:
8533
8534 @table @option
8535 @item ^-n^/NOMAIN^
8536 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8537 No main program. The main program is not in Ada.
8538 @end table
8539
8540 @noindent
8541 In this case, most of the functions of the binder are still required,
8542 but instead of generating a main program, the binder generates a file
8543 containing the following callable routines:
8544
8545 @table @code
8546 @item adainit
8547 @findex adainit
8548 You must call this routine to initialize the Ada part of the program by
8549 calling the necessary elaboration routines. A call to @code{adainit} is
8550 required before the first call to an Ada subprogram.
8551
8552 Note that it is assumed that the basic execution environment must be setup
8553 to be appropriate for Ada execution at the point where the first Ada
8554 subprogram is called. In particular, if the Ada code will do any
8555 floating-point operations, then the FPU must be setup in an appropriate
8556 manner. For the case of the x86, for example, full precision mode is
8557 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8558 that the FPU is in the right state.
8559
8560 @item adafinal
8561 @findex adafinal
8562 You must call this routine to perform any library-level finalization
8563 required by the Ada subprograms. A call to @code{adafinal} is required
8564 after the last call to an Ada subprogram, and before the program
8565 terminates.
8566 @end table
8567
8568 @noindent
8569 If the @option{^-n^/NOMAIN^} switch
8570 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8571 @cindex Binder, multiple input files
8572 is given, more than one ALI file may appear on
8573 the command line for @code{gnatbind}. The normal @dfn{closure}
8574 calculation is performed for each of the specified units. Calculating
8575 the closure means finding out the set of units involved by tracing
8576 @code{with} references. The reason it is necessary to be able to
8577 specify more than one ALI file is that a given program may invoke two or
8578 more quite separate groups of Ada units.
8579
8580 The binder takes the name of its output file from the last specified ALI
8581 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8582 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8583 The output is an Ada unit in source form that can
8584 be compiled with GNAT unless the -C switch is used in which case the
8585 output is a C source file, which must be compiled using the C compiler.
8586 This compilation occurs automatically as part of the @command{gnatlink}
8587 processing.
8588
8589 Currently the GNAT run time requires a FPU using 80 bits mode
8590 precision. Under targets where this is not the default it is required to
8591 call GNAT.Float_Control.Reset before using floating point numbers (this
8592 include float computation, float input and output) in the Ada code. A
8593 side effect is that this could be the wrong mode for the foreign code
8594 where floating point computation could be broken after this call.
8595
8596 @node Binding Programs with No Main Subprogram
8597 @subsection Binding Programs with No Main Subprogram
8598
8599 @noindent
8600 It is possible to have an Ada program which does not have a main
8601 subprogram. This program will call the elaboration routines of all the
8602 packages, then the finalization routines.
8603
8604 The following switch is used to bind programs organized in this manner:
8605
8606 @table @option
8607 @item ^-z^/ZERO_MAIN^
8608 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8609 Normally the binder checks that the unit name given on the command line
8610 corresponds to a suitable main subprogram. When this switch is used,
8611 a list of ALI files can be given, and the execution of the program
8612 consists of elaboration of these units in an appropriate order. Note
8613 that the default wide character encoding method for standard Text_IO
8614 files is always set to Brackets if this switch is set (you can use
8615 the binder switch
8616 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8617 @end table
8618
8619 @node Command-Line Access
8620 @section Command-Line Access
8621
8622 @noindent
8623 The package @code{Ada.Command_Line} provides access to the command-line
8624 arguments and program name. In order for this interface to operate
8625 correctly, the two variables
8626
8627 @smallexample
8628 @group
8629 int gnat_argc;
8630 char **gnat_argv;
8631 @end group
8632 @end smallexample
8633
8634 @noindent
8635 @findex gnat_argv
8636 @findex gnat_argc
8637 are declared in one of the GNAT library routines. These variables must
8638 be set from the actual @code{argc} and @code{argv} values passed to the
8639 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8640 generates the C main program to automatically set these variables.
8641 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8642 set these variables. If they are not set, the procedures in
8643 @code{Ada.Command_Line} will not be available, and any attempt to use
8644 them will raise @code{Constraint_Error}. If command line access is
8645 required, your main program must set @code{gnat_argc} and
8646 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8647 it.
8648
8649 @node Search Paths for gnatbind
8650 @section Search Paths for @code{gnatbind}
8651
8652 @noindent
8653 The binder takes the name of an ALI file as its argument and needs to
8654 locate source files as well as other ALI files to verify object consistency.
8655
8656 For source files, it follows exactly the same search rules as @command{gcc}
8657 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8658 directories searched are:
8659
8660 @enumerate
8661 @item
8662 The directory containing the ALI file named in the command line, unless
8663 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8664
8665 @item
8666 All directories specified by @option{^-I^/SEARCH^}
8667 switches on the @code{gnatbind}
8668 command line, in the order given.
8669
8670 @item
8671 @findex ADA_PRJ_OBJECTS_FILE
8672 Each of the directories listed in the text file whose name is given
8673 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8674
8675 @noindent
8676 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8677 driver when project files are used. It should not normally be set
8678 by other means.
8679
8680 @item
8681 @findex ADA_OBJECTS_PATH
8682 Each of the directories listed in the value of the
8683 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8684 @ifset unw
8685 Construct this value
8686 exactly as the @env{PATH} environment variable: a list of directory
8687 names separated by colons (semicolons when working with the NT version
8688 of GNAT).
8689 @end ifset
8690 @ifset vms
8691 Normally, define this value as a logical name containing a comma separated
8692 list of directory names.
8693
8694 This variable can also be defined by means of an environment string
8695 (an argument to the HP C exec* set of functions).
8696
8697 Logical Name:
8698 @smallexample
8699 DEFINE ANOTHER_PATH FOO:[BAG]
8700 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8701 @end smallexample
8702
8703 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8704 first, followed by the standard Ada
8705 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8706 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8707 (Text_IO, Sequential_IO, etc)
8708 instead of the standard Ada packages. Thus, in order to get the standard Ada
8709 packages by default, ADA_OBJECTS_PATH must be redefined.
8710 @end ifset
8711
8712 @item
8713 The content of the @file{ada_object_path} file which is part of the GNAT
8714 installation tree and is used to store standard libraries such as the
8715 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8716 specified.
8717 @ifclear vms
8718 @ref{Installing a library}
8719 @end ifclear
8720 @end enumerate
8721
8722 @noindent
8723 In the binder the switch @option{^-I^/SEARCH^}
8724 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8725 is used to specify both source and
8726 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8727 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8728 instead if you want to specify
8729 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8730 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8731 if you want to specify library paths
8732 only. This means that for the binder
8733 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8734 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8735 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8736 The binder generates the bind file (a C language source file) in the
8737 current working directory.
8738
8739 @findex Ada
8740 @findex System
8741 @findex Interfaces
8742 @findex GNAT
8743 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8744 children make up the GNAT Run-Time Library, together with the package
8745 GNAT and its children, which contain a set of useful additional
8746 library functions provided by GNAT. The sources for these units are
8747 needed by the compiler and are kept together in one directory. The ALI
8748 files and object files generated by compiling the RTL are needed by the
8749 binder and the linker and are kept together in one directory, typically
8750 different from the directory containing the sources. In a normal
8751 installation, you need not specify these directory names when compiling
8752 or binding. Either the environment variables or the built-in defaults
8753 cause these files to be found.
8754
8755 Besides simplifying access to the RTL, a major use of search paths is
8756 in compiling sources from multiple directories. This can make
8757 development environments much more flexible.
8758
8759 @node Examples of gnatbind Usage
8760 @section Examples of @code{gnatbind} Usage
8761
8762 @noindent
8763 This section contains a number of examples of using the GNAT binding
8764 utility @code{gnatbind}.
8765
8766 @table @code
8767 @item gnatbind hello
8768 The main program @code{Hello} (source program in @file{hello.adb}) is
8769 bound using the standard switch settings. The generated main program is
8770 @file{b~hello.adb}. This is the normal, default use of the binder.
8771
8772 @ifclear vms
8773 @item gnatbind hello -o mainprog.adb
8774 @end ifclear
8775 @ifset vms
8776 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8777 @end ifset
8778 The main program @code{Hello} (source program in @file{hello.adb}) is
8779 bound using the standard switch settings. The generated main program is
8780 @file{mainprog.adb} with the associated spec in
8781 @file{mainprog.ads}. Note that you must specify the body here not the
8782 spec, in the case where the output is in Ada. Note that if this option
8783 is used, then linking must be done manually, since gnatlink will not
8784 be able to find the generated file.
8785
8786 @ifclear vms
8787 @item gnatbind main -C -o mainprog.c -x
8788 @end ifclear
8789 @ifset vms
8790 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8791 @end ifset
8792 The main program @code{Main} (source program in
8793 @file{main.adb}) is bound, excluding source files from the
8794 consistency checking, generating
8795 the file @file{mainprog.c}.
8796
8797 @ifclear vms
8798 @item gnatbind -x main_program -C -o mainprog.c
8799 This command is exactly the same as the previous example. Switches may
8800 appear anywhere in the command line, and single letter switches may be
8801 combined into a single switch.
8802 @end ifclear
8803
8804 @ifclear vms
8805 @item gnatbind -n math dbase -C -o ada-control.c
8806 @end ifclear
8807 @ifset vms
8808 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8809 @end ifset
8810 The main program is in a language other than Ada, but calls to
8811 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8812 to @code{gnatbind} generates the file @file{ada-control.c} containing
8813 the @code{adainit} and @code{adafinal} routines to be called before and
8814 after accessing the Ada units.
8815 @end table
8816
8817 @c ------------------------------------
8818 @node Linking Using gnatlink
8819 @chapter Linking Using @command{gnatlink}
8820 @c ------------------------------------
8821 @findex gnatlink
8822
8823 @noindent
8824 This chapter discusses @command{gnatlink}, a tool that links
8825 an Ada program and builds an executable file. This utility
8826 invokes the system linker ^(via the @command{gcc} command)^^
8827 with a correct list of object files and library references.
8828 @command{gnatlink} automatically determines the list of files and
8829 references for the Ada part of a program. It uses the binder file
8830 generated by the @command{gnatbind} to determine this list.
8831
8832 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8833 driver (see @ref{The GNAT Driver and Project Files}).
8834
8835 @menu
8836 * Running gnatlink::
8837 * Switches for gnatlink::
8838 @end menu
8839
8840 @node Running gnatlink
8841 @section Running @command{gnatlink}
8842
8843 @noindent
8844 The form of the @command{gnatlink} command is
8845
8846 @smallexample
8847 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8848            @ovar{non-Ada objects} @ovar{linker options}
8849 @end smallexample
8850
8851 @noindent
8852 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8853 non-Ada objects
8854 or linker options) may be in any order, provided that no non-Ada object may
8855 be mistaken for a main @file{ALI} file.
8856 Any file name @file{F} without the @file{.ali}
8857 extension will be taken as the main @file{ALI} file if a file exists
8858 whose name is the concatenation of @file{F} and @file{.ali}.
8859
8860 @noindent
8861 @file{@var{mainprog}.ali} references the ALI file of the main program.
8862 The @file{.ali} extension of this file can be omitted. From this
8863 reference, @command{gnatlink} locates the corresponding binder file
8864 @file{b~@var{mainprog}.adb} and, using the information in this file along
8865 with the list of non-Ada objects and linker options, constructs a
8866 linker command file to create the executable.
8867
8868 The arguments other than the @command{gnatlink} switches and the main
8869 @file{ALI} file are passed to the linker uninterpreted.
8870 They typically include the names of
8871 object files for units written in other languages than Ada and any library
8872 references required to resolve references in any of these foreign language
8873 units, or in @code{Import} pragmas in any Ada units.
8874
8875 @var{linker options} is an optional list of linker specific
8876 switches.
8877 The default linker called by gnatlink is @command{gcc} which in
8878 turn calls the appropriate system linker.
8879 Standard options for the linker such as @option{-lmy_lib} or
8880 @option{-Ldir} can be added as is.
8881 For options that are not recognized by
8882 @command{gcc} as linker options, use the @command{gcc} switches
8883 @option{-Xlinker} or @option{-Wl,}.
8884 Refer to the GCC documentation for
8885 details. Here is an example showing how to generate a linker map:
8886
8887 @smallexample
8888 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8889 @end smallexample
8890
8891 Using @var{linker options} it is possible to set the program stack and
8892 heap size.
8893 @ifset unw
8894 See @ref{Setting Stack Size from gnatlink} and
8895 @ref{Setting Heap Size from gnatlink}.
8896 @end ifset
8897
8898 @command{gnatlink} determines the list of objects required by the Ada
8899 program and prepends them to the list of objects passed to the linker.
8900 @command{gnatlink} also gathers any arguments set by the use of
8901 @code{pragma Linker_Options} and adds them to the list of arguments
8902 presented to the linker.
8903
8904 @ifset vms
8905 @command{gnatlink} accepts the following types of extra files on the command
8906 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8907 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8908 handled according to their extension.
8909 @end ifset
8910
8911 @node Switches for gnatlink
8912 @section Switches for @command{gnatlink}
8913
8914 @noindent
8915 The following switches are available with the @command{gnatlink} utility:
8916
8917 @table @option
8918 @c !sort!
8919
8920 @item --version
8921 @cindex @option{--version} @command{gnatlink}
8922 Display Copyright and version, then exit disregarding all other options.
8923
8924 @item --help
8925 @cindex @option{--help} @command{gnatlink}
8926 If @option{--version} was not used, display usage, then exit disregarding
8927 all other options.
8928
8929 @item ^-A^/BIND_FILE=ADA^
8930 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8931 The binder has generated code in Ada. This is the default.
8932
8933 @item ^-C^/BIND_FILE=C^
8934 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8935 If instead of generating a file in Ada, the binder has generated one in
8936 C, then the linker needs to know about it. Use this switch to signal
8937 to @command{gnatlink} that the binder has generated C code rather than
8938 Ada code.
8939
8940 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8941 @cindex Command line length
8942 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8943 On some targets, the command line length is limited, and @command{gnatlink}
8944 will generate a separate file for the linker if the list of object files
8945 is too long.
8946 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8947 to be generated even if
8948 the limit is not exceeded. This is useful in some cases to deal with
8949 special situations where the command line length is exceeded.
8950
8951 @item ^-g^/DEBUG^
8952 @cindex Debugging information, including
8953 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8954 The option to include debugging information causes the Ada bind file (in
8955 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8956 @option{^-g^/DEBUG^}.
8957 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8958 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8959 Without @option{^-g^/DEBUG^}, the binder removes these files by
8960 default. The same procedure apply if a C bind file was generated using
8961 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8962 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8963
8964 @item ^-n^/NOCOMPILE^
8965 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8966 Do not compile the file generated by the binder. This may be used when
8967 a link is rerun with different options, but there is no need to recompile
8968 the binder file.
8969
8970 @item ^-v^/VERBOSE^
8971 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8972 Causes additional information to be output, including a full list of the
8973 included object files. This switch option is most useful when you want
8974 to see what set of object files are being used in the link step.
8975
8976 @item ^-v -v^/VERBOSE/VERBOSE^
8977 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8978 Very verbose mode. Requests that the compiler operate in verbose mode when
8979 it compiles the binder file, and that the system linker run in verbose mode.
8980
8981 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8982 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8983 @var{exec-name} specifies an alternate name for the generated
8984 executable program. If this switch is omitted, the executable has the same
8985 name as the main unit. For example, @code{gnatlink try.ali} creates
8986 an executable called @file{^try^TRY.EXE^}.
8987
8988 @ifclear vms
8989 @item -b @var{target}
8990 @cindex @option{-b} (@command{gnatlink})
8991 Compile your program to run on @var{target}, which is the name of a
8992 system configuration. You must have a GNAT cross-compiler built if
8993 @var{target} is not the same as your host system.
8994
8995 @item -B@var{dir}
8996 @cindex @option{-B} (@command{gnatlink})
8997 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8998 from @var{dir} instead of the default location. Only use this switch
8999 when multiple versions of the GNAT compiler are available.
9000 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9001 for further details. You would normally use the @option{-b} or
9002 @option{-V} switch instead.
9003
9004 @item --GCC=@var{compiler_name}
9005 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9006 Program used for compiling the binder file. The default is
9007 @command{gcc}. You need to use quotes around @var{compiler_name} if
9008 @code{compiler_name} contains spaces or other separator characters.
9009 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9010 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9011 inserted after your command name. Thus in the above example the compiler
9012 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9013 A limitation of this syntax is that the name and path name of the executable
9014 itself must not include any embedded spaces. If the compiler executable is
9015 different from the default one (gcc or <prefix>-gcc), then the back-end
9016 switches in the ALI file are not used to compile the binder generated source.
9017 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9018 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9019 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9020 is taken into account. However, all the additional switches are also taken
9021 into account. Thus,
9022 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9023 @option{--GCC="bar -x -y -z -t"}.
9024
9025 @item --LINK=@var{name}
9026 @cindex @option{--LINK=} (@command{gnatlink})
9027 @var{name} is the name of the linker to be invoked. This is especially
9028 useful in mixed language programs since languages such as C++ require
9029 their own linker to be used. When this switch is omitted, the default
9030 name for the linker is @command{gcc}. When this switch is used, the
9031 specified linker is called instead of @command{gcc} with exactly the same
9032 parameters that would have been passed to @command{gcc} so if the desired
9033 linker requires different parameters it is necessary to use a wrapper
9034 script that massages the parameters before invoking the real linker. It
9035 may be useful to control the exact invocation by using the verbose
9036 switch.
9037
9038 @end ifclear
9039
9040 @ifset vms
9041 @item /DEBUG=TRACEBACK
9042 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9043 This qualifier causes sufficient information to be included in the
9044 executable file to allow a traceback, but does not include the full
9045 symbol information needed by the debugger.
9046
9047 @item /IDENTIFICATION="<string>"
9048 @code{"<string>"} specifies the string to be stored in the image file
9049 identification field in the image header.
9050 It overrides any pragma @code{Ident} specified string.
9051
9052 @item /NOINHIBIT-EXEC
9053 Generate the executable file even if there are linker warnings.
9054
9055 @item /NOSTART_FILES
9056 Don't link in the object file containing the ``main'' transfer address.
9057 Used when linking with a foreign language main program compiled with an
9058 HP compiler.
9059
9060 @item /STATIC
9061 Prefer linking with object libraries over sharable images, even without
9062 /DEBUG.
9063 @end ifset
9064
9065 @end table
9066
9067 @node The GNAT Make Program gnatmake
9068 @chapter The GNAT Make Program @command{gnatmake}
9069 @findex gnatmake
9070
9071 @menu
9072 * Running gnatmake::
9073 * Switches for gnatmake::
9074 * Mode Switches for gnatmake::
9075 * Notes on the Command Line::
9076 * How gnatmake Works::
9077 * Examples of gnatmake Usage::
9078 @end menu
9079 @noindent
9080 A typical development cycle when working on an Ada program consists of
9081 the following steps:
9082
9083 @enumerate
9084 @item
9085 Edit some sources to fix bugs.
9086
9087 @item
9088 Add enhancements.
9089
9090 @item
9091 Compile all sources affected.
9092
9093 @item
9094 Rebind and relink.
9095
9096 @item
9097 Test.
9098 @end enumerate
9099
9100 @noindent
9101 The third step can be tricky, because not only do the modified files
9102 @cindex Dependency rules
9103 have to be compiled, but any files depending on these files must also be
9104 recompiled. The dependency rules in Ada can be quite complex, especially
9105 in the presence of overloading, @code{use} clauses, generics and inlined
9106 subprograms.
9107
9108 @command{gnatmake} automatically takes care of the third and fourth steps
9109 of this process. It determines which sources need to be compiled,
9110 compiles them, and binds and links the resulting object files.
9111
9112 Unlike some other Ada make programs, the dependencies are always
9113 accurately recomputed from the new sources. The source based approach of
9114 the GNAT compilation model makes this possible. This means that if
9115 changes to the source program cause corresponding changes in
9116 dependencies, they will always be tracked exactly correctly by
9117 @command{gnatmake}.
9118
9119 @node Running gnatmake
9120 @section Running @command{gnatmake}
9121
9122 @noindent
9123 The usual form of the @command{gnatmake} command is
9124
9125 @smallexample
9126 $ gnatmake @ovar{switches} @var{file_name}
9127       @ovar{file_names} @ovar{mode_switches}
9128 @end smallexample
9129
9130 @noindent
9131 The only required argument is one @var{file_name}, which specifies
9132 a compilation unit that is a main program. Several @var{file_names} can be
9133 specified: this will result in several executables being built.
9134 If @code{switches} are present, they can be placed before the first
9135 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9136 If @var{mode_switches} are present, they must always be placed after
9137 the last @var{file_name} and all @code{switches}.
9138
9139 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9140 extension may be omitted from the @var{file_name} arguments. However, if
9141 you are using non-standard extensions, then it is required that the
9142 extension be given. A relative or absolute directory path can be
9143 specified in a @var{file_name}, in which case, the input source file will
9144 be searched for in the specified directory only. Otherwise, the input
9145 source file will first be searched in the directory where
9146 @command{gnatmake} was invoked and if it is not found, it will be search on
9147 the source path of the compiler as described in
9148 @ref{Search Paths and the Run-Time Library (RTL)}.
9149
9150 All @command{gnatmake} output (except when you specify
9151 @option{^-M^/DEPENDENCIES_LIST^}) is to
9152 @file{stderr}. The output produced by the
9153 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9154 @file{stdout}.
9155
9156 @node Switches for gnatmake
9157 @section Switches for @command{gnatmake}
9158
9159 @noindent
9160 You may specify any of the following switches to @command{gnatmake}:
9161
9162 @table @option
9163 @c !sort!
9164
9165 @item --version
9166 @cindex @option{--version} @command{gnatmake}
9167 Display Copyright and version, then exit disregarding all other options.
9168
9169 @item --help
9170 @cindex @option{--help} @command{gnatmake}
9171 If @option{--version} was not used, display usage, then exit disregarding
9172 all other options.
9173
9174 @ifclear vms
9175 @item --GCC=@var{compiler_name}
9176 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9177 Program used for compiling. The default is `@command{gcc}'. You need to use
9178 quotes around @var{compiler_name} if @code{compiler_name} contains
9179 spaces or other separator characters. As an example @option{--GCC="foo -x
9180 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9181 compiler. A limitation of this syntax is that the name and path name of
9182 the executable itself must not include any embedded spaces. Note that
9183 switch @option{-c} is always inserted after your command name. Thus in the
9184 above example the compiler command that will be used by @command{gnatmake}
9185 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9186 used, only the last @var{compiler_name} is taken into account. However,
9187 all the additional switches are also taken into account. Thus,
9188 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9189 @option{--GCC="bar -x -y -z -t"}.
9190
9191 @item --GNATBIND=@var{binder_name}
9192 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9193 Program used for binding. The default is `@code{gnatbind}'. You need to
9194 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9195 or other separator characters. As an example @option{--GNATBIND="bar -x
9196 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9197 binder. Binder switches that are normally appended by @command{gnatmake}
9198 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9199 A limitation of this syntax is that the name and path name of the executable
9200 itself must not include any embedded spaces.
9201
9202 @item --GNATLINK=@var{linker_name}
9203 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9204 Program used for linking. The default is `@command{gnatlink}'. You need to
9205 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9206 or other separator characters. As an example @option{--GNATLINK="lan -x
9207 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9208 linker. Linker switches that are normally appended by @command{gnatmake} to
9209 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9210 A limitation of this syntax is that the name and path name of the executable
9211 itself must not include any embedded spaces.
9212
9213 @end ifclear
9214
9215 @item ^-a^/ALL_FILES^
9216 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9217 Consider all files in the make process, even the GNAT internal system
9218 files (for example, the predefined Ada library files), as well as any
9219 locked files. Locked files are files whose ALI file is write-protected.
9220 By default,
9221 @command{gnatmake} does not check these files,
9222 because the assumption is that the GNAT internal files are properly up
9223 to date, and also that any write protected ALI files have been properly
9224 installed. Note that if there is an installation problem, such that one
9225 of these files is not up to date, it will be properly caught by the
9226 binder.
9227 You may have to specify this switch if you are working on GNAT
9228 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9229 in conjunction with @option{^-f^/FORCE_COMPILE^}
9230 if you need to recompile an entire application,
9231 including run-time files, using special configuration pragmas,
9232 such as a @code{Normalize_Scalars} pragma.
9233
9234 By default
9235 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9236 internal files with
9237 @ifclear vms
9238 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9239 @end ifclear
9240 @ifset vms
9241 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9242 @end ifset
9243
9244 @item ^-b^/ACTIONS=BIND^
9245 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9246 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9247 compilation and binding, but no link.
9248 Can be combined with @option{^-l^/ACTIONS=LINK^}
9249 to do binding and linking. When not combined with
9250 @option{^-c^/ACTIONS=COMPILE^}
9251 all the units in the closure of the main program must have been previously
9252 compiled and must be up to date. The root unit specified by @var{file_name}
9253 may be given without extension, with the source extension or, if no GNAT
9254 Project File is specified, with the ALI file extension.
9255
9256 @item ^-c^/ACTIONS=COMPILE^
9257 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9258 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9259 is also specified. Do not perform linking, except if both
9260 @option{^-b^/ACTIONS=BIND^} and
9261 @option{^-l^/ACTIONS=LINK^} are also specified.
9262 If the root unit specified by @var{file_name} is not a main unit, this is the
9263 default. Otherwise @command{gnatmake} will attempt binding and linking
9264 unless all objects are up to date and the executable is more recent than
9265 the objects.
9266
9267 @item ^-C^/MAPPING^
9268 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9269 Use a temporary mapping file. A mapping file is a way to communicate to the
9270 compiler two mappings: from unit names to file names (without any directory
9271 information) and from file names to path names (with full directory
9272 information). These mappings are used by the compiler to short-circuit the path
9273 search. When @command{gnatmake} is invoked with this switch, it will create
9274 a temporary mapping file, initially populated by the project manager,
9275 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9276 Each invocation of the compiler will add the newly accessed sources to the
9277 mapping file. This will improve the source search during the next invocation
9278 of the compiler.
9279
9280 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9281 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9282 Use a specific mapping file. The file, specified as a path name (absolute or
9283 relative) by this switch, should already exist, otherwise the switch is
9284 ineffective. The specified mapping file will be communicated to the compiler.
9285 This switch is not compatible with a project file
9286 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9287 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9288
9289 @item ^-d^/DISPLAY_PROGRESS^
9290 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9291 Display progress for each source, up to date or not, as a single line
9292
9293 @smallexample
9294 completed x out of y (zz%)
9295 @end smallexample
9296
9297 If the file needs to be compiled this is displayed after the invocation of
9298 the compiler. These lines are displayed even in quiet output mode.
9299
9300 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9301 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9302 Put all object files and ALI file in directory @var{dir}.
9303 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9304 and ALI files go in the current working directory.
9305
9306 This switch cannot be used when using a project file.
9307
9308 @ifclear vms
9309 @item -eL
9310 @cindex @option{-eL} (@command{gnatmake})
9311 Follow all symbolic links when processing project files.
9312 @end ifclear
9313
9314 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9315 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9316 Output the commands for the compiler, the binder and the linker
9317 on ^standard output^SYS$OUTPUT^,
9318 instead of ^standard error^SYS$ERROR^.
9319
9320 @item ^-f^/FORCE_COMPILE^
9321 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9322 Force recompilations. Recompile all sources, even though some object
9323 files may be up to date, but don't recompile predefined or GNAT internal
9324 files or locked files (files with a write-protected ALI file),
9325 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9326
9327 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9328 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9329 When using project files, if some errors or warnings are detected during
9330 parsing and verbose mode is not in effect (no use of switch
9331 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9332 file, rather than its simple file name.
9333
9334 @item ^-g^/DEBUG^
9335 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9336 Enable debugging. This switch is simply passed to the compiler and to the
9337 linker.
9338
9339 @item ^-i^/IN_PLACE^
9340 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9341 In normal mode, @command{gnatmake} compiles all object files and ALI files
9342 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9343 then instead object files and ALI files that already exist are overwritten
9344 in place. This means that once a large project is organized into separate
9345 directories in the desired manner, then @command{gnatmake} will automatically
9346 maintain and update this organization. If no ALI files are found on the
9347 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9348 the new object and ALI files are created in the
9349 directory containing the source being compiled. If another organization
9350 is desired, where objects and sources are kept in different directories,
9351 a useful technique is to create dummy ALI files in the desired directories.
9352 When detecting such a dummy file, @command{gnatmake} will be forced to
9353 recompile the corresponding source file, and it will be put the resulting
9354 object and ALI files in the directory where it found the dummy file.
9355
9356 @item ^-j^/PROCESSES=^@var{n}
9357 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9358 @cindex Parallel make
9359 Use @var{n} processes to carry out the (re)compilations. On a
9360 multiprocessor machine compilations will occur in parallel. In the
9361 event of compilation errors, messages from various compilations might
9362 get interspersed (but @command{gnatmake} will give you the full ordered
9363 list of failing compiles at the end). If this is problematic, rerun
9364 the make process with n set to 1 to get a clean list of messages.
9365
9366 @item ^-k^/CONTINUE_ON_ERROR^
9367 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9368 Keep going. Continue as much as possible after a compilation error. To
9369 ease the programmer's task in case of compilation errors, the list of
9370 sources for which the compile fails is given when @command{gnatmake}
9371 terminates.
9372
9373 If @command{gnatmake} is invoked with several @file{file_names} and with this
9374 switch, if there are compilation errors when building an executable,
9375 @command{gnatmake} will not attempt to build the following executables.
9376
9377 @item ^-l^/ACTIONS=LINK^
9378 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9379 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9380 and linking. Linking will not be performed if combined with
9381 @option{^-c^/ACTIONS=COMPILE^}
9382 but not with @option{^-b^/ACTIONS=BIND^}.
9383 When not combined with @option{^-b^/ACTIONS=BIND^}
9384 all the units in the closure of the main program must have been previously
9385 compiled and must be up to date, and the main program needs to have been bound.
9386 The root unit specified by @var{file_name}
9387 may be given without extension, with the source extension or, if no GNAT
9388 Project File is specified, with the ALI file extension.
9389
9390 @item ^-m^/MINIMAL_RECOMPILATION^
9391 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9392 Specify that the minimum necessary amount of recompilations
9393 be performed. In this mode @command{gnatmake} ignores time
9394 stamp differences when the only
9395 modifications to a source file consist in adding/removing comments,
9396 empty lines, spaces or tabs. This means that if you have changed the
9397 comments in a source file or have simply reformatted it, using this
9398 switch will tell @command{gnatmake} not to recompile files that depend on it
9399 (provided other sources on which these files depend have undergone no
9400 semantic modifications). Note that the debugging information may be
9401 out of date with respect to the sources if the @option{-m} switch causes
9402 a compilation to be switched, so the use of this switch represents a
9403 trade-off between compilation time and accurate debugging information.
9404
9405 @item ^-M^/DEPENDENCIES_LIST^
9406 @cindex Dependencies, producing list
9407 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9408 Check if all objects are up to date. If they are, output the object
9409 dependences to @file{stdout} in a form that can be directly exploited in
9410 a @file{Makefile}. By default, each source file is prefixed with its
9411 (relative or absolute) directory name. This name is whatever you
9412 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9413 and @option{^-I^/SEARCH^} switches. If you use
9414 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9415 @option{^-q^/QUIET^}
9416 (see below), only the source file names,
9417 without relative paths, are output. If you just specify the
9418 @option{^-M^/DEPENDENCIES_LIST^}
9419 switch, dependencies of the GNAT internal system files are omitted. This
9420 is typically what you want. If you also specify
9421 the @option{^-a^/ALL_FILES^} switch,
9422 dependencies of the GNAT internal files are also listed. Note that
9423 dependencies of the objects in external Ada libraries (see switch
9424 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9425 are never reported.
9426
9427 @item ^-n^/DO_OBJECT_CHECK^
9428 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9429 Don't compile, bind, or link. Checks if all objects are up to date.
9430 If they are not, the full name of the first file that needs to be
9431 recompiled is printed.
9432 Repeated use of this option, followed by compiling the indicated source
9433 file, will eventually result in recompiling all required units.
9434
9435 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9436 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9437 Output executable name. The name of the final executable program will be
9438 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9439 name for the executable will be the name of the input file in appropriate form
9440 for an executable file on the host system.
9441
9442 This switch cannot be used when invoking @command{gnatmake} with several
9443 @file{file_names}.
9444
9445 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9446 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9447 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9448 automatically missing object directories, library directories and exec
9449 directories.
9450
9451 @item ^-P^/PROJECT_FILE=^@var{project}
9452 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9453 Use project file @var{project}. Only one such switch can be used.
9454 @xref{gnatmake and Project Files}.
9455
9456 @item ^-q^/QUIET^
9457 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9458 Quiet. When this flag is not set, the commands carried out by
9459 @command{gnatmake} are displayed.
9460
9461 @item ^-s^/SWITCH_CHECK/^
9462 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9463 Recompile if compiler switches have changed since last compilation.
9464 All compiler switches but -I and -o are taken into account in the
9465 following way:
9466 orders between different ``first letter'' switches are ignored, but
9467 orders between same switches are taken into account. For example,
9468 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9469 is equivalent to @option{-O -g}.
9470
9471 This switch is recommended when Integrated Preprocessing is used.
9472
9473 @item ^-u^/UNIQUE^
9474 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9475 Unique. Recompile at most the main files. It implies -c. Combined with
9476 -f, it is equivalent to calling the compiler directly. Note that using
9477 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9478 (@pxref{Project Files and Main Subprograms}).
9479
9480 @item ^-U^/ALL_PROJECTS^
9481 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9482 When used without a project file or with one or several mains on the command
9483 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9484 on the command line, all sources of all project files are checked and compiled
9485 if not up to date, and libraries are rebuilt, if necessary.
9486
9487 @item ^-v^/REASONS^
9488 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9489 Verbose. Display the reason for all recompilations @command{gnatmake}
9490 decides are necessary, with the highest verbosity level.
9491
9492 @item ^-vl^/LOW_VERBOSITY^
9493 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9494 Verbosity level Low. Display fewer lines than in verbosity Medium.
9495
9496 @item ^-vm^/MEDIUM_VERBOSITY^
9497 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9498 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9499
9500 @item ^-vh^/HIGH_VERBOSITY^
9501 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9502 Verbosity level High. Equivalent to ^-v^/REASONS^.
9503
9504 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9505 Indicate the verbosity of the parsing of GNAT project files.
9506 @xref{Switches Related to Project Files}.
9507
9508 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9509 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9510 Indicate that sources that are not part of any Project File may be compiled.
9511 Normally, when using Project Files, only sources that are part of a Project
9512 File may be compile. When this switch is used, a source outside of all Project
9513 Files may be compiled. The ALI file and the object file will be put in the
9514 object directory of the main Project. The compilation switches used will only
9515 be those specified on the command line. Even when
9516 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9517 command line need to be sources of a project file.
9518
9519 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9520 Indicate that external variable @var{name} has the value @var{value}.
9521 The Project Manager will use this value for occurrences of
9522 @code{external(name)} when parsing the project file.
9523 @xref{Switches Related to Project Files}.
9524
9525 @item ^-z^/NOMAIN^
9526 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9527 No main subprogram. Bind and link the program even if the unit name
9528 given on the command line is a package name. The resulting executable
9529 will execute the elaboration routines of the package and its closure,
9530 then the finalization routines.
9531
9532 @end table
9533
9534 @table @asis
9535 @item @command{gcc} @asis{switches}
9536 @ifclear vms
9537 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9538 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9539 @end ifclear
9540 @ifset vms
9541 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9542 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9543 automatically treated as a compiler switch, and passed on to all
9544 compilations that are carried out.
9545 @end ifset
9546 @end table
9547
9548 @noindent
9549 Source and library search path switches:
9550
9551 @table @option
9552 @c !sort!
9553 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9554 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9555 When looking for source files also look in directory @var{dir}.
9556 The order in which source files search is undertaken is
9557 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9558
9559 @item ^-aL^/SKIP_MISSING=^@var{dir}
9560 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9561 Consider @var{dir} as being an externally provided Ada library.
9562 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9563 files have been located in directory @var{dir}. This allows you to have
9564 missing bodies for the units in @var{dir} and to ignore out of date bodies
9565 for the same units. You still need to specify
9566 the location of the specs for these units by using the switches
9567 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9568 or @option{^-I^/SEARCH=^@var{dir}}.
9569 Note: this switch is provided for compatibility with previous versions
9570 of @command{gnatmake}. The easier method of causing standard libraries
9571 to be excluded from consideration is to write-protect the corresponding
9572 ALI files.
9573
9574 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9575 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9576 When searching for library and object files, look in directory
9577 @var{dir}. The order in which library files are searched is described in
9578 @ref{Search Paths for gnatbind}.
9579
9580 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9581 @cindex Search paths, for @command{gnatmake}
9582 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9583 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9584 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9585
9586 @item ^-I^/SEARCH=^@var{dir}
9587 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9588 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9589 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9590
9591 @item ^-I-^/NOCURRENT_DIRECTORY^
9592 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9593 @cindex Source files, suppressing search
9594 Do not look for source files in the directory containing the source
9595 file named in the command line.
9596 Do not look for ALI or object files in the directory
9597 where @command{gnatmake} was invoked.
9598
9599 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9600 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9601 @cindex Linker libraries
9602 Add directory @var{dir} to the list of directories in which the linker
9603 will search for libraries. This is equivalent to
9604 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9605 @ifclear vms
9606 Furthermore, under Windows, the sources pointed to by the libraries path
9607 set in the registry are not searched for.
9608 @end ifclear
9609
9610 @item -nostdinc
9611 @cindex @option{-nostdinc} (@command{gnatmake})
9612 Do not look for source files in the system default directory.
9613
9614 @item -nostdlib
9615 @cindex @option{-nostdlib} (@command{gnatmake})
9616 Do not look for library files in the system default directory.
9617
9618 @item --RTS=@var{rts-path}
9619 @cindex @option{--RTS} (@command{gnatmake})
9620 Specifies the default location of the runtime library. GNAT looks for the
9621 runtime
9622 in the following directories, and stops as soon as a valid runtime is found
9623 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9624 @file{ada_object_path} present):
9625
9626 @itemize @bullet
9627 @item <current directory>/$rts_path
9628
9629 @item <default-search-dir>/$rts_path
9630
9631 @item <default-search-dir>/rts-$rts_path
9632 @end itemize
9633
9634 @noindent
9635 The selected path is handled like a normal RTS path.
9636
9637 @end table
9638
9639 @node Mode Switches for gnatmake
9640 @section Mode Switches for @command{gnatmake}
9641
9642 @noindent
9643 The mode switches (referred to as @code{mode_switches}) allow the
9644 inclusion of switches that are to be passed to the compiler itself, the
9645 binder or the linker. The effect of a mode switch is to cause all
9646 subsequent switches up to the end of the switch list, or up to the next
9647 mode switch, to be interpreted as switches to be passed on to the
9648 designated component of GNAT.
9649
9650 @table @option
9651 @c !sort!
9652 @item -cargs @var{switches}
9653 @cindex @option{-cargs} (@command{gnatmake})
9654 Compiler switches. Here @var{switches} is a list of switches
9655 that are valid switches for @command{gcc}. They will be passed on to
9656 all compile steps performed by @command{gnatmake}.
9657
9658 @item -bargs @var{switches}
9659 @cindex @option{-bargs} (@command{gnatmake})
9660 Binder switches. Here @var{switches} is a list of switches
9661 that are valid switches for @code{gnatbind}. They will be passed on to
9662 all bind steps performed by @command{gnatmake}.
9663
9664 @item -largs @var{switches}
9665 @cindex @option{-largs} (@command{gnatmake})
9666 Linker switches. Here @var{switches} is a list of switches
9667 that are valid switches for @command{gnatlink}. They will be passed on to
9668 all link steps performed by @command{gnatmake}.
9669
9670 @item -margs @var{switches}
9671 @cindex @option{-margs} (@command{gnatmake})
9672 Make switches. The switches are directly interpreted by @command{gnatmake},
9673 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9674 or @option{-largs}.
9675 @end table
9676
9677 @node Notes on the Command Line
9678 @section Notes on the Command Line
9679
9680 @noindent
9681 This section contains some additional useful notes on the operation
9682 of the @command{gnatmake} command.
9683
9684 @itemize @bullet
9685 @item
9686 @cindex Recompilation, by @command{gnatmake}
9687 If @command{gnatmake} finds no ALI files, it recompiles the main program
9688 and all other units required by the main program.
9689 This means that @command{gnatmake}
9690 can be used for the initial compile, as well as during subsequent steps of
9691 the development cycle.
9692
9693 @item
9694 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9695 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9696 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9697 warning.
9698
9699 @item
9700 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9701 is used to specify both source and
9702 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9703 instead if you just want to specify
9704 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9705 if you want to specify library paths
9706 only.
9707
9708 @item
9709 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9710 This may conveniently be used to exclude standard libraries from
9711 consideration and in particular it means that the use of the
9712 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9713 unless @option{^-a^/ALL_FILES^} is also specified.
9714
9715 @item
9716 @command{gnatmake} has been designed to make the use of Ada libraries
9717 particularly convenient. Assume you have an Ada library organized
9718 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9719 of your Ada compilation units,
9720 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9721 specs of these units, but no bodies. Then to compile a unit
9722 stored in @code{main.adb}, which uses this Ada library you would just type
9723
9724 @smallexample
9725 @ifclear vms
9726 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9727 @end ifclear
9728 @ifset vms
9729 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9730            /SKIP_MISSING=@i{[OBJ_DIR]} main
9731 @end ifset
9732 @end smallexample
9733
9734 @item
9735 Using @command{gnatmake} along with the
9736 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9737 switch provides a mechanism for avoiding unnecessary recompilations. Using
9738 this switch,
9739 you can update the comments/format of your
9740 source files without having to recompile everything. Note, however, that
9741 adding or deleting lines in a source files may render its debugging
9742 info obsolete. If the file in question is a spec, the impact is rather
9743 limited, as that debugging info will only be useful during the
9744 elaboration phase of your program. For bodies the impact can be more
9745 significant. In all events, your debugger will warn you if a source file
9746 is more recent than the corresponding object, and alert you to the fact
9747 that the debugging information may be out of date.
9748 @end itemize
9749
9750 @node How gnatmake Works
9751 @section How @command{gnatmake} Works
9752
9753 @noindent
9754 Generally @command{gnatmake} automatically performs all necessary
9755 recompilations and you don't need to worry about how it works. However,
9756 it may be useful to have some basic understanding of the @command{gnatmake}
9757 approach and in particular to understand how it uses the results of
9758 previous compilations without incorrectly depending on them.
9759
9760 First a definition: an object file is considered @dfn{up to date} if the
9761 corresponding ALI file exists and if all the source files listed in the
9762 dependency section of this ALI file have time stamps matching those in
9763 the ALI file. This means that neither the source file itself nor any
9764 files that it depends on have been modified, and hence there is no need
9765 to recompile this file.
9766
9767 @command{gnatmake} works by first checking if the specified main unit is up
9768 to date. If so, no compilations are required for the main unit. If not,
9769 @command{gnatmake} compiles the main program to build a new ALI file that
9770 reflects the latest sources. Then the ALI file of the main unit is
9771 examined to find all the source files on which the main program depends,
9772 and @command{gnatmake} recursively applies the above procedure on all these
9773 files.
9774
9775 This process ensures that @command{gnatmake} only trusts the dependencies
9776 in an existing ALI file if they are known to be correct. Otherwise it
9777 always recompiles to determine a new, guaranteed accurate set of
9778 dependencies. As a result the program is compiled ``upside down'' from what may
9779 be more familiar as the required order of compilation in some other Ada
9780 systems. In particular, clients are compiled before the units on which
9781 they depend. The ability of GNAT to compile in any order is critical in
9782 allowing an order of compilation to be chosen that guarantees that
9783 @command{gnatmake} will recompute a correct set of new dependencies if
9784 necessary.
9785
9786 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9787 imported by several of the executables, it will be recompiled at most once.
9788
9789 Note: when using non-standard naming conventions
9790 (@pxref{Using Other File Names}), changing through a configuration pragmas
9791 file the version of a source and invoking @command{gnatmake} to recompile may
9792 have no effect, if the previous version of the source is still accessible
9793 by @command{gnatmake}. It may be necessary to use the switch
9794 ^-f^/FORCE_COMPILE^.
9795
9796 @node Examples of gnatmake Usage
9797 @section Examples of @command{gnatmake} Usage
9798
9799 @table @code
9800 @item gnatmake hello.adb
9801 Compile all files necessary to bind and link the main program
9802 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9803 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9804
9805 @item gnatmake main1 main2 main3
9806 Compile all files necessary to bind and link the main programs
9807 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9808 (containing unit @code{Main2}) and @file{main3.adb}
9809 (containing unit @code{Main3}) and bind and link the resulting object files
9810 to generate three executable files @file{^main1^MAIN1.EXE^},
9811 @file{^main2^MAIN2.EXE^}
9812 and @file{^main3^MAIN3.EXE^}.
9813
9814 @ifclear vms
9815 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9816 @end ifclear
9817
9818 @ifset vms
9819 @item gnatmake Main_Unit /QUIET
9820 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9821 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9822 @end ifset
9823 Compile all files necessary to bind and link the main program unit
9824 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9825 be done with optimization level 2 and the order of elaboration will be
9826 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9827 displaying commands it is executing.
9828 @end table
9829
9830 @c *************************
9831 @node Improving Performance
9832 @chapter Improving Performance
9833 @cindex Improving performance
9834
9835 @noindent
9836 This chapter presents several topics related to program performance.
9837 It first describes some of the tradeoffs that need to be considered
9838 and some of the techniques for making your program run faster.
9839 It then documents the @command{gnatelim} tool and unused subprogram/data
9840 elimination feature, which can reduce the size of program executables.
9841
9842 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9843 driver (see @ref{The GNAT Driver and Project Files}).
9844
9845 @ifnottex
9846 @menu
9847 * Performance Considerations::
9848 * Text_IO Suggestions::
9849 * Reducing Size of Ada Executables with gnatelim::
9850 * Reducing Size of Executables with unused subprogram/data elimination::
9851 @end menu
9852 @end ifnottex
9853
9854 @c *****************************
9855 @node Performance Considerations
9856 @section Performance Considerations
9857
9858 @noindent
9859 The GNAT system provides a number of options that allow a trade-off
9860 between
9861
9862 @itemize @bullet
9863 @item
9864 performance of the generated code
9865
9866 @item
9867 speed of compilation
9868
9869 @item
9870 minimization of dependences and recompilation
9871
9872 @item
9873 the degree of run-time checking.
9874 @end itemize
9875
9876 @noindent
9877 The defaults (if no options are selected) aim at improving the speed
9878 of compilation and minimizing dependences, at the expense of performance
9879 of the generated code:
9880
9881 @itemize @bullet
9882 @item
9883 no optimization
9884
9885 @item
9886 no inlining of subprogram calls
9887
9888 @item
9889 all run-time checks enabled except overflow and elaboration checks
9890 @end itemize
9891
9892 @noindent
9893 These options are suitable for most program development purposes. This
9894 chapter describes how you can modify these choices, and also provides
9895 some guidelines on debugging optimized code.
9896
9897 @menu
9898 * Controlling Run-Time Checks::
9899 * Use of Restrictions::
9900 * Optimization Levels::
9901 * Debugging Optimized Code::
9902 * Inlining of Subprograms::
9903 * Other Optimization Switches::
9904 * Optimization and Strict Aliasing::
9905
9906 @ifset vms
9907 * Coverage Analysis::
9908 @end ifset
9909 @end menu
9910
9911 @node Controlling Run-Time Checks
9912 @subsection Controlling Run-Time Checks
9913
9914 @noindent
9915 By default, GNAT generates all run-time checks, except integer overflow
9916 checks, stack overflow checks, and checks for access before elaboration on
9917 subprogram calls. The latter are not required in default mode, because all
9918 necessary checking is done at compile time.
9919 @cindex @option{-gnatp} (@command{gcc})
9920 @cindex @option{-gnato} (@command{gcc})
9921 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9922 be modified. @xref{Run-Time Checks}.
9923
9924 Our experience is that the default is suitable for most development
9925 purposes.
9926
9927 We treat integer overflow specially because these
9928 are quite expensive and in our experience are not as important as other
9929 run-time checks in the development process. Note that division by zero
9930 is not considered an overflow check, and divide by zero checks are
9931 generated where required by default.
9932
9933 Elaboration checks are off by default, and also not needed by default, since
9934 GNAT uses a static elaboration analysis approach that avoids the need for
9935 run-time checking. This manual contains a full chapter discussing the issue
9936 of elaboration checks, and if the default is not satisfactory for your use,
9937 you should read this chapter.
9938
9939 For validity checks, the minimal checks required by the Ada Reference
9940 Manual (for case statements and assignments to array elements) are on
9941 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9942 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9943 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9944 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9945 are also suppressed entirely if @option{-gnatp} is used.
9946
9947 @cindex Overflow checks
9948 @cindex Checks, overflow
9949 @findex Suppress
9950 @findex Unsuppress
9951 @cindex pragma Suppress
9952 @cindex pragma Unsuppress
9953 Note that the setting of the switches controls the default setting of
9954 the checks. They may be modified using either @code{pragma Suppress} (to
9955 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9956 checks) in the program source.
9957
9958 @node Use of Restrictions
9959 @subsection Use of Restrictions
9960
9961 @noindent
9962 The use of pragma Restrictions allows you to control which features are
9963 permitted in your program. Apart from the obvious point that if you avoid
9964 relatively expensive features like finalization (enforceable by the use
9965 of pragma Restrictions (No_Finalization), the use of this pragma does not
9966 affect the generated code in most cases.
9967
9968 One notable exception to this rule is that the possibility of task abort
9969 results in some distributed overhead, particularly if finalization or
9970 exception handlers are used. The reason is that certain sections of code
9971 have to be marked as non-abortable.
9972
9973 If you use neither the @code{abort} statement, nor asynchronous transfer
9974 of control (@code{select @dots{} then abort}), then this distributed overhead
9975 is removed, which may have a general positive effect in improving
9976 overall performance.  Especially code involving frequent use of tasking
9977 constructs and controlled types will show much improved performance.
9978 The relevant restrictions pragmas are
9979
9980 @smallexample @c ada
9981    pragma Restrictions (No_Abort_Statements);
9982    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9983 @end smallexample
9984
9985 @noindent
9986 It is recommended that these restriction pragmas be used if possible. Note
9987 that this also means that you can write code without worrying about the
9988 possibility of an immediate abort at any point.
9989
9990 @node Optimization Levels
9991 @subsection Optimization Levels
9992 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9993
9994 @noindent
9995 Without any optimization ^option,^qualifier,^
9996 the compiler's goal is to reduce the cost of
9997 compilation and to make debugging produce the expected results.
9998 Statements are independent: if you stop the program with a breakpoint between
9999 statements, you can then assign a new value to any variable or change
10000 the program counter to any other statement in the subprogram and get exactly
10001 the results you would expect from the source code.
10002
10003 Turning on optimization makes the compiler attempt to improve the
10004 performance and/or code size at the expense of compilation time and
10005 possibly the ability to debug the program.
10006
10007 If you use multiple
10008 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10009 the last such option is the one that is effective.
10010
10011 @noindent
10012 The default is optimization off. This results in the fastest compile
10013 times, but GNAT makes absolutely no attempt to optimize, and the
10014 generated programs are considerably larger and slower than when
10015 optimization is enabled. You can use the
10016 @ifclear vms
10017 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10018 @option{-O2}, @option{-O3}, and @option{-Os})
10019 @end ifclear
10020 @ifset vms
10021 @code{OPTIMIZE} qualifier
10022 @end ifset
10023 to @command{gcc} to control the optimization level:
10024
10025 @table @option
10026 @item ^-O0^/OPTIMIZE=NONE^
10027 No optimization (the default);
10028 generates unoptimized code but has
10029 the fastest compilation time.
10030
10031 Note that many other compilers do fairly extensive optimization
10032 even if ``no optimization'' is specified. With gcc, it is
10033 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10034 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10035 really does mean no optimization at all. This difference between
10036 gcc and other compilers should be kept in mind when doing
10037 performance comparisons.
10038
10039 @item ^-O1^/OPTIMIZE=SOME^
10040 Moderate optimization;
10041 optimizes reasonably well but does not
10042 degrade compilation time significantly.
10043
10044 @item ^-O2^/OPTIMIZE=ALL^
10045 @ifset vms
10046 @itemx /OPTIMIZE=DEVELOPMENT
10047 @end ifset
10048 Full optimization;
10049 generates highly optimized code and has
10050 the slowest compilation time.
10051
10052 @item ^-O3^/OPTIMIZE=INLINING^
10053 Full optimization as in @option{-O2},
10054 and also attempts automatic inlining of small
10055 subprograms within a unit (@pxref{Inlining of Subprograms}).
10056
10057 @item ^-Os^/OPTIMIZE=SPACE^
10058 Optimize space usage of resulting program.
10059 @end table
10060
10061 @noindent
10062 Higher optimization levels perform more global transformations on the
10063 program and apply more expensive analysis algorithms in order to generate
10064 faster and more compact code. The price in compilation time, and the
10065 resulting improvement in execution time,
10066 both depend on the particular application and the hardware environment.
10067 You should experiment to find the best level for your application.
10068
10069 Since the precise set of optimizations done at each level will vary from
10070 release to release (and sometime from target to target), it is best to think
10071 of the optimization settings in general terms.
10072 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10073 the GNU Compiler Collection (GCC)}, for details about
10074 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10075 individually enable or disable specific optimizations.
10076
10077 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10078 been tested extensively at all optimization levels. There are some bugs
10079 which appear only with optimization turned on, but there have also been
10080 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10081 level of optimization does not improve the reliability of the code
10082 generator, which in practice is highly reliable at all optimization
10083 levels.
10084
10085 Note regarding the use of @option{-O3}: The use of this optimization level
10086 is generally discouraged with GNAT, since it often results in larger
10087 executables which run more slowly. See further discussion of this point
10088 in @ref{Inlining of Subprograms}.
10089
10090 @node Debugging Optimized Code
10091 @subsection Debugging Optimized Code
10092 @cindex Debugging optimized code
10093 @cindex Optimization and debugging
10094
10095 @noindent
10096 Although it is possible to do a reasonable amount of debugging at
10097 @ifclear vms
10098 nonzero optimization levels,
10099 the higher the level the more likely that
10100 @end ifclear
10101 @ifset vms
10102 @option{/OPTIMIZE} settings other than @code{NONE},
10103 such settings will make it more likely that
10104 @end ifset
10105 source-level constructs will have been eliminated by optimization.
10106 For example, if a loop is strength-reduced, the loop
10107 control variable may be completely eliminated and thus cannot be
10108 displayed in the debugger.
10109 This can only happen at @option{-O2} or @option{-O3}.
10110 Explicit temporary variables that you code might be eliminated at
10111 ^level^setting^ @option{-O1} or higher.
10112
10113 The use of the @option{^-g^/DEBUG^} switch,
10114 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10115 which is needed for source-level debugging,
10116 affects the size of the program executable on disk,
10117 and indeed the debugging information can be quite large.
10118 However, it has no effect on the generated code (and thus does not
10119 degrade performance)
10120
10121 Since the compiler generates debugging tables for a compilation unit before
10122 it performs optimizations, the optimizing transformations may invalidate some
10123 of the debugging data.  You therefore need to anticipate certain
10124 anomalous situations that may arise while debugging optimized code.
10125 These are the most common cases:
10126
10127 @enumerate
10128 @item
10129 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10130 commands show
10131 the PC bouncing back and forth in the code.  This may result from any of
10132 the following optimizations:
10133
10134 @itemize @bullet
10135 @item
10136 @i{Common subexpression elimination:} using a single instance of code for a
10137 quantity that the source computes several times.  As a result you
10138 may not be able to stop on what looks like a statement.
10139
10140 @item
10141 @i{Invariant code motion:} moving an expression that does not change within a
10142 loop, to the beginning of the loop.
10143
10144 @item
10145 @i{Instruction scheduling:} moving instructions so as to
10146 overlap loads and stores (typically) with other code, or in
10147 general to move computations of values closer to their uses. Often
10148 this causes you to pass an assignment statement without the assignment
10149 happening and then later bounce back to the statement when the
10150 value is actually needed.  Placing a breakpoint on a line of code
10151 and then stepping over it may, therefore, not always cause all the
10152 expected side-effects.
10153 @end itemize
10154
10155 @item
10156 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10157 two identical pieces of code are merged and the program counter suddenly
10158 jumps to a statement that is not supposed to be executed, simply because
10159 it (and the code following) translates to the same thing as the code
10160 that @emph{was} supposed to be executed.  This effect is typically seen in
10161 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10162 a @code{break} in a C @code{^switch^switch^} statement.
10163
10164 @item
10165 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10166 There are various reasons for this effect:
10167
10168 @itemize @bullet
10169 @item
10170 In a subprogram prologue, a parameter may not yet have been moved to its
10171 ``home''.
10172
10173 @item
10174 A variable may be dead, and its register re-used.  This is
10175 probably the most common cause.
10176
10177 @item
10178 As mentioned above, the assignment of a value to a variable may
10179 have been moved.
10180
10181 @item
10182 A variable may be eliminated entirely by value propagation or
10183 other means.  In this case, GCC may incorrectly generate debugging
10184 information for the variable
10185 @end itemize
10186
10187 @noindent
10188 In general, when an unexpected value appears for a local variable or parameter
10189 you should first ascertain if that value was actually computed by
10190 your program, as opposed to being incorrectly reported by the debugger.
10191 Record fields or
10192 array elements in an object designated by an access value
10193 are generally less of a problem, once you have ascertained that the access
10194 value is sensible.
10195 Typically, this means checking variables in the preceding code and in the
10196 calling subprogram to verify that the value observed is explainable from other
10197 values (one must apply the procedure recursively to those
10198 other values); or re-running the code and stopping a little earlier
10199 (perhaps before the call) and stepping to better see how the variable obtained
10200 the value in question; or continuing to step @emph{from} the point of the
10201 strange value to see if code motion had simply moved the variable's
10202 assignments later.
10203 @end enumerate
10204
10205 @noindent
10206 In light of such anomalies, a recommended technique is to use @option{-O0}
10207 early in the software development cycle, when extensive debugging capabilities
10208 are most needed, and then move to @option{-O1} and later @option{-O2} as
10209 the debugger becomes less critical.
10210 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10211 a release management issue.
10212 @ifclear vms
10213 Note that if you use @option{-g} you can then use the @command{strip} program
10214 on the resulting executable,
10215 which removes both debugging information and global symbols.
10216 @end ifclear
10217
10218 @node Inlining of Subprograms
10219 @subsection Inlining of Subprograms
10220
10221 @noindent
10222 A call to a subprogram in the current unit is inlined if all the
10223 following conditions are met:
10224
10225 @itemize @bullet
10226 @item
10227 The optimization level is at least @option{-O1}.
10228
10229 @item
10230 The called subprogram is suitable for inlining: It must be small enough
10231 and not contain something that @command{gcc} cannot support in inlined
10232 subprograms.
10233
10234 @item
10235 @cindex pragma Inline
10236 @findex Inline
10237 Either @code{pragma Inline} applies to the subprogram, or it is local
10238 to the unit and called once from within it, or it is small and automatic
10239 inlining (optimization level @option{-O3}) is specified.
10240 @end itemize
10241
10242 @noindent
10243 Calls to subprograms in @code{with}'ed units are normally not inlined.
10244 To achieve actual inlining (that is, replacement of the call by the code
10245 in the body of the subprogram), the following conditions must all be true.
10246
10247 @itemize @bullet
10248 @item
10249 The optimization level is at least @option{-O1}.
10250
10251 @item
10252 The called subprogram is suitable for inlining: It must be small enough
10253 and not contain something that @command{gcc} cannot support in inlined
10254 subprograms.
10255
10256 @item
10257 The call appears in a body (not in a package spec).
10258
10259 @item
10260 There is a @code{pragma Inline} for the subprogram.
10261
10262 @item
10263 @cindex @option{-gnatn} (@command{gcc})
10264 The @option{^-gnatn^/INLINE^} switch
10265 is used in the @command{gcc} command line
10266 @end itemize
10267
10268 Even if all these conditions are met, it may not be possible for
10269 the compiler to inline the call, due to the length of the body,
10270 or features in the body that make it impossible for the compiler
10271 to do the inlining.
10272
10273 Note that specifying the @option{-gnatn} switch causes additional
10274 compilation dependencies. Consider the following:
10275
10276 @smallexample @c ada
10277 @cartouche
10278 package R is
10279    procedure Q;
10280    pragma Inline (Q);
10281 end R;
10282 package body R is
10283    @dots{}
10284 end R;
10285
10286 with R;
10287 procedure Main is
10288 begin
10289    @dots{}
10290    R.Q;
10291 end Main;
10292 @end cartouche
10293 @end smallexample
10294
10295 @noindent
10296 With the default behavior (no @option{-gnatn} switch specified), the
10297 compilation of the @code{Main} procedure depends only on its own source,
10298 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10299 means that editing the body of @code{R} does not require recompiling
10300 @code{Main}.
10301
10302 On the other hand, the call @code{R.Q} is not inlined under these
10303 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10304 is compiled, the call will be inlined if the body of @code{Q} is small
10305 enough, but now @code{Main} depends on the body of @code{R} in
10306 @file{r.adb} as well as on the spec. This means that if this body is edited,
10307 the main program must be recompiled. Note that this extra dependency
10308 occurs whether or not the call is in fact inlined by @command{gcc}.
10309
10310 The use of front end inlining with @option{-gnatN} generates similar
10311 additional dependencies.
10312
10313 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10314 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10315 can be used to prevent
10316 all inlining. This switch overrides all other conditions and ensures
10317 that no inlining occurs. The extra dependences resulting from
10318 @option{-gnatn} will still be active, even if
10319 this switch is used to suppress the resulting inlining actions.
10320
10321 @cindex @option{-fno-inline-functions} (@command{gcc})
10322 Note: The @option{-fno-inline-functions} switch can be used to prevent
10323 automatic inlining of small subprograms if @option{-O3} is used.
10324
10325 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10326 Note: The @option{-fno-inline-functions-called-once} switch
10327 can be used to prevent inlining of subprograms local to the unit
10328 and called once from within it if @option{-O1} is used.
10329
10330 Note regarding the use of @option{-O3}: There is no difference in inlining
10331 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10332 pragma @code{Inline} assuming the use of @option{-gnatn}
10333 or @option{-gnatN} (the switches that activate inlining). If you have used
10334 pragma @code{Inline} in appropriate cases, then it is usually much better
10335 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10336 in this case only has the effect of inlining subprograms you did not
10337 think should be inlined. We often find that the use of @option{-O3} slows
10338 down code by performing excessive inlining, leading to increased instruction
10339 cache pressure from the increased code size. So the bottom line here is
10340 that you should not automatically assume that @option{-O3} is better than
10341 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10342 it actually improves performance.
10343
10344 @node Other Optimization Switches
10345 @subsection Other Optimization Switches
10346 @cindex Optimization Switches
10347
10348 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10349 @command{gcc} optimization switches are potentially usable. These switches
10350 have not been extensively tested with GNAT but can generally be expected
10351 to work. Examples of switches in this category are
10352 @option{-funroll-loops} and
10353 the various target-specific @option{-m} options (in particular, it has been
10354 observed that @option{-march=pentium4} can significantly improve performance
10355 on appropriate machines). For full details of these switches, see
10356 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10357 the GNU Compiler Collection (GCC)}.
10358
10359 @node Optimization and Strict Aliasing
10360 @subsection Optimization and Strict Aliasing
10361 @cindex Aliasing
10362 @cindex Strict Aliasing
10363 @cindex No_Strict_Aliasing
10364
10365 @noindent
10366 The strong typing capabilities of Ada allow an optimizer to generate
10367 efficient code in situations where other languages would be forced to
10368 make worst case assumptions preventing such optimizations. Consider
10369 the following example:
10370
10371 @smallexample @c ada
10372 @cartouche
10373 procedure R is
10374    type Int1 is new Integer;
10375    type Int2 is new Integer;
10376    type Int1A is access Int1;
10377    type Int2A is access Int2;
10378    Int1V : Int1A;
10379    Int2V : Int2A;
10380    @dots{}
10381
10382 begin
10383    @dots{}
10384    for J in Data'Range loop
10385       if Data (J) = Int1V.all then
10386          Int2V.all := Int2V.all + 1;
10387       end if;
10388    end loop;
10389    @dots{}
10390 end R;
10391 @end cartouche
10392 @end smallexample
10393
10394 @noindent
10395 In this example, since the variable @code{Int1V} can only access objects
10396 of type @code{Int1}, and @code{Int2V} can only access objects of type
10397 @code{Int2}, there is no possibility that the assignment to
10398 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10399 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10400 for all iterations of the loop and avoid the extra memory reference
10401 required to dereference it each time through the loop.
10402
10403 This kind of optimization, called strict aliasing analysis, is
10404 triggered by specifying an optimization level of @option{-O2} or
10405 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10406 when access values are involved.
10407
10408 However, although this optimization is always correct in terms of
10409 the formal semantics of the Ada Reference Manual, difficulties can
10410 arise if features like @code{Unchecked_Conversion} are used to break
10411 the typing system. Consider the following complete program example:
10412
10413 @smallexample @c ada
10414 @cartouche
10415 package p1 is
10416    type int1 is new integer;
10417    type int2 is new integer;
10418    type a1 is access int1;
10419    type a2 is access int2;
10420 end p1;
10421
10422 with p1; use p1;
10423 package p2 is
10424    function to_a2 (Input : a1) return a2;
10425 end p2;
10426
10427 with Unchecked_Conversion;
10428 package body p2 is
10429    function to_a2 (Input : a1) return a2 is
10430       function to_a2u is
10431         new Unchecked_Conversion (a1, a2);
10432    begin
10433       return to_a2u (Input);
10434    end to_a2;
10435 end p2;
10436
10437 with p2; use p2;
10438 with p1; use p1;
10439 with Text_IO; use Text_IO;
10440 procedure m is
10441    v1 : a1 := new int1;
10442    v2 : a2 := to_a2 (v1);
10443 begin
10444    v1.all := 1;
10445    v2.all := 0;
10446    put_line (int1'image (v1.all));
10447 end;
10448 @end cartouche
10449 @end smallexample
10450
10451 @noindent
10452 This program prints out 0 in @option{-O0} or @option{-O1}
10453 mode, but it prints out 1 in @option{-O2} mode. That's
10454 because in strict aliasing mode, the compiler can and
10455 does assume that the assignment to @code{v2.all} could not
10456 affect the value of @code{v1.all}, since different types
10457 are involved.
10458
10459 This behavior is not a case of non-conformance with the standard, since
10460 the Ada RM specifies that an unchecked conversion where the resulting
10461 bit pattern is not a correct value of the target type can result in an
10462 abnormal value and attempting to reference an abnormal value makes the
10463 execution of a program erroneous.  That's the case here since the result
10464 does not point to an object of type @code{int2}.  This means that the
10465 effect is entirely unpredictable.
10466
10467 However, although that explanation may satisfy a language
10468 lawyer, in practice an applications programmer expects an
10469 unchecked conversion involving pointers to create true
10470 aliases and the behavior of printing 1 seems plain wrong.
10471 In this case, the strict aliasing optimization is unwelcome.
10472
10473 Indeed the compiler recognizes this possibility, and the
10474 unchecked conversion generates a warning:
10475
10476 @smallexample
10477 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10478 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10479 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10480 @end smallexample
10481
10482 @noindent
10483 Unfortunately the problem is recognized when compiling the body of
10484 package @code{p2}, but the actual "bad" code is generated while
10485 compiling the body of @code{m} and this latter compilation does not see
10486 the suspicious @code{Unchecked_Conversion}.
10487
10488 As implied by the warning message, there are approaches you can use to
10489 avoid the unwanted strict aliasing optimization in a case like this.
10490
10491 One possibility is to simply avoid the use of @option{-O2}, but
10492 that is a bit drastic, since it throws away a number of useful
10493 optimizations that do not involve strict aliasing assumptions.
10494
10495 A less drastic approach is to compile the program using the
10496 option @option{-fno-strict-aliasing}. Actually it is only the
10497 unit containing the dereferencing of the suspicious pointer
10498 that needs to be compiled. So in this case, if we compile
10499 unit @code{m} with this switch, then we get the expected
10500 value of zero printed. Analyzing which units might need
10501 the switch can be painful, so a more reasonable approach
10502 is to compile the entire program with options @option{-O2}
10503 and @option{-fno-strict-aliasing}. If the performance is
10504 satisfactory with this combination of options, then the
10505 advantage is that the entire issue of possible "wrong"
10506 optimization due to strict aliasing is avoided.
10507
10508 To avoid the use of compiler switches, the configuration
10509 pragma @code{No_Strict_Aliasing} with no parameters may be
10510 used to specify that for all access types, the strict
10511 aliasing optimization should be suppressed.
10512
10513 However, these approaches are still overkill, in that they causes
10514 all manipulations of all access values to be deoptimized. A more
10515 refined approach is to concentrate attention on the specific
10516 access type identified as problematic.
10517
10518 First, if a careful analysis of uses of the pointer shows
10519 that there are no possible problematic references, then
10520 the warning can be suppressed by bracketing the
10521 instantiation of @code{Unchecked_Conversion} to turn
10522 the warning off:
10523
10524 @smallexample @c ada
10525    pragma Warnings (Off);
10526    function to_a2u is
10527      new Unchecked_Conversion (a1, a2);
10528    pragma Warnings (On);
10529 @end smallexample
10530
10531 @noindent
10532 Of course that approach is not appropriate for this particular
10533 example, since indeed there is a problematic reference. In this
10534 case we can take one of two other approaches.
10535
10536 The first possibility is to move the instantiation of unchecked
10537 conversion to the unit in which the type is declared. In
10538 this example, we would move the instantiation of
10539 @code{Unchecked_Conversion} from the body of package
10540 @code{p2} to the spec of package @code{p1}. Now the
10541 warning disappears. That's because any use of the
10542 access type knows there is a suspicious unchecked
10543 conversion, and the strict aliasing optimization
10544 is automatically suppressed for the type.
10545
10546 If it is not practical to move the unchecked conversion to the same unit
10547 in which the destination access type is declared (perhaps because the
10548 source type is not visible in that unit), you may use pragma
10549 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10550 same declarative sequence as the declaration of the access type:
10551
10552 @smallexample @c ada
10553    type a2 is access int2;
10554    pragma No_Strict_Aliasing (a2);
10555 @end smallexample
10556
10557 @noindent
10558 Here again, the compiler now knows that the strict aliasing optimization
10559 should be suppressed for any reference to type @code{a2} and the
10560 expected behavior is obtained.
10561
10562 Finally, note that although the compiler can generate warnings for
10563 simple cases of unchecked conversions, there are tricker and more
10564 indirect ways of creating type incorrect aliases which the compiler
10565 cannot detect. Examples are the use of address overlays and unchecked
10566 conversions involving composite types containing access types as
10567 components. In such cases, no warnings are generated, but there can
10568 still be aliasing problems. One safe coding practice is to forbid the
10569 use of address clauses for type overlaying, and to allow unchecked
10570 conversion only for primitive types. This is not really a significant
10571 restriction since any possible desired effect can be achieved by
10572 unchecked conversion of access values.
10573
10574 The aliasing analysis done in strict aliasing mode can certainly
10575 have significant benefits. We have seen cases of large scale
10576 application code where the time is increased by up to 5% by turning
10577 this optimization off. If you have code that includes significant
10578 usage of unchecked conversion, you might want to just stick with
10579 @option{-O1} and avoid the entire issue. If you get adequate
10580 performance at this level of optimization level, that's probably
10581 the safest approach. If tests show that you really need higher
10582 levels of optimization, then you can experiment with @option{-O2}
10583 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10584 has on size and speed of the code. If you really need to use
10585 @option{-O2} with strict aliasing in effect, then you should
10586 review any uses of unchecked conversion of access types,
10587 particularly if you are getting the warnings described above.
10588
10589 @ifset vms
10590 @node Coverage Analysis
10591 @subsection Coverage Analysis
10592
10593 @noindent
10594 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10595 the user to determine the distribution of execution time across a program,
10596 @pxref{Profiling} for details of usage.
10597 @end ifset
10598
10599
10600 @node Text_IO Suggestions
10601 @section @code{Text_IO} Suggestions
10602 @cindex @code{Text_IO} and performance
10603
10604 @noindent
10605 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10606 the requirement of maintaining page and line counts. If performance
10607 is critical, a recommendation is to use @code{Stream_IO} instead of
10608 @code{Text_IO} for volume output, since this package has less overhead.
10609
10610 If @code{Text_IO} must be used, note that by default output to the standard
10611 output and standard error files is unbuffered (this provides better
10612 behavior when output statements are used for debugging, or if the
10613 progress of a program is observed by tracking the output, e.g. by
10614 using the Unix @command{tail -f} command to watch redirected output.
10615
10616 If you are generating large volumes of output with @code{Text_IO} and
10617 performance is an important factor, use a designated file instead
10618 of the standard output file, or change the standard output file to
10619 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10620
10621
10622
10623 @node Reducing Size of Ada Executables with gnatelim
10624 @section Reducing Size of Ada Executables with @code{gnatelim}
10625 @findex gnatelim
10626
10627 @noindent
10628 This section describes @command{gnatelim}, a tool which detects unused
10629 subprograms and helps the compiler to create a smaller executable for your
10630 program.
10631
10632 @menu
10633 * About gnatelim::
10634 * Running gnatelim::
10635 * Correcting the List of Eliminate Pragmas::
10636 * Making Your Executables Smaller::
10637 * Summary of the gnatelim Usage Cycle::
10638 @end menu
10639
10640 @node About gnatelim
10641 @subsection About @code{gnatelim}
10642
10643 @noindent
10644 When a program shares a set of Ada
10645 packages with other programs, it may happen that this program uses
10646 only a fraction of the subprograms defined in these packages. The code
10647 created for these unused subprograms increases the size of the executable.
10648
10649 @code{gnatelim} tracks unused subprograms in an Ada program and
10650 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10651 subprograms that are declared but never called. By placing the list of
10652 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10653 recompiling your program, you may decrease the size of its executable,
10654 because the compiler will not generate the code for 'eliminated' subprograms.
10655 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10656 information about this pragma.
10657
10658 @code{gnatelim} needs as its input data the name of the main subprogram
10659 and a bind file for a main subprogram.
10660
10661 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10662 the main subprogram. @code{gnatelim} can work with both Ada and C
10663 bind files; when both are present, it uses the Ada bind file.
10664 The following commands will build the program and create the bind file:
10665
10666 @smallexample
10667 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10668 $ gnatbind main_prog
10669 @end smallexample
10670
10671 Note that @code{gnatelim} needs neither object nor ALI files.
10672
10673 @node Running gnatelim
10674 @subsection Running @code{gnatelim}
10675
10676 @noindent
10677 @code{gnatelim} has the following command-line interface:
10678
10679 @smallexample
10680 $ gnatelim @ovar{options} name
10681 @end smallexample
10682
10683 @noindent
10684 @code{name} should be a name of a source file that contains the main subprogram
10685 of a program (partition).
10686
10687 @code{gnatelim} has the following switches:
10688
10689 @table @option
10690 @c !sort!
10691 @item ^-q^/QUIET^
10692 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10693 Quiet mode: by default @code{gnatelim} outputs to the standard error
10694 stream the number of program units left to be processed. This option turns
10695 this trace off.
10696
10697 @item ^-v^/VERBOSE^
10698 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10699 Verbose mode: @code{gnatelim} version information is printed as Ada
10700 comments to the standard output stream. Also, in addition to the number of
10701 program units left @code{gnatelim} will output the name of the current unit
10702 being processed.
10703
10704 @item ^-a^/ALL^
10705 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10706 Also look for subprograms from the GNAT run time that can be eliminated. Note
10707 that when @file{gnat.adc} is produced using this switch, the entire program
10708 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10709
10710 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10711 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10712 When looking for source files also look in directory @var{dir}. Specifying
10713 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10714 sources in the current directory.
10715
10716 @item ^-b^/BIND_FILE=^@var{bind_file}
10717 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10718 Specifies @var{bind_file} as the bind file to process. If not set, the name
10719 of the bind file is computed from the full expanded Ada name
10720 of a main subprogram.
10721
10722 @item ^-C^/CONFIG_FILE=^@var{config_file}
10723 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10724 Specifies a file @var{config_file} that contains configuration pragmas. The
10725 file must be specified with full path.
10726
10727 @item ^--GCC^/COMPILER^=@var{compiler_name}
10728 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10729 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10730 available on the path.
10731
10732 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10733 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10734 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10735 available on the path.
10736 @end table
10737
10738 @noindent
10739 @code{gnatelim} sends its output to the standard output stream, and all the
10740 tracing and debug information is sent to the standard error stream.
10741 In order to produce a proper GNAT configuration file
10742 @file{gnat.adc}, redirection must be used:
10743
10744 @smallexample
10745 @ifset vms
10746 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10747 @end ifset
10748 @ifclear vms
10749 $ gnatelim main_prog.adb > gnat.adc
10750 @end ifclear
10751 @end smallexample
10752
10753 @ifclear vms
10754 @noindent
10755 or
10756
10757 @smallexample
10758 $ gnatelim main_prog.adb >> gnat.adc
10759 @end smallexample
10760
10761 @noindent
10762 in order to append the @code{gnatelim} output to the existing contents of
10763 @file{gnat.adc}.
10764 @end ifclear
10765
10766 @node Correcting the List of Eliminate Pragmas
10767 @subsection Correcting the List of Eliminate Pragmas
10768
10769 @noindent
10770 In some rare cases @code{gnatelim} may try to eliminate
10771 subprograms that are actually called in the program. In this case, the
10772 compiler will generate an error message of the form:
10773
10774 @smallexample
10775 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10776 @end smallexample
10777
10778 @noindent
10779 You will need to manually remove the wrong @code{Eliminate} pragmas from
10780 the @file{gnat.adc} file. You should recompile your program
10781 from scratch after that, because you need a consistent @file{gnat.adc} file
10782 during the entire compilation.
10783
10784 @node Making Your Executables Smaller
10785 @subsection Making Your Executables Smaller
10786
10787 @noindent
10788 In order to get a smaller executable for your program you now have to
10789 recompile the program completely with the new @file{gnat.adc} file
10790 created by @code{gnatelim} in your current directory:
10791
10792 @smallexample
10793 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10794 @end smallexample
10795
10796 @noindent
10797 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10798 recompile everything
10799 with the set of pragmas @code{Eliminate} that you have obtained with
10800 @command{gnatelim}).
10801
10802 Be aware that the set of @code{Eliminate} pragmas is specific to each
10803 program. It is not recommended to merge sets of @code{Eliminate}
10804 pragmas created for different programs in one @file{gnat.adc} file.
10805
10806 @node Summary of the gnatelim Usage Cycle
10807 @subsection Summary of the gnatelim Usage Cycle
10808
10809 @noindent
10810 Here is a quick summary of the steps to be taken in order to reduce
10811 the size of your executables with @code{gnatelim}. You may use
10812 other GNAT options to control the optimization level,
10813 to produce the debugging information, to set search path, etc.
10814
10815 @enumerate
10816 @item
10817 Produce a bind file
10818
10819 @smallexample
10820 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10821 $ gnatbind main_prog
10822 @end smallexample
10823
10824 @item
10825 Generate a list of @code{Eliminate} pragmas
10826 @smallexample
10827 @ifset vms
10828 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10829 @end ifset
10830 @ifclear vms
10831 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10832 @end ifclear
10833 @end smallexample
10834
10835 @item
10836 Recompile the application
10837
10838 @smallexample
10839 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10840 @end smallexample
10841
10842 @end enumerate
10843
10844 @node Reducing Size of Executables with unused subprogram/data elimination
10845 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10846 @findex unused subprogram/data elimination
10847
10848 @noindent
10849 This section describes how you can eliminate unused subprograms and data from
10850 your executable just by setting options at compilation time.
10851
10852 @menu
10853 * About unused subprogram/data elimination::
10854 * Compilation options::
10855 * Example of unused subprogram/data elimination::
10856 @end menu
10857
10858 @node About unused subprogram/data elimination
10859 @subsection About unused subprogram/data elimination
10860
10861 @noindent
10862 By default, an executable contains all code and data of its composing objects
10863 (directly linked or coming from statically linked libraries), even data or code
10864 never used by this executable.
10865
10866 This feature will allow you to eliminate such unused code from your
10867 executable, making it smaller (in disk and in memory).
10868
10869 This functionality is available on all Linux platforms except for the IA-64
10870 architecture and on all cross platforms using the ELF binary file format.
10871 In both cases GNU binutils version 2.16 or later are required to enable it.
10872
10873 @node Compilation options
10874 @subsection Compilation options
10875
10876 @noindent
10877 The operation of eliminating the unused code and data from the final executable
10878 is directly performed by the linker.
10879
10880 In order to do this, it has to work with objects compiled with the
10881 following options:
10882 @option{-ffunction-sections} @option{-fdata-sections}.
10883 @cindex @option{-ffunction-sections} (@command{gcc})
10884 @cindex @option{-fdata-sections} (@command{gcc})
10885 These options are usable with C and Ada files.
10886 They will place respectively each
10887 function or data in a separate section in the resulting object file.
10888
10889 Once the objects and static libraries are created with these options, the
10890 linker can perform the dead code elimination. You can do this by setting
10891 the @option{-Wl,--gc-sections} option to gcc command or in the
10892 @option{-largs} section of @command{gnatmake}. This will perform a
10893 garbage collection of code and data never referenced.
10894
10895 If the linker performs a partial link (@option{-r} ld linker option), then you
10896 will need to provide one or several entry point using the
10897 @option{-e} / @option{--entry} ld option.
10898
10899 Note that objects compiled without the @option{-ffunction-sections} and
10900 @option{-fdata-sections} options can still be linked with the executable.
10901 However, no dead code elimination will be performed on those objects (they will
10902 be linked as is).
10903
10904 The GNAT static library is now compiled with -ffunction-sections and
10905 -fdata-sections on some platforms. This allows you to eliminate the unused code
10906 and data of the GNAT library from your executable.
10907
10908 @node Example of unused subprogram/data elimination
10909 @subsection Example of unused subprogram/data elimination
10910
10911 @noindent
10912 Here is a simple example:
10913
10914 @smallexample @c ada
10915 with Aux;
10916
10917 procedure Test is
10918 begin
10919    Aux.Used (10);
10920 end Test;
10921
10922 package Aux is
10923    Used_Data   : Integer;
10924    Unused_Data : Integer;
10925
10926    procedure Used   (Data : Integer);
10927    procedure Unused (Data : Integer);
10928 end Aux;
10929
10930 package body Aux is
10931    procedure Used (Data : Integer) is
10932    begin
10933       Used_Data := Data;
10934    end Used;
10935
10936    procedure Unused (Data : Integer) is
10937    begin
10938       Unused_Data := Data;
10939    end Unused;
10940 end Aux;
10941 @end smallexample
10942
10943 @noindent
10944 @code{Unused} and @code{Unused_Data} are never referenced in this code
10945 excerpt, and hence they may be safely removed from the final executable.
10946
10947 @smallexample
10948 $ gnatmake test
10949
10950 $ nm test | grep used
10951 020015f0 T aux__unused
10952 02005d88 B aux__unused_data
10953 020015cc T aux__used
10954 02005d84 B aux__used_data
10955
10956 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10957      -largs -Wl,--gc-sections
10958
10959 $ nm test | grep used
10960 02005350 T aux__used
10961 0201ffe0 B aux__used_data
10962 @end smallexample
10963
10964 @noindent
10965 It can be observed that the procedure @code{Unused} and the object
10966 @code{Unused_Data} are removed by the linker when using the
10967 appropriate options.
10968
10969 @c ********************************
10970 @node Renaming Files Using gnatchop
10971 @chapter Renaming Files Using @code{gnatchop}
10972 @findex gnatchop
10973
10974 @noindent
10975 This chapter discusses how to handle files with multiple units by using
10976 the @code{gnatchop} utility. This utility is also useful in renaming
10977 files to meet the standard GNAT default file naming conventions.
10978
10979 @menu
10980 * Handling Files with Multiple Units::
10981 * Operating gnatchop in Compilation Mode::
10982 * Command Line for gnatchop::
10983 * Switches for gnatchop::
10984 * Examples of gnatchop Usage::
10985 @end menu
10986
10987 @node Handling Files with Multiple Units
10988 @section Handling Files with Multiple Units
10989
10990 @noindent
10991 The basic compilation model of GNAT requires that a file submitted to the
10992 compiler have only one unit and there be a strict correspondence
10993 between the file name and the unit name.
10994
10995 The @code{gnatchop} utility allows both of these rules to be relaxed,
10996 allowing GNAT to process files which contain multiple compilation units
10997 and files with arbitrary file names. @code{gnatchop}
10998 reads the specified file and generates one or more output files,
10999 containing one unit per file. The unit and the file name correspond,
11000 as required by GNAT.
11001
11002 If you want to permanently restructure a set of ``foreign'' files so that
11003 they match the GNAT rules, and do the remaining development using the
11004 GNAT structure, you can simply use @command{gnatchop} once, generate the
11005 new set of files and work with them from that point on.
11006
11007 Alternatively, if you want to keep your files in the ``foreign'' format,
11008 perhaps to maintain compatibility with some other Ada compilation
11009 system, you can set up a procedure where you use @command{gnatchop} each
11010 time you compile, regarding the source files that it writes as temporary
11011 files that you throw away.
11012
11013 Note that if your file containing multiple units starts with a byte order
11014 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11015 will each start with a copy of this BOM, meaning that they can be compiled
11016 automatically in UTF-8 mode without needing to specify an explicit encoding.
11017
11018 @node Operating gnatchop in Compilation Mode
11019 @section Operating gnatchop in Compilation Mode
11020
11021 @noindent
11022 The basic function of @code{gnatchop} is to take a file with multiple units
11023 and split it into separate files. The boundary between files is reasonably
11024 clear, except for the issue of comments and pragmas. In default mode, the
11025 rule is that any pragmas between units belong to the previous unit, except
11026 that configuration pragmas always belong to the following unit. Any comments
11027 belong to the following unit. These rules
11028 almost always result in the right choice of
11029 the split point without needing to mark it explicitly and most users will
11030 find this default to be what they want. In this default mode it is incorrect to
11031 submit a file containing only configuration pragmas, or one that ends in
11032 configuration pragmas, to @code{gnatchop}.
11033
11034 However, using a special option to activate ``compilation mode'',
11035 @code{gnatchop}
11036 can perform another function, which is to provide exactly the semantics
11037 required by the RM for handling of configuration pragmas in a compilation.
11038 In the absence of configuration pragmas (at the main file level), this
11039 option has no effect, but it causes such configuration pragmas to be handled
11040 in a quite different manner.
11041
11042 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11043 only configuration pragmas, then this file is appended to the
11044 @file{gnat.adc} file in the current directory. This behavior provides
11045 the required behavior described in the RM for the actions to be taken
11046 on submitting such a file to the compiler, namely that these pragmas
11047 should apply to all subsequent compilations in the same compilation
11048 environment. Using GNAT, the current directory, possibly containing a
11049 @file{gnat.adc} file is the representation
11050 of a compilation environment. For more information on the
11051 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11052
11053 Second, in compilation mode, if @code{gnatchop}
11054 is given a file that starts with
11055 configuration pragmas, and contains one or more units, then these
11056 configuration pragmas are prepended to each of the chopped files. This
11057 behavior provides the required behavior described in the RM for the
11058 actions to be taken on compiling such a file, namely that the pragmas
11059 apply to all units in the compilation, but not to subsequently compiled
11060 units.
11061
11062 Finally, if configuration pragmas appear between units, they are appended
11063 to the previous unit. This results in the previous unit being illegal,
11064 since the compiler does not accept configuration pragmas that follow
11065 a unit. This provides the required RM behavior that forbids configuration
11066 pragmas other than those preceding the first compilation unit of a
11067 compilation.
11068
11069 For most purposes, @code{gnatchop} will be used in default mode. The
11070 compilation mode described above is used only if you need exactly
11071 accurate behavior with respect to compilations, and you have files
11072 that contain multiple units and configuration pragmas. In this
11073 circumstance the use of @code{gnatchop} with the compilation mode
11074 switch provides the required behavior, and is for example the mode
11075 in which GNAT processes the ACVC tests.
11076
11077 @node Command Line for gnatchop
11078 @section Command Line for @code{gnatchop}
11079
11080 @noindent
11081 The @code{gnatchop} command has the form:
11082
11083 @smallexample
11084 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11085       @ovar{directory}
11086 @end smallexample
11087
11088 @noindent
11089 The only required argument is the file name of the file to be chopped.
11090 There are no restrictions on the form of this file name. The file itself
11091 contains one or more Ada units, in normal GNAT format, concatenated
11092 together. As shown, more than one file may be presented to be chopped.
11093
11094 When run in default mode, @code{gnatchop} generates one output file in
11095 the current directory for each unit in each of the files.
11096
11097 @var{directory}, if specified, gives the name of the directory to which
11098 the output files will be written. If it is not specified, all files are
11099 written to the current directory.
11100
11101 For example, given a
11102 file called @file{hellofiles} containing
11103
11104 @smallexample @c ada
11105 @group
11106 @cartouche
11107 procedure hello;
11108
11109 with Text_IO; use Text_IO;
11110 procedure hello is
11111 begin
11112    Put_Line ("Hello");
11113 end hello;
11114 @end cartouche
11115 @end group
11116 @end smallexample
11117
11118 @noindent
11119 the command
11120
11121 @smallexample
11122 $ gnatchop ^hellofiles^HELLOFILES.^
11123 @end smallexample
11124
11125 @noindent
11126 generates two files in the current directory, one called
11127 @file{hello.ads} containing the single line that is the procedure spec,
11128 and the other called @file{hello.adb} containing the remaining text. The
11129 original file is not affected. The generated files can be compiled in
11130 the normal manner.
11131
11132 @noindent
11133 When gnatchop is invoked on a file that is empty or that contains only empty
11134 lines and/or comments, gnatchop will not fail, but will not produce any
11135 new sources.
11136
11137 For example, given a
11138 file called @file{toto.txt} containing
11139
11140 @smallexample @c ada
11141 @group
11142 @cartouche
11143 --  Just a comment
11144 @end cartouche
11145 @end group
11146 @end smallexample
11147
11148 @noindent
11149 the command
11150
11151 @smallexample
11152 $ gnatchop ^toto.txt^TOT.TXT^
11153 @end smallexample
11154
11155 @noindent
11156 will not produce any new file and will result in the following warnings:
11157
11158 @smallexample
11159 toto.txt:1:01: warning: empty file, contains no compilation units
11160 no compilation units found
11161 no source files written
11162 @end smallexample
11163
11164 @node Switches for gnatchop
11165 @section Switches for @code{gnatchop}
11166
11167 @noindent
11168 @command{gnatchop} recognizes the following switches:
11169
11170 @table @option
11171 @c !sort!
11172
11173 @item --version
11174 @cindex @option{--version} @command{gnatchop}
11175 Display Copyright and version, then exit disregarding all other options.
11176
11177 @item --help
11178 @cindex @option{--help} @command{gnatchop}
11179 If @option{--version} was not used, display usage, then exit disregarding
11180 all other options.
11181
11182 @item ^-c^/COMPILATION^
11183 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11184 Causes @code{gnatchop} to operate in compilation mode, in which
11185 configuration pragmas are handled according to strict RM rules. See
11186 previous section for a full description of this mode.
11187
11188 @ifclear vms
11189 @item -gnat@var{xxx}
11190 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11191 used to parse the given file. Not all @var{xxx} options make sense,
11192 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11193 process a source file that uses Latin-2 coding for identifiers.
11194 @end ifclear
11195
11196 @item ^-h^/HELP^
11197 Causes @code{gnatchop} to generate a brief help summary to the standard
11198 output file showing usage information.
11199
11200 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11201 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11202 Limit generated file names to the specified number @code{mm}
11203 of characters.
11204 This is useful if the
11205 resulting set of files is required to be interoperable with systems
11206 which limit the length of file names.
11207 @ifset vms
11208 If no value is given, or
11209 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11210 a default of 39, suitable for OpenVMS Alpha
11211 Systems, is assumed
11212 @end ifset
11213 @ifclear vms
11214 No space is allowed between the @option{-k} and the numeric value. The numeric
11215 value may be omitted in which case a default of @option{-k8},
11216 suitable for use
11217 with DOS-like file systems, is used. If no @option{-k} switch
11218 is present then
11219 there is no limit on the length of file names.
11220 @end ifclear
11221
11222 @item ^-p^/PRESERVE^
11223 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11224 Causes the file ^modification^creation^ time stamp of the input file to be
11225 preserved and used for the time stamp of the output file(s). This may be
11226 useful for preserving coherency of time stamps in an environment where
11227 @code{gnatchop} is used as part of a standard build process.
11228
11229 @item ^-q^/QUIET^
11230 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11231 Causes output of informational messages indicating the set of generated
11232 files to be suppressed. Warnings and error messages are unaffected.
11233
11234 @item ^-r^/REFERENCE^
11235 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11236 @findex Source_Reference
11237 Generate @code{Source_Reference} pragmas. Use this switch if the output
11238 files are regarded as temporary and development is to be done in terms
11239 of the original unchopped file. This switch causes
11240 @code{Source_Reference} pragmas to be inserted into each of the
11241 generated files to refers back to the original file name and line number.
11242 The result is that all error messages refer back to the original
11243 unchopped file.
11244 In addition, the debugging information placed into the object file (when
11245 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11246 specified)
11247 also refers back to this original file so that tools like profilers and
11248 debuggers will give information in terms of the original unchopped file.
11249
11250 If the original file to be chopped itself contains
11251 a @code{Source_Reference}
11252 pragma referencing a third file, then gnatchop respects
11253 this pragma, and the generated @code{Source_Reference} pragmas
11254 in the chopped file refer to the original file, with appropriate
11255 line numbers. This is particularly useful when @code{gnatchop}
11256 is used in conjunction with @code{gnatprep} to compile files that
11257 contain preprocessing statements and multiple units.
11258
11259 @item ^-v^/VERBOSE^
11260 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11261 Causes @code{gnatchop} to operate in verbose mode. The version
11262 number and copyright notice are output, as well as exact copies of
11263 the gnat1 commands spawned to obtain the chop control information.
11264
11265 @item ^-w^/OVERWRITE^
11266 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11267 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11268 fatal error if there is already a file with the same name as a
11269 file it would otherwise output, in other words if the files to be
11270 chopped contain duplicated units. This switch bypasses this
11271 check, and causes all but the last instance of such duplicated
11272 units to be skipped.
11273
11274 @ifclear vms
11275 @item --GCC=@var{xxxx}
11276 @cindex @option{--GCC=} (@code{gnatchop})
11277 Specify the path of the GNAT parser to be used. When this switch is used,
11278 no attempt is made to add the prefix to the GNAT parser executable.
11279 @end ifclear
11280 @end table
11281
11282 @node Examples of gnatchop Usage
11283 @section Examples of @code{gnatchop} Usage
11284
11285 @table @code
11286 @ifset vms
11287 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11288 @end ifset
11289 @ifclear vms
11290 @item gnatchop -w hello_s.ada prerelease/files
11291 @end ifclear
11292
11293 Chops the source file @file{hello_s.ada}. The output files will be
11294 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11295 overwriting any
11296 files with matching names in that directory (no files in the current
11297 directory are modified).
11298
11299 @item gnatchop ^archive^ARCHIVE.^
11300 Chops the source file @file{^archive^ARCHIVE.^}
11301 into the current directory. One
11302 useful application of @code{gnatchop} is in sending sets of sources
11303 around, for example in email messages. The required sources are simply
11304 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11305 command), and then
11306 @command{gnatchop} is used at the other end to reconstitute the original
11307 file names.
11308
11309 @item gnatchop file1 file2 file3 direc
11310 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11311 the resulting files in the directory @file{direc}. Note that if any units
11312 occur more than once anywhere within this set of files, an error message
11313 is generated, and no files are written. To override this check, use the
11314 @option{^-w^/OVERWRITE^} switch,
11315 in which case the last occurrence in the last file will
11316 be the one that is output, and earlier duplicate occurrences for a given
11317 unit will be skipped.
11318 @end table
11319
11320 @node Configuration Pragmas
11321 @chapter Configuration Pragmas
11322 @cindex Configuration pragmas
11323 @cindex Pragmas, configuration
11324
11325 @noindent
11326 Configuration pragmas include those pragmas described as
11327 such in the Ada Reference Manual, as well as
11328 implementation-dependent pragmas that are configuration pragmas.
11329 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11330 for details on these additional GNAT-specific configuration pragmas.
11331 Most notably, the pragma @code{Source_File_Name}, which allows
11332 specifying non-default names for source files, is a configuration
11333 pragma. The following is a complete list of configuration pragmas
11334 recognized by GNAT:
11335
11336 @smallexample
11337    Ada_83
11338    Ada_95
11339    Ada_05
11340    Ada_2005
11341    Assertion_Policy
11342    Assume_No_Invalid_Values
11343    C_Pass_By_Copy
11344    Check_Name
11345    Check_Policy
11346    Compile_Time_Error
11347    Compile_Time_Warning
11348    Compiler_Unit
11349    Component_Alignment
11350    Convention_Identifier
11351    Debug_Policy
11352    Detect_Blocking
11353    Discard_Names
11354    Elaboration_Checks
11355    Eliminate
11356    Extend_System
11357    Extensions_Allowed
11358    External_Name_Casing
11359    Fast_Math
11360    Favor_Top_Level
11361    Float_Representation
11362    Implicit_Packing
11363    Initialize_Scalars
11364    Interrupt_State
11365    License
11366    Locking_Policy
11367    Long_Float
11368    No_Run_Time
11369    No_Strict_Aliasing
11370    Normalize_Scalars
11371    Optimize_Alignment
11372    Persistent_BSS
11373    Polling
11374    Priority_Specific_Dispatching
11375    Profile
11376    Profile_Warnings
11377    Propagate_Exceptions
11378    Queuing_Policy
11379    Ravenscar
11380    Restricted_Run_Time
11381    Restrictions
11382    Restrictions_Warnings
11383    Reviewable
11384    Source_File_Name
11385    Source_File_Name_Project
11386    Style_Checks
11387    Suppress
11388    Suppress_Exception_Locations
11389    Task_Dispatching_Policy
11390    Universal_Data
11391    Unsuppress
11392    Use_VADS_Size
11393    Validity_Checks
11394    Warnings
11395    Wide_Character_Encoding
11396
11397 @end smallexample
11398
11399 @menu
11400 * Handling of Configuration Pragmas::
11401 * The Configuration Pragmas Files::
11402 @end menu
11403
11404 @node Handling of Configuration Pragmas
11405 @section Handling of Configuration Pragmas
11406
11407 Configuration pragmas may either appear at the start of a compilation
11408 unit, in which case they apply only to that unit, or they may apply to
11409 all compilations performed in a given compilation environment.
11410
11411 GNAT also provides the @code{gnatchop} utility to provide an automatic
11412 way to handle configuration pragmas following the semantics for
11413 compilations (that is, files with multiple units), described in the RM.
11414 See @ref{Operating gnatchop in Compilation Mode} for details.
11415 However, for most purposes, it will be more convenient to edit the
11416 @file{gnat.adc} file that contains configuration pragmas directly,
11417 as described in the following section.
11418
11419 @node The Configuration Pragmas Files
11420 @section The Configuration Pragmas Files
11421 @cindex @file{gnat.adc}
11422
11423 @noindent
11424 In GNAT a compilation environment is defined by the current
11425 directory at the time that a compile command is given. This current
11426 directory is searched for a file whose name is @file{gnat.adc}. If
11427 this file is present, it is expected to contain one or more
11428 configuration pragmas that will be applied to the current compilation.
11429 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11430 considered.
11431
11432 Configuration pragmas may be entered into the @file{gnat.adc} file
11433 either by running @code{gnatchop} on a source file that consists only of
11434 configuration pragmas, or more conveniently  by
11435 direct editing of the @file{gnat.adc} file, which is a standard format
11436 source file.
11437
11438 In addition to @file{gnat.adc}, additional files containing configuration
11439 pragmas may be applied to the current compilation using the switch
11440 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11441 contains only configuration pragmas. These configuration pragmas are
11442 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11443 is present and switch @option{-gnatA} is not used).
11444
11445 It is allowed to specify several switches @option{-gnatec}, all of which
11446 will be taken into account.
11447
11448 If you are using project file, a separate mechanism is provided using
11449 project attributes, see @ref{Specifying Configuration Pragmas} for more
11450 details.
11451
11452 @ifset vms
11453 Of special interest to GNAT OpenVMS Alpha is the following
11454 configuration pragma:
11455
11456 @smallexample @c ada
11457 @cartouche
11458 pragma Extend_System (Aux_DEC);
11459 @end cartouche
11460 @end smallexample
11461
11462 @noindent
11463 In the presence of this pragma, GNAT adds to the definition of the
11464 predefined package SYSTEM all the additional types and subprograms that are
11465 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11466 @end ifset
11467
11468 @node Handling Arbitrary File Naming Conventions Using gnatname
11469 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11470 @cindex Arbitrary File Naming Conventions
11471
11472 @menu
11473 * Arbitrary File Naming Conventions::
11474 * Running gnatname::
11475 * Switches for gnatname::
11476 * Examples of gnatname Usage::
11477 @end menu
11478
11479 @node Arbitrary File Naming Conventions
11480 @section Arbitrary File Naming Conventions
11481
11482 @noindent
11483 The GNAT compiler must be able to know the source file name of a compilation
11484 unit.  When using the standard GNAT default file naming conventions
11485 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11486 does not need additional information.
11487
11488 @noindent
11489 When the source file names do not follow the standard GNAT default file naming
11490 conventions, the GNAT compiler must be given additional information through
11491 a configuration pragmas file (@pxref{Configuration Pragmas})
11492 or a project file.
11493 When the non-standard file naming conventions are well-defined,
11494 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11495 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11496 if the file naming conventions are irregular or arbitrary, a number
11497 of pragma @code{Source_File_Name} for individual compilation units
11498 must be defined.
11499 To help maintain the correspondence between compilation unit names and
11500 source file names within the compiler,
11501 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11502 set of files.
11503
11504 @node Running gnatname
11505 @section Running @code{gnatname}
11506
11507 @noindent
11508 The usual form of the @code{gnatname} command is
11509
11510 @smallexample
11511 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11512       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11513 @end smallexample
11514
11515 @noindent
11516 All of the arguments are optional. If invoked without any argument,
11517 @code{gnatname} will display its usage.
11518
11519 @noindent
11520 When used with at least one naming pattern, @code{gnatname} will attempt to
11521 find all the compilation units in files that follow at least one of the
11522 naming patterns. To find these compilation units,
11523 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11524 regular files.
11525
11526 @noindent
11527 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11528 Each Naming Pattern is enclosed between double quotes.
11529 A Naming Pattern is a regular expression similar to the wildcard patterns
11530 used in file names by the Unix shells or the DOS prompt.
11531
11532 @noindent
11533 @code{gnatname} may be called with several sections of directories/patterns.
11534 Sections are separated by switch @code{--and}. In each section, there must be
11535 at least one pattern. If no directory is specified in a section, the current
11536 directory (or the project directory is @code{-P} is used) is implied.
11537 The options other that the directory switches and the patterns apply globally
11538 even if they are in different sections.
11539
11540 @noindent
11541 Examples of Naming Patterns are
11542
11543 @smallexample
11544    "*.[12].ada"
11545    "*.ad[sb]*"
11546    "body_*"    "spec_*"
11547 @end smallexample
11548
11549 @noindent
11550 For a more complete description of the syntax of Naming Patterns,
11551 see the second kind of regular expressions described in @file{g-regexp.ads}
11552 (the ``Glob'' regular expressions).
11553
11554 @noindent
11555 When invoked with no switch @code{-P}, @code{gnatname} will create a
11556 configuration pragmas file @file{gnat.adc} in the current working directory,
11557 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11558 unit.
11559
11560 @node Switches for gnatname
11561 @section Switches for @code{gnatname}
11562
11563 @noindent
11564 Switches for @code{gnatname} must precede any specified Naming Pattern.
11565
11566 @noindent
11567 You may specify any of the following switches to @code{gnatname}:
11568
11569 @table @option
11570 @c !sort!
11571
11572 @item --version
11573 @cindex @option{--version} @command{gnatname}
11574 Display Copyright and version, then exit disregarding all other options.
11575
11576 @item --help
11577 @cindex @option{--help} @command{gnatname}
11578 If @option{--version} was not used, display usage, then exit disregarding
11579 all other options.
11580
11581 @item --and
11582 Start another section of directories/patterns.
11583
11584 @item ^-c^/CONFIG_FILE=^@file{file}
11585 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11586 Create a configuration pragmas file @file{file} (instead of the default
11587 @file{gnat.adc}).
11588 @ifclear vms
11589 There may be zero, one or more space between @option{-c} and
11590 @file{file}.
11591 @end ifclear
11592 @file{file} may include directory information. @file{file} must be
11593 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11594 When a switch @option{^-c^/CONFIG_FILE^} is
11595 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11596
11597 @item ^-d^/SOURCE_DIRS=^@file{dir}
11598 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11599 Look for source files in directory @file{dir}. There may be zero, one or more
11600 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11601 When a switch @option{^-d^/SOURCE_DIRS^}
11602 is specified, the current working directory will not be searched for source
11603 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11604 or @option{^-D^/DIR_FILES^} switch.
11605 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11606 If @file{dir} is a relative path, it is relative to the directory of
11607 the configuration pragmas file specified with switch
11608 @option{^-c^/CONFIG_FILE^},
11609 or to the directory of the project file specified with switch
11610 @option{^-P^/PROJECT_FILE^} or,
11611 if neither switch @option{^-c^/CONFIG_FILE^}
11612 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11613 current working directory. The directory
11614 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11615
11616 @item ^-D^/DIRS_FILE=^@file{file}
11617 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11618 Look for source files in all directories listed in text file @file{file}.
11619 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11620 and @file{file}.
11621 @file{file} must be an existing, readable text file.
11622 Each nonempty line in @file{file} must be a directory.
11623 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11624 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11625 @file{file}.
11626
11627 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11628 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11629 Foreign patterns. Using this switch, it is possible to add sources of languages
11630 other than Ada to the list of sources of a project file.
11631 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11632 For example,
11633 @smallexample
11634 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11635 @end smallexample
11636 @noindent
11637 will look for Ada units in all files with the @file{.ada} extension,
11638 and will add to the list of file for project @file{prj.gpr} the C files
11639 with extension @file{.^c^C^}.
11640
11641 @item ^-h^/HELP^
11642 @cindex @option{^-h^/HELP^} (@code{gnatname})
11643 Output usage (help) information. The output is written to @file{stdout}.
11644
11645 @item ^-P^/PROJECT_FILE=^@file{proj}
11646 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11647 Create or update project file @file{proj}. There may be zero, one or more space
11648 between @option{-P} and @file{proj}. @file{proj} may include directory
11649 information. @file{proj} must be writable.
11650 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11651 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11652 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11653
11654 @item ^-v^/VERBOSE^
11655 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11656 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11657 This includes name of the file written, the name of the directories to search
11658 and, for each file in those directories whose name matches at least one of
11659 the Naming Patterns, an indication of whether the file contains a unit,
11660 and if so the name of the unit.
11661
11662 @item ^-v -v^/VERBOSE /VERBOSE^
11663 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11664 Very Verbose mode. In addition to the output produced in verbose mode,
11665 for each file in the searched directories whose name matches none of
11666 the Naming Patterns, an indication is given that there is no match.
11667
11668 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11669 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11670 Excluded patterns. Using this switch, it is possible to exclude some files
11671 that would match the name patterns. For example,
11672 @smallexample
11673 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11674 @end smallexample
11675 @noindent
11676 will look for Ada units in all files with the @file{.ada} extension,
11677 except those whose names end with @file{_nt.ada}.
11678
11679 @end table
11680
11681 @node Examples of gnatname Usage
11682 @section Examples of @code{gnatname} Usage
11683
11684 @ifset vms
11685 @smallexample
11686 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11687 @end smallexample
11688 @end ifset
11689
11690 @ifclear vms
11691 @smallexample
11692 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11693 @end smallexample
11694 @end ifclear
11695
11696 @noindent
11697 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11698 and be writable. In addition, the directory
11699 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11700 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11701
11702 @ifclear vms
11703 Note the optional spaces after @option{-c} and @option{-d}.
11704 @end ifclear
11705
11706 @smallexample
11707 @ifclear vms
11708 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11709   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11710 @end ifclear
11711 @ifset vms
11712 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11713   /EXCLUDED_PATTERN=*_nt_body.ada
11714   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11715   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11716 @end ifset
11717 @end smallexample
11718
11719 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11720 even in conjunction with one or several switches
11721 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11722 are used in this example.
11723
11724 @c *****************************************
11725 @c * G N A T  P r o j e c t  M a n a g e r *
11726 @c *****************************************
11727 @node GNAT Project Manager
11728 @chapter GNAT Project Manager
11729
11730 @menu
11731 * Introduction::
11732 * Examples of Project Files::
11733 * Project File Syntax::
11734 * Objects and Sources in Project Files::
11735 * Importing Projects::
11736 * Project Extension::
11737 * Project Hierarchy Extension::
11738 * External References in Project Files::
11739 * Packages in Project Files::
11740 * Variables from Imported Projects::
11741 * Naming Schemes::
11742 * Library Projects::
11743 * Stand-alone Library Projects::
11744 * Switches Related to Project Files::
11745 * Tools Supporting Project Files::
11746 * An Extended Example::
11747 * Project File Complete Syntax::
11748 @end menu
11749
11750 @c ****************
11751 @c * Introduction *
11752 @c ****************
11753
11754 @node Introduction
11755 @section Introduction
11756
11757 @noindent
11758 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11759 you to manage complex builds involving a number of source files, directories,
11760 and compilation options for different system configurations. In particular,
11761 project files allow you to specify:
11762 @itemize @bullet
11763 @item
11764 The directory or set of directories containing the source files, and/or the
11765 names of the specific source files themselves
11766 @item
11767 The directory in which the compiler's output
11768 (@file{ALI} files, object files, tree files) is to be placed
11769 @item
11770 The directory in which the executable programs is to be placed
11771 @item
11772 ^Switch^Switch^ settings for any of the project-enabled tools
11773 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11774 @code{gnatfind}); you can apply these settings either globally or to individual
11775 compilation units.
11776 @item
11777 The source files containing the main subprogram(s) to be built
11778 @item
11779 The source programming language(s) (currently Ada and/or C)
11780 @item
11781 Source file naming conventions; you can specify these either globally or for
11782 individual compilation units
11783 @end itemize
11784
11785 @menu
11786 * Project Files::
11787 @end menu
11788
11789 @node Project Files
11790 @subsection Project Files
11791
11792 @noindent
11793 Project files are written in a syntax close to that of Ada, using  familiar
11794 notions such as packages, context clauses, declarations, default values,
11795 assignments, and inheritance. Finally, project files can be built
11796 hierarchically from other project files, simplifying complex system
11797 integration and project reuse.
11798
11799 A @dfn{project} is a specific set of values for various compilation properties.
11800 The settings for a given project are described by means of
11801 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11802 Property values in project files are either strings or lists of strings.
11803 Properties that are not explicitly set receive default values.  A project
11804 file may interrogate the values of @dfn{external variables} (user-defined
11805 command-line switches or environment variables), and it may specify property
11806 settings conditionally, based on the value of such variables.
11807
11808 In simple cases, a project's source files depend only on other source files
11809 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11810 used in
11811 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11812 the Project Manager also allows more sophisticated arrangements,
11813 where the source files in one project depend on source files in other
11814 projects:
11815 @itemize @bullet
11816 @item
11817 One project can @emph{import} other projects containing needed source files.
11818 @item
11819 You can organize GNAT projects in a hierarchy: a @emph{child} project
11820 can extend a @emph{parent} project, inheriting the parent's source files and
11821 optionally overriding any of them with alternative versions
11822 @end itemize
11823
11824 @noindent
11825 More generally, the Project Manager lets you structure large development
11826 efforts into hierarchical subsystems, where build decisions are delegated
11827 to the subsystem level, and thus different compilation environments
11828 (^switch^switch^ settings) used for different subsystems.
11829
11830 The Project Manager is invoked through the
11831 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11832 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11833 @ifclear vms
11834 There may be zero, one or more spaces between @option{-P} and
11835 @option{@emph{projectfile}}.
11836 @end ifclear
11837 If you want to define (on the command line) an external variable that is
11838 queried by the project file, you must use the
11839 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11840 The Project Manager parses and interprets the project file, and drives the
11841 invoked tool based on the project settings.
11842
11843 The Project Manager supports a wide range of development strategies,
11844 for systems of all sizes.  Here are some typical practices that are
11845 easily handled:
11846 @itemize @bullet
11847 @item
11848 Using a common set of source files, but generating object files in different
11849 directories via different ^switch^switch^ settings
11850 @item
11851 Using a mostly-shared set of source files, but with different versions of
11852 some unit or units
11853 @end itemize
11854
11855 @noindent
11856 The destination of an executable can be controlled inside a project file
11857 using the @option{^-o^-o^}
11858 ^switch^switch^.
11859 In the absence of such a ^switch^switch^ either inside
11860 the project file or on the command line, any executable files generated by
11861 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11862 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11863 in the object directory of the project.
11864
11865 You can use project files to achieve some of the effects of a source
11866 versioning system (for example, defining separate projects for
11867 the different sets of sources that comprise different releases) but the
11868 Project Manager is independent of any source configuration management tools
11869 that might be used by the developers.
11870
11871 The next section introduces the main features of GNAT's project facility
11872 through a sequence of examples; subsequent sections will present the syntax
11873 and semantics in more detail. A more formal description of the project
11874 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11875 Reference Manual}.
11876
11877 @c *****************************
11878 @c * Examples of Project Files *
11879 @c *****************************
11880
11881 @node Examples of Project Files
11882 @section Examples of Project Files
11883 @noindent
11884 This section illustrates some of the typical uses of project files and
11885 explains their basic structure and behavior.
11886
11887 @menu
11888 * Common Sources with Different ^Switches^Switches^ and Directories::
11889 * Using External Variables::
11890 * Importing Other Projects::
11891 * Extending a Project::
11892 @end menu
11893
11894 @node Common Sources with Different ^Switches^Switches^ and Directories
11895 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11896
11897 @menu
11898 * Source Files::
11899 * Specifying the Object Directory::
11900 * Specifying the Exec Directory::
11901 * Project File Packages::
11902 * Specifying ^Switch^Switch^ Settings::
11903 * Main Subprograms::
11904 * Executable File Names::
11905 * Source File Naming Conventions::
11906 * Source Language(s)::
11907 @end menu
11908
11909 @noindent
11910 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11911 @file{proc.adb} are in the @file{/common} directory.  The file
11912 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11913 package @code{Pack}.  We want to compile these source files under two sets
11914 of ^switches^switches^:
11915 @itemize @bullet
11916 @item
11917 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11918 and the @option{^-gnata^-gnata^},
11919 @option{^-gnato^-gnato^},
11920 and @option{^-gnatE^-gnatE^} switches to the
11921 compiler; the compiler's output is to appear in @file{/common/debug}
11922 @item
11923 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11924 to the compiler; the compiler's output is to appear in @file{/common/release}
11925 @end itemize
11926
11927 @noindent
11928 The GNAT project files shown below, respectively @file{debug.gpr} and
11929 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11930
11931 Schematically:
11932 @smallexample
11933 @group
11934 ^/common^[COMMON]^
11935   debug.gpr
11936   release.gpr
11937   pack.ads
11938   pack.adb
11939   proc.adb
11940 @end group
11941 @group
11942 ^/common/debug^[COMMON.DEBUG]^
11943   proc.ali, proc.o
11944   pack.ali, pack.o
11945 @end group
11946 @group
11947 ^/common/release^[COMMON.RELEASE]^
11948   proc.ali, proc.o
11949   pack.ali, pack.o
11950 @end group
11951 @end smallexample
11952 Here are the corresponding project files:
11953
11954 @smallexample @c projectfile
11955 @group
11956 project Debug is
11957   for Object_Dir use "debug";
11958   for Main use ("proc");
11959
11960   package Builder is
11961     for ^Default_Switches^Default_Switches^ ("Ada")
11962         use ("^-g^-g^");
11963     for Executable ("proc.adb") use "proc1";
11964   end Builder;
11965 @end group
11966
11967 @group
11968   package Compiler is
11969     for ^Default_Switches^Default_Switches^ ("Ada")
11970        use ("-fstack-check",
11971             "^-gnata^-gnata^",
11972             "^-gnato^-gnato^",
11973             "^-gnatE^-gnatE^");
11974   end Compiler;
11975 end Debug;
11976 @end group
11977 @end smallexample
11978
11979 @smallexample @c projectfile
11980 @group
11981 project Release is
11982   for Object_Dir use "release";
11983   for Exec_Dir use ".";
11984   for Main use ("proc");
11985
11986   package Compiler is
11987     for ^Default_Switches^Default_Switches^ ("Ada")
11988         use ("^-O2^-O2^");
11989   end Compiler;
11990 end Release;
11991 @end group
11992 @end smallexample
11993
11994 @noindent
11995 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11996 insensitive), and analogously the project defined by @file{release.gpr} is
11997 @code{"Release"}.  For consistency the file should have the same name as the
11998 project, and the project file's extension should be @code{"gpr"}. These
11999 conventions are not required, but a warning is issued if they are not followed.
12000
12001 If the current directory is @file{^/temp^[TEMP]^}, then the command
12002 @smallexample
12003 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12004 @end smallexample
12005
12006 @noindent
12007 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12008 as well as the @code{^proc1^PROC1.EXE^} executable,
12009 using the ^switch^switch^ settings defined in the project file.
12010
12011 Likewise, the command
12012 @smallexample
12013 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12014 @end smallexample
12015
12016 @noindent
12017 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12018 and the @code{^proc^PROC.EXE^}
12019 executable in @file{^/common^[COMMON]^},
12020 using the ^switch^switch^ settings from the project file.
12021
12022 @node Source Files
12023 @unnumberedsubsubsec Source Files
12024
12025 @noindent
12026 If a project file does not explicitly specify a set of source directories or
12027 a set of source files, then by default the project's source files are the
12028 Ada source files in the project file directory.  Thus @file{pack.ads},
12029 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12030
12031 @node Specifying the Object Directory
12032 @unnumberedsubsubsec Specifying the Object Directory
12033
12034 @noindent
12035 Several project properties are modeled by Ada-style @emph{attributes};
12036 a property is defined by supplying the equivalent of an Ada attribute
12037 definition clause in the project file.
12038 A project's object directory is another such a property; the corresponding
12039 attribute is @code{Object_Dir}, and its value is also a string expression,
12040 specified either as absolute or relative. In the later case,
12041 it is relative to the project file directory. Thus the compiler's
12042 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12043 (for the @code{Debug} project)
12044 and to @file{^/common/release^[COMMON.RELEASE]^}
12045 (for the @code{Release} project).
12046 If @code{Object_Dir} is not specified, then the default is the project file
12047 directory itself.
12048
12049 @node Specifying the Exec Directory
12050 @unnumberedsubsubsec Specifying the Exec Directory
12051
12052 @noindent
12053 A project's exec directory is another property; the corresponding
12054 attribute is @code{Exec_Dir}, and its value is also a string expression,
12055 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12056 then the default is the object directory (which may also be the project file
12057 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12058 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12059 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12060 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12061
12062 @node Project File Packages
12063 @unnumberedsubsubsec Project File Packages
12064
12065 @noindent
12066 A GNAT tool that is integrated with the Project Manager is modeled by a
12067 corresponding package in the project file. In the example above,
12068 The @code{Debug} project defines the packages @code{Builder}
12069 (for @command{gnatmake}) and @code{Compiler};
12070 the @code{Release} project defines only the @code{Compiler} package.
12071
12072 The Ada-like package syntax is not to be taken literally.  Although packages in
12073 project files bear a surface resemblance to packages in Ada source code, the
12074 notation is simply a way to convey a grouping of properties for a named
12075 entity.  Indeed, the package names permitted in project files are restricted
12076 to a predefined set, corresponding to the project-aware tools, and the contents
12077 of packages are limited to a small set of constructs.
12078 The packages in the example above contain attribute definitions.
12079
12080 @node Specifying ^Switch^Switch^ Settings
12081 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12082
12083 @noindent
12084 ^Switch^Switch^ settings for a project-aware tool can be specified through
12085 attributes in the package that corresponds to the tool.
12086 The example above illustrates one of the relevant attributes,
12087 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12088 in both project files.
12089 Unlike simple attributes like @code{Source_Dirs},
12090 @code{^Default_Switches^Default_Switches^} is
12091 known as an @emph{associative array}.  When you define this attribute, you must
12092 supply an ``index'' (a literal string), and the effect of the attribute
12093 definition is to set the value of the array at the specified index.
12094 For the @code{^Default_Switches^Default_Switches^} attribute,
12095 the index is a programming language (in our case, Ada),
12096 and the value specified (after @code{use}) must be a list
12097 of string expressions.
12098
12099 The attributes permitted in project files are restricted to a predefined set.
12100 Some may appear at project level, others in packages.
12101 For any attribute that is an associative array, the index must always be a
12102 literal string, but the restrictions on this string (e.g., a file name or a
12103 language name) depend on the individual attribute.
12104 Also depending on the attribute, its specified value will need to be either a
12105 string or a string list.
12106
12107 In the @code{Debug} project, we set the switches for two tools,
12108 @command{gnatmake} and the compiler, and thus we include the two corresponding
12109 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12110 attribute with index @code{"Ada"}.
12111 Note that the package corresponding to
12112 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12113 similar, but only includes the @code{Compiler} package.
12114
12115 In project @code{Debug} above, the ^switches^switches^ starting with
12116 @option{-gnat} that are specified in package @code{Compiler}
12117 could have been placed in package @code{Builder}, since @command{gnatmake}
12118 transmits all such ^switches^switches^ to the compiler.
12119
12120 @node Main Subprograms
12121 @unnumberedsubsubsec Main Subprograms
12122
12123 @noindent
12124 One of the specifiable properties of a project is a list of files that contain
12125 main subprograms.  This property is captured in the @code{Main} attribute,
12126 whose value is a list of strings.  If a project defines the @code{Main}
12127 attribute, it is not necessary to identify the main subprogram(s) when
12128 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12129
12130 @node Executable File Names
12131 @unnumberedsubsubsec Executable File Names
12132
12133 @noindent
12134 By default, the executable file name corresponding to a main source is
12135 deduced from the main source file name. Through the attributes
12136 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12137 it is possible to change this default.
12138 In project @code{Debug} above, the executable file name
12139 for main source @file{^proc.adb^PROC.ADB^} is
12140 @file{^proc1^PROC1.EXE^}.
12141 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12142 of the executable files, when no attribute @code{Executable} applies:
12143 its value replace the platform-specific executable suffix.
12144 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12145 specify a non-default executable file name when several mains are built at once
12146 in a single @command{gnatmake} command.
12147
12148 @node Source File Naming Conventions
12149 @unnumberedsubsubsec Source File Naming Conventions
12150
12151 @noindent
12152 Since the project files above do not specify any source file naming
12153 conventions, the GNAT defaults are used.  The mechanism for defining source
12154 file naming conventions -- a package named @code{Naming} --
12155 is described below (@pxref{Naming Schemes}).
12156
12157 @node Source Language(s)
12158 @unnumberedsubsubsec Source Language(s)
12159
12160 @noindent
12161 Since the project files do not specify a @code{Languages} attribute, by
12162 default the GNAT tools assume that the language of the project file is Ada.
12163 More generally, a project can comprise source files
12164 in Ada, C, and/or other languages.
12165
12166 @node Using External Variables
12167 @subsection Using External Variables
12168
12169 @noindent
12170 Instead of supplying different project files for debug and release, we can
12171 define a single project file that queries an external variable (set either
12172 on the command line or via an ^environment variable^logical name^) in order to
12173 conditionally define the appropriate settings.  Again, assume that the
12174 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12175 located in directory @file{^/common^[COMMON]^}.  The following project file,
12176 @file{build.gpr}, queries the external variable named @code{STYLE} and
12177 defines an object directory and ^switch^switch^ settings based on whether
12178 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12179 the default is @code{"deb"}.
12180
12181 @smallexample @c projectfile
12182 @group
12183 project Build is
12184   for Main use ("proc");
12185
12186   type Style_Type is ("deb", "rel");
12187   Style : Style_Type := external ("STYLE", "deb");
12188
12189   case Style is
12190     when "deb" =>
12191       for Object_Dir use "debug";
12192
12193     when "rel" =>
12194       for Object_Dir use "release";
12195       for Exec_Dir use ".";
12196   end case;
12197 @end group
12198
12199 @group
12200   package Builder is
12201
12202     case Style is
12203       when "deb" =>
12204         for ^Default_Switches^Default_Switches^ ("Ada")
12205             use ("^-g^-g^");
12206         for Executable ("proc") use "proc1";
12207       when others =>
12208         null;
12209     end case;
12210
12211   end Builder;
12212 @end group
12213
12214 @group
12215   package Compiler is
12216
12217     case Style is
12218       when "deb" =>
12219         for ^Default_Switches^Default_Switches^ ("Ada")
12220             use ("^-gnata^-gnata^",
12221                  "^-gnato^-gnato^",
12222                  "^-gnatE^-gnatE^");
12223
12224       when "rel" =>
12225         for ^Default_Switches^Default_Switches^ ("Ada")
12226             use ("^-O2^-O2^");
12227     end case;
12228
12229   end Compiler;
12230
12231 end Build;
12232 @end group
12233 @end smallexample
12234
12235 @noindent
12236 @code{Style_Type} is an example of a @emph{string type}, which is the project
12237 file analog of an Ada enumeration type but whose components are string literals
12238 rather than identifiers.  @code{Style} is declared as a variable of this type.
12239
12240 The form @code{external("STYLE", "deb")} is known as an
12241 @emph{external reference}; its first argument is the name of an
12242 @emph{external variable}, and the second argument is a default value to be
12243 used if the external variable doesn't exist.  You can define an external
12244 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12245 or you can use ^an environment variable^a logical name^
12246 as an external variable.
12247
12248 Each @code{case} construct is expanded by the Project Manager based on the
12249 value of @code{Style}. Thus the command
12250 @ifclear vms
12251 @smallexample
12252 gnatmake -P/common/build.gpr -XSTYLE=deb
12253 @end smallexample
12254 @end ifclear
12255
12256 @ifset vms
12257 @smallexample
12258 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12259 @end smallexample
12260 @end ifset
12261
12262 @noindent
12263 is equivalent to the @command{gnatmake} invocation using the project file
12264 @file{debug.gpr} in the earlier example.  So is the command
12265 @smallexample
12266 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12267 @end smallexample
12268
12269 @noindent
12270 since @code{"deb"} is the default for @code{STYLE}.
12271
12272 Analogously,
12273
12274 @ifclear vms
12275 @smallexample
12276 gnatmake -P/common/build.gpr -XSTYLE=rel
12277 @end smallexample
12278 @end ifclear
12279
12280 @ifset vms
12281 @smallexample
12282 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12283 @end smallexample
12284 @end ifset
12285
12286 @noindent
12287 is equivalent to the @command{gnatmake} invocation using the project file
12288 @file{release.gpr} in the earlier example.
12289
12290 @node Importing Other Projects
12291 @subsection Importing Other Projects
12292 @cindex @code{ADA_PROJECT_PATH}
12293 @cindex @code{GPR_PROJECT_PATH}
12294
12295 @noindent
12296 A compilation unit in a source file in one project may depend on compilation
12297 units in source files in other projects.  To compile this unit under
12298 control of a project file, the
12299 dependent project must @emph{import} the projects containing the needed source
12300 files.
12301 This effect is obtained using syntax similar to an Ada @code{with} clause,
12302 but where @code{with}ed entities are strings that denote project files.
12303
12304 As an example, suppose that the two projects @code{GUI_Proj} and
12305 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12306 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12307 and @file{^/comm^[COMM]^}, respectively.
12308 Suppose that the source files for @code{GUI_Proj} are
12309 @file{gui.ads} and @file{gui.adb}, and that the source files for
12310 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12311 files is located in its respective project file directory.  Schematically:
12312
12313 @smallexample
12314 @group
12315 ^/gui^[GUI]^
12316   gui_proj.gpr
12317   gui.ads
12318   gui.adb
12319 @end group
12320
12321 @group
12322 ^/comm^[COMM]^
12323   comm_proj.gpr
12324   comm.ads
12325   comm.adb
12326 @end group
12327 @end smallexample
12328
12329 @noindent
12330 We want to develop an application in directory @file{^/app^[APP]^} that
12331 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12332 the corresponding project files (e.g.@: the ^switch^switch^ settings
12333 and object directory).
12334 Skeletal code for a main procedure might be something like the following:
12335
12336 @smallexample @c ada
12337 @group
12338 with GUI, Comm;
12339 procedure App_Main is
12340    @dots{}
12341 begin
12342    @dots{}
12343 end App_Main;
12344 @end group
12345 @end smallexample
12346
12347 @noindent
12348 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12349 effect:
12350
12351 @smallexample @c projectfile
12352 @group
12353 with "/gui/gui_proj", "/comm/comm_proj";
12354 project App_Proj is
12355    for Main use ("app_main");
12356 end App_Proj;
12357 @end group
12358 @end smallexample
12359
12360 @noindent
12361 Building an executable is achieved through the command:
12362 @smallexample
12363 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12364 @end smallexample
12365 @noindent
12366 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12367 in the directory where @file{app_proj.gpr} resides.
12368
12369 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12370 (as illustrated above) the @code{with} clause can omit the extension.
12371
12372 Our example specified an absolute path for each imported project file.
12373 Alternatively, the directory name of an imported object can be omitted
12374 if either
12375 @itemize @bullet
12376 @item
12377 The imported project file is in the same directory as the importing project
12378 file, or
12379 @item
12380 You have defined one or two ^environment variables^logical names^
12381 that includes the directory containing
12382 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12383 @code{ADA_PROJECT_PATH} is the same as
12384 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12385 directory names separated by colons (semicolons on Windows).
12386 @end itemize
12387
12388 @noindent
12389 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12390 to include @file{^/gui^[GUI]^} and
12391 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12392 as follows:
12393
12394 @smallexample @c projectfile
12395 @group
12396 with "gui_proj", "comm_proj";
12397 project App_Proj is
12398    for Main use ("app_main");
12399 end App_Proj;
12400 @end group
12401 @end smallexample
12402
12403 @noindent
12404 Importing other projects can create ambiguities.
12405 For example, the same unit might be present in different imported projects, or
12406 it might be present in both the importing project and in an imported project.
12407 Both of these conditions are errors.  Note that in the current version of
12408 the Project Manager, it is illegal to have an ambiguous unit even if the
12409 unit is never referenced by the importing project.  This restriction may be
12410 relaxed in a future release.
12411
12412 @node Extending a Project
12413 @subsection Extending a Project
12414
12415 @noindent
12416 In large software systems it is common to have multiple
12417 implementations of a common interface; in Ada terms, multiple versions of a
12418 package body for the same spec.  For example, one implementation
12419 might be safe for use in tasking programs, while another might only be used
12420 in sequential applications.  This can be modeled in GNAT using the concept
12421 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12422 another project (the ``parent'') then by default all source files of the
12423 parent project are inherited by the child, but the child project can
12424 override any of the parent's source files with new versions, and can also
12425 add new files.  This facility is the project analog of a type extension in
12426 Object-Oriented Programming.  Project hierarchies are permitted (a child
12427 project may be the parent of yet another project), and a project that
12428 inherits one project can also import other projects.
12429
12430 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12431 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12432 @file{pack.adb}, and @file{proc.adb}:
12433
12434 @smallexample
12435 @group
12436 ^/seq^[SEQ]^
12437   pack.ads
12438   pack.adb
12439   proc.adb
12440   seq_proj.gpr
12441 @end group
12442 @end smallexample
12443
12444 @noindent
12445 Note that the project file can simply be empty (that is, no attribute or
12446 package is defined):
12447
12448 @smallexample @c projectfile
12449 @group
12450 project Seq_Proj is
12451 end Seq_Proj;
12452 @end group
12453 @end smallexample
12454
12455 @noindent
12456 implying that its source files are all the Ada source files in the project
12457 directory.
12458
12459 Suppose we want to supply an alternate version of @file{pack.adb}, in
12460 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12461 @file{pack.ads} and @file{proc.adb}.  We can define a project
12462 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12463
12464 @smallexample
12465 @group
12466 ^/tasking^[TASKING]^
12467   pack.adb
12468   tasking_proj.gpr
12469 @end group
12470
12471 @group
12472 project Tasking_Proj extends "/seq/seq_proj" is
12473 end Tasking_Proj;
12474 @end group
12475 @end smallexample
12476
12477 @noindent
12478 The version of @file{pack.adb} used in a build depends on which project file
12479 is specified.
12480
12481 Note that we could have obtained the desired behavior using project import
12482 rather than project inheritance; a @code{base} project would contain the
12483 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12484 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12485 would import @code{base} and add a different version of @file{pack.adb}.  The
12486 choice depends on whether other sources in the original project need to be
12487 overridden.  If they do, then project extension is necessary, otherwise,
12488 importing is sufficient.
12489
12490 @noindent
12491 In a project file that extends another project file, it is possible to
12492 indicate that an inherited source is not part of the sources of the extending
12493 project. This is necessary sometimes when a package spec has been overloaded
12494 and no longer requires a body: in this case, it is necessary to indicate that
12495 the inherited body is not part of the sources of the project, otherwise there
12496 will be a compilation error when compiling the spec.
12497
12498 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12499 Its value is a string list: a list of file names. It is also possible to use
12500 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12501 the file name of a text file containing a list of file names, one per line.
12502
12503 @smallexample @c @projectfile
12504 project B extends "a" is
12505    for Source_Files use ("pkg.ads");
12506    --  New spec of Pkg does not need a completion
12507    for Excluded_Source_Files use ("pkg.adb");
12508 end B;
12509 @end smallexample
12510
12511 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12512 is still needed: if it is possible to build using @command{gnatmake} when such
12513 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12514 it is possible to remove the source completely from a system that includes
12515 project P.
12516
12517 @c ***********************
12518 @c * Project File Syntax *
12519 @c ***********************
12520
12521 @node Project File Syntax
12522 @section Project File Syntax
12523
12524 @menu
12525 * Basic Syntax::
12526 * Qualified Projects::
12527 * Packages::
12528 * Expressions::
12529 * String Types::
12530 * Variables::
12531 * Attributes::
12532 * Associative Array Attributes::
12533 * case Constructions::
12534 @end menu
12535
12536 @noindent
12537 This section describes the structure of project files.
12538
12539 A project may be an @emph{independent project}, entirely defined by a single
12540 project file. Any Ada source file in an independent project depends only
12541 on the predefined library and other Ada source files in the same project.
12542
12543 @noindent
12544 A project may also @dfn{depend on} other projects, in either or both of
12545 the following ways:
12546 @itemize @bullet
12547 @item It may import any number of projects
12548 @item It may extend at most one other project
12549 @end itemize
12550
12551 @noindent
12552 The dependence relation is a directed acyclic graph (the subgraph reflecting
12553 the ``extends'' relation is a tree).
12554
12555 A project's @dfn{immediate sources} are the source files directly defined by
12556 that project, either implicitly by residing in the project file's directory,
12557 or explicitly through any of the source-related attributes described below.
12558 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12559 of @var{proj} together with the immediate sources (unless overridden) of any
12560 project on which @var{proj} depends (either directly or indirectly).
12561
12562 @node Basic Syntax
12563 @subsection Basic Syntax
12564
12565 @noindent
12566 As seen in the earlier examples, project files have an Ada-like syntax.
12567 The minimal project file is:
12568 @smallexample @c projectfile
12569 @group
12570 project Empty is
12571
12572 end Empty;
12573 @end group
12574 @end smallexample
12575
12576 @noindent
12577 The identifier @code{Empty} is the name of the project.
12578 This project name must be present after the reserved
12579 word @code{end} at the end of the project file, followed by a semi-colon.
12580
12581 Any name in a project file, such as the project name or a variable name,
12582 has the same syntax as an Ada identifier.
12583
12584 The reserved words of project files are the Ada 95 reserved words plus
12585 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12586 reserved words currently used in project file syntax are:
12587
12588 @itemize @bullet
12589 @item
12590 @code{all}
12591 @item
12592 @code{at}
12593 @item
12594 @code{case}
12595 @item
12596 @code{end}
12597 @item
12598 @code{for}
12599 @item
12600 @code{is}
12601 @item
12602 @code{limited}
12603 @item
12604 @code{null}
12605 @item
12606 @code{others}
12607 @item
12608 @code{package}
12609 @item
12610 @code{renames}
12611 @item
12612 @code{type}
12613 @item
12614 @code{use}
12615 @item
12616 @code{when}
12617 @item
12618 @code{with}
12619 @end itemize
12620
12621 @noindent
12622 Comments in project files have the same syntax as in Ada, two consecutive
12623 hyphens through the end of the line.
12624
12625 @node Qualified Projects
12626 @subsection Qualified Projects
12627
12628 @noindent
12629 Before the reserved @code{project}, there may be one or two "qualifiers", that
12630 is identifiers or other reserved words, to qualify the project.
12631
12632 The current list of qualifiers is:
12633
12634 @itemize @bullet
12635 @item
12636 @code{abstract}: qualify a project with no sources. A qualified abstract
12637 project must either have no declaration of attributes @code{Source_Dirs},
12638 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12639 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12640 as empty. If it extends another project, the project it extends must also be a
12641 qualified abstract project.
12642
12643 @item
12644 @code{standard}: a standard project is a non library project with sources.
12645
12646 @item
12647 @code{aggregate}: for future extension
12648
12649 @item
12650 @code{aggregate library}: for future extension
12651
12652 @item
12653 @code{library}: a library project must declare both attributes
12654 @code{Library_Name} and @code{Library_Dir}.
12655
12656 @item
12657 @code{configuration}: a configuration project cannot be in a project tree.
12658 @end itemize
12659
12660 @node Packages
12661 @subsection Packages
12662
12663 @noindent
12664 A project file may contain @emph{packages}. The name of a package must be one
12665 of the identifiers from the following list. A package
12666 with a given name may only appear once in a project file. Package names are
12667 case insensitive. The following package names are legal:
12668
12669 @itemize @bullet
12670 @item
12671 @code{Naming}
12672 @item
12673 @code{Builder}
12674 @item
12675 @code{Compiler}
12676 @item
12677 @code{Binder}
12678 @item
12679 @code{Linker}
12680 @item
12681 @code{Finder}
12682 @item
12683 @code{Cross_Reference}
12684 @item
12685 @code{Eliminate}
12686 @item
12687 @code{Pretty_Printer}
12688 @item
12689 @code{Metrics}
12690 @item
12691 @code{gnatls}
12692 @item
12693 @code{gnatstub}
12694 @item
12695 @code{IDE}
12696 @item
12697 @code{Language_Processing}
12698 @end itemize
12699
12700 @noindent
12701 In its simplest form, a package may be empty:
12702
12703 @smallexample @c projectfile
12704 @group
12705 project Simple is
12706   package Builder is
12707   end Builder;
12708 end Simple;
12709 @end group
12710 @end smallexample
12711
12712 @noindent
12713 A package may contain @emph{attribute declarations},
12714 @emph{variable declarations} and @emph{case constructions}, as will be
12715 described below.
12716
12717 When there is ambiguity between a project name and a package name,
12718 the name always designates the project. To avoid possible confusion, it is
12719 always a good idea to avoid naming a project with one of the
12720 names allowed for packages or any name that starts with @code{gnat}.
12721
12722 @node Expressions
12723 @subsection Expressions
12724
12725 @noindent
12726 An @emph{expression} is either a @emph{string expression} or a
12727 @emph{string list expression}.
12728
12729 A @emph{string expression} is either a @emph{simple string expression} or a
12730 @emph{compound string expression}.
12731
12732 A @emph{simple string expression} is one of the following:
12733 @itemize @bullet
12734 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12735 @item A string-valued variable reference (@pxref{Variables})
12736 @item A string-valued attribute reference (@pxref{Attributes})
12737 @item An external reference (@pxref{External References in Project Files})
12738 @end itemize
12739
12740 @noindent
12741 A @emph{compound string expression} is a concatenation of string expressions,
12742 using the operator @code{"&"}
12743 @smallexample
12744        Path & "/" & File_Name & ".ads"
12745 @end smallexample
12746
12747 @noindent
12748 A @emph{string list expression} is either a
12749 @emph{simple string list expression} or a
12750 @emph{compound string list expression}.
12751
12752 A @emph{simple string list expression} is one of the following:
12753 @itemize @bullet
12754 @item A parenthesized list of zero or more string expressions,
12755 separated by commas
12756 @smallexample
12757    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12758    Empty_List := ();
12759 @end smallexample
12760 @item A string list-valued variable reference
12761 @item A string list-valued attribute reference
12762 @end itemize
12763
12764 @noindent
12765 A @emph{compound string list expression} is the concatenation (using
12766 @code{"&"}) of a simple string list expression and an expression.  Note that
12767 each term in a compound string list expression, except the first, may be
12768 either a string expression or a string list expression.
12769
12770 @smallexample @c projectfile
12771 @group
12772    File_Name_List := () & File_Name; --  One string in this list
12773    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12774    --  Two strings
12775    Big_List := File_Name_List & Extended_File_Name_List;
12776    --  Concatenation of two string lists: three strings
12777    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12778    --  Illegal: must start with a string list
12779 @end group
12780 @end smallexample
12781
12782 @node String Types
12783 @subsection String Types
12784
12785 @noindent
12786 A @emph{string type declaration} introduces a discrete set of string literals.
12787 If a string variable is declared to have this type, its value
12788 is restricted to the given set of literals.
12789
12790 Here is an example of a string type declaration:
12791
12792 @smallexample @c projectfile
12793    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12794 @end smallexample
12795
12796 @noindent
12797 Variables of a string type are called @emph{typed variables}; all other
12798 variables are called @emph{untyped variables}. Typed variables are
12799 particularly useful in @code{case} constructions, to support conditional
12800 attribute declarations.
12801 (@pxref{case Constructions}).
12802
12803 The string literals in the list are case sensitive and must all be different.
12804 They may include any graphic characters allowed in Ada, including spaces.
12805
12806 A string type may only be declared at the project level, not inside a package.
12807
12808 A string type may be referenced by its name if it has been declared in the same
12809 project file, or by an expanded name whose prefix is the name of the project
12810 in which it is declared.
12811
12812 @node Variables
12813 @subsection Variables
12814
12815 @noindent
12816 A variable may be declared at the project file level, or within a package.
12817 Here are some examples of variable declarations:
12818
12819 @smallexample @c projectfile
12820 @group
12821    This_OS : OS := external ("OS"); --  a typed variable declaration
12822    That_OS := "GNU/Linux";          --  an untyped variable declaration
12823 @end group
12824 @end smallexample
12825
12826 @noindent
12827 The syntax of a @emph{typed variable declaration} is identical to the Ada
12828 syntax for an object declaration. By contrast, the syntax of an untyped
12829 variable declaration is identical to an Ada assignment statement. In fact,
12830 variable declarations in project files have some of the characteristics of
12831 an assignment, in that successive declarations for the same variable are
12832 allowed. Untyped variable declarations do establish the expected kind of the
12833 variable (string or string list), and successive declarations for it must
12834 respect the initial kind.
12835
12836 @noindent
12837 A string variable declaration (typed or untyped) declares a variable
12838 whose value is a string. This variable may be used as a string expression.
12839 @smallexample @c projectfile
12840    File_Name       := "readme.txt";
12841    Saved_File_Name := File_Name & ".saved";
12842 @end smallexample
12843
12844 @noindent
12845 A string list variable declaration declares a variable whose value is a list
12846 of strings. The list may contain any number (zero or more) of strings.
12847
12848 @smallexample @c projectfile
12849    Empty_List := ();
12850    List_With_One_Element := ("^-gnaty^-gnaty^");
12851    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12852    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12853                  "pack2.ada", "util_.ada", "util.ada");
12854 @end smallexample
12855
12856 @noindent
12857 The same typed variable may not be declared more than once at project level,
12858 and it may not be declared more than once in any package; it is in effect
12859 a constant.
12860
12861 The same untyped variable may be declared several times. Declarations are
12862 elaborated in the order in which they appear, so  the new value replaces
12863 the old one, and any subsequent reference to the variable uses the new value.
12864 However, as noted above, if a variable has been declared as a string, all
12865 subsequent
12866 declarations must give it a string value. Similarly, if a variable has
12867 been declared as a string list, all subsequent declarations
12868 must give it a string list value.
12869
12870 A @emph{variable reference} may take several forms:
12871
12872 @itemize @bullet
12873 @item The simple variable name, for a variable in the current package (if any)
12874 or in the current project
12875 @item An expanded name, whose prefix is a context name.
12876 @end itemize
12877
12878 @noindent
12879 A @emph{context} may be one of the following:
12880
12881 @itemize @bullet
12882 @item The name of an existing package in the current project
12883 @item The name of an imported project of the current project
12884 @item The name of an ancestor project (i.e., a project extended by the current
12885 project, either directly or indirectly)
12886 @item An expanded name whose prefix is an imported/parent project name, and
12887 whose selector is a package name in that project.
12888 @end itemize
12889
12890 @noindent
12891 A variable reference may be used in an expression.
12892
12893 @node Attributes
12894 @subsection Attributes
12895
12896 @noindent
12897 A project (and its packages) may have @emph{attributes} that define
12898 the project's properties.  Some attributes have values that are strings;
12899 others have values that are string lists.
12900
12901 There are two categories of attributes: @emph{simple attributes}
12902 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12903
12904 Legal project attribute names, and attribute names for each legal package are
12905 listed below. Attributes names are case-insensitive.
12906
12907 The following attributes are defined on projects (all are simple attributes):
12908
12909 @multitable @columnfractions .4 .3
12910 @item @emph{Attribute Name}
12911 @tab @emph{Value}
12912 @item @code{Source_Files}
12913 @tab string list
12914 @item @code{Source_Dirs}
12915 @tab string list
12916 @item @code{Source_List_File}
12917 @tab string
12918 @item @code{Object_Dir}
12919 @tab string
12920 @item @code{Exec_Dir}
12921 @tab string
12922 @item @code{Excluded_Source_Dirs}
12923 @tab string list
12924 @item @code{Excluded_Source_Files}
12925 @tab string list
12926 @item @code{Excluded_Source_List_File}
12927 @tab string
12928 @item @code{Languages}
12929 @tab string list
12930 @item @code{Main}
12931 @tab string list
12932 @item @code{Library_Dir}
12933 @tab string
12934 @item @code{Library_Name}
12935 @tab string
12936 @item @code{Library_Kind}
12937 @tab string
12938 @item @code{Library_Version}
12939 @tab string
12940 @item @code{Library_Interface}
12941 @tab string
12942 @item @code{Library_Auto_Init}
12943 @tab string
12944 @item @code{Library_Options}
12945 @tab string list
12946 @item @code{Library_Src_Dir}
12947 @tab string
12948 @item @code{Library_ALI_Dir}
12949 @tab string
12950 @item @code{Library_GCC}
12951 @tab string
12952 @item @code{Library_Symbol_File}
12953 @tab string
12954 @item @code{Library_Symbol_Policy}
12955 @tab string
12956 @item @code{Library_Reference_Symbol_File}
12957 @tab string
12958 @item @code{Externally_Built}
12959 @tab string
12960 @end multitable
12961
12962 @noindent
12963 The following attributes are defined for package  @code{Naming}
12964 (@pxref{Naming Schemes}):
12965
12966 @multitable @columnfractions .4 .2 .2 .2
12967 @item Attribute Name @tab Category @tab Index @tab Value
12968 @item @code{Spec_Suffix}
12969 @tab associative array
12970 @tab language name
12971 @tab string
12972 @item @code{Body_Suffix}
12973 @tab associative array
12974 @tab language name
12975 @tab string
12976 @item @code{Separate_Suffix}
12977 @tab simple attribute
12978 @tab n/a
12979 @tab string
12980 @item @code{Casing}
12981 @tab simple attribute
12982 @tab n/a
12983 @tab string
12984 @item @code{Dot_Replacement}
12985 @tab simple attribute
12986 @tab n/a
12987 @tab string
12988 @item @code{Spec}
12989 @tab associative array
12990 @tab Ada unit name
12991 @tab string
12992 @item @code{Body}
12993 @tab associative array
12994 @tab Ada unit name
12995 @tab string
12996 @item @code{Specification_Exceptions}
12997 @tab associative array
12998 @tab language name
12999 @tab string list
13000 @item @code{Implementation_Exceptions}
13001 @tab associative array
13002 @tab language name
13003 @tab string list
13004 @end multitable
13005
13006 @noindent
13007 The following attributes are defined for packages @code{Builder},
13008 @code{Compiler}, @code{Binder},
13009 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13010 (@pxref{^Switches^Switches^ and Project Files}).
13011
13012 @multitable @columnfractions .4 .2 .2 .2
13013 @item Attribute Name @tab Category @tab Index @tab Value
13014 @item @code{^Default_Switches^Default_Switches^}
13015 @tab associative array
13016 @tab language name
13017 @tab string list
13018 @item @code{^Switches^Switches^}
13019 @tab associative array
13020 @tab file name
13021 @tab string list
13022 @end multitable
13023
13024 @noindent
13025 In addition, package @code{Compiler} has a single string attribute
13026 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13027 string attribute @code{Global_Configuration_Pragmas}.
13028
13029 @noindent
13030 Each simple attribute has a default value: the empty string (for string-valued
13031 attributes) and the empty list (for string list-valued attributes).
13032
13033 An attribute declaration defines a new value for an attribute.
13034
13035 Examples of simple attribute declarations:
13036
13037 @smallexample @c projectfile
13038    for Object_Dir use "objects";
13039    for Source_Dirs use ("units", "test/drivers");
13040 @end smallexample
13041
13042 @noindent
13043 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13044 attribute definition clause in Ada.
13045
13046 Attributes references may be appear in expressions.
13047 The general form for such a reference is @code{<entity>'<attribute>}:
13048 Associative array attributes are functions. Associative
13049 array attribute references must have an argument that is a string literal.
13050
13051 Examples are:
13052
13053 @smallexample @c projectfile
13054   project'Object_Dir
13055   Naming'Dot_Replacement
13056   Imported_Project'Source_Dirs
13057   Imported_Project.Naming'Casing
13058   Builder'^Default_Switches^Default_Switches^("Ada")
13059 @end smallexample
13060
13061 @noindent
13062 The prefix of an attribute may be:
13063 @itemize @bullet
13064 @item @code{project} for an attribute of the current project
13065 @item The name of an existing package of the current project
13066 @item The name of an imported project
13067 @item The name of a parent project that is extended by the current project
13068 @item An expanded name whose prefix is imported/parent project name,
13069 and whose selector is a package name
13070 @end itemize
13071
13072 @noindent
13073 Example:
13074 @smallexample @c projectfile
13075 @group
13076    project Prj is
13077      for Source_Dirs use project'Source_Dirs & "units";
13078      for Source_Dirs use project'Source_Dirs & "test/drivers"
13079    end Prj;
13080 @end group
13081 @end smallexample
13082
13083 @noindent
13084 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13085 has the default value: an empty string list. After this declaration,
13086 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13087 After the second attribute declaration @code{Source_Dirs} is a string list of
13088 two elements: @code{"units"} and @code{"test/drivers"}.
13089
13090 Note: this example is for illustration only. In practice,
13091 the project file would contain only one attribute declaration:
13092
13093 @smallexample @c projectfile
13094    for Source_Dirs use ("units", "test/drivers");
13095 @end smallexample
13096
13097 @node Associative Array Attributes
13098 @subsection Associative Array Attributes
13099
13100 @noindent
13101 Some attributes are defined as @emph{associative arrays}. An associative
13102 array may be regarded as a function that takes a string as a parameter
13103 and delivers a string or string list value as its result.
13104
13105 Here are some examples of single associative array attribute associations:
13106
13107 @smallexample @c projectfile
13108    for Body ("main") use "Main.ada";
13109    for ^Switches^Switches^ ("main.ada")
13110        use ("^-v^-v^",
13111             "^-gnatv^-gnatv^");
13112    for ^Switches^Switches^ ("main.ada")
13113             use Builder'^Switches^Switches^ ("main.ada")
13114               & "^-g^-g^";
13115 @end smallexample
13116
13117 @noindent
13118 Like untyped variables and simple attributes, associative array attributes
13119 may be declared several times. Each declaration supplies a new value for the
13120 attribute, and replaces the previous setting.
13121
13122 @noindent
13123 An associative array attribute may be declared as a full associative array
13124 declaration, with the value of the same attribute in an imported or extended
13125 project.
13126
13127 @smallexample @c projectfile
13128    package Builder is
13129       for Default_Switches use Default.Builder'Default_Switches;
13130    end Builder;
13131 @end smallexample
13132
13133 @noindent
13134 In this example, @code{Default} must be either a project imported by the
13135 current project, or the project that the current project extends. If the
13136 attribute is in a package (in this case, in package @code{Builder}), the same
13137 package needs to be specified.
13138
13139 @noindent
13140 A full associative array declaration replaces any other declaration for the
13141 attribute, including other full associative array declaration. Single
13142 associative array associations may be declare after a full associative
13143 declaration, modifying the value for a single association of the attribute.
13144
13145 @node case Constructions
13146 @subsection @code{case} Constructions
13147
13148 @noindent
13149 A @code{case} construction is used in a project file to effect conditional
13150 behavior.
13151 Here is a typical example:
13152
13153 @smallexample @c projectfile
13154 @group
13155 project MyProj is
13156    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13157
13158    OS : OS_Type := external ("OS", "GNU/Linux");
13159 @end group
13160
13161 @group
13162    package Compiler is
13163      case OS is
13164        when "GNU/Linux" | "Unix" =>
13165          for ^Default_Switches^Default_Switches^ ("Ada")
13166              use ("^-gnath^-gnath^");
13167        when "NT" =>
13168          for ^Default_Switches^Default_Switches^ ("Ada")
13169              use ("^-gnatP^-gnatP^");
13170        when others =>
13171      end case;
13172    end Compiler;
13173 end MyProj;
13174 @end group
13175 @end smallexample
13176
13177 @noindent
13178 The syntax of a @code{case} construction is based on the Ada case statement
13179 (although there is no @code{null} construction for empty alternatives).
13180
13181 The case expression must be a typed string variable.
13182 Each alternative comprises the reserved word @code{when}, either a list of
13183 literal strings separated by the @code{"|"} character or the reserved word
13184 @code{others},  and the @code{"=>"} token.
13185 Each literal string must belong to the string type that is the type of the
13186 case variable.
13187 An @code{others} alternative, if present, must occur last.
13188
13189 After each @code{=>}, there are zero or more constructions.  The only
13190 constructions allowed in a case construction are other case constructions,
13191 attribute declarations and variable declarations. String type declarations and
13192 package declarations are not allowed. Variable declarations are restricted to
13193 variables that have already been declared before the case construction.
13194
13195 The value of the case variable is often given by an external reference
13196 (@pxref{External References in Project Files}).
13197
13198 @c ****************************************
13199 @c * Objects and Sources in Project Files *
13200 @c ****************************************
13201
13202 @node Objects and Sources in Project Files
13203 @section Objects and Sources in Project Files
13204
13205 @menu
13206 * Object Directory::
13207 * Exec Directory::
13208 * Source Directories::
13209 * Source File Names::
13210 @end menu
13211
13212 @noindent
13213 Each project has exactly one object directory and one or more source
13214 directories. The source directories must contain at least one source file,
13215 unless  the project file explicitly specifies that no source files are present
13216 (@pxref{Source File Names}).
13217
13218 @node Object Directory
13219 @subsection Object Directory
13220
13221 @noindent
13222 The object directory for a project is the directory containing the compiler's
13223 output (such as @file{ALI} files and object files) for the project's immediate
13224 sources.
13225
13226 The object directory is given by the value of the attribute @code{Object_Dir}
13227 in the project file.
13228
13229 @smallexample @c projectfile
13230    for Object_Dir use "objects";
13231 @end smallexample
13232
13233 @noindent
13234 The attribute @code{Object_Dir} has a string value, the path name of the object
13235 directory. The path name may be absolute or relative to the directory of the
13236 project file. This directory must already exist, and be readable and writable.
13237
13238 By default, when the attribute @code{Object_Dir} is not given an explicit value
13239 or when its value is the empty string, the object directory is the same as the
13240 directory containing the project file.
13241
13242 @node Exec Directory
13243 @subsection Exec Directory
13244
13245 @noindent
13246 The exec directory for a project is the directory containing the executables
13247 for the project's main subprograms.
13248
13249 The exec directory is given by the value of the attribute @code{Exec_Dir}
13250 in the project file.
13251
13252 @smallexample @c projectfile
13253    for Exec_Dir use "executables";
13254 @end smallexample
13255
13256 @noindent
13257 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13258 directory. The path name may be absolute or relative to the directory of the
13259 project file. This directory must already exist, and be writable.
13260
13261 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13262 or when its value is the empty string, the exec directory is the same as the
13263 object directory of the project file.
13264
13265 @node Source Directories
13266 @subsection Source Directories
13267
13268 @noindent
13269 The source directories of a project are specified by the project file
13270 attribute @code{Source_Dirs}.
13271
13272 This attribute's value is a string list. If the attribute is not given an
13273 explicit value, then there is only one source directory, the one where the
13274 project file resides.
13275
13276 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13277 as in
13278
13279 @smallexample @c projectfile
13280     for Source_Dirs use ();
13281 @end smallexample
13282
13283 @noindent
13284 indicates that the project contains no source files.
13285
13286 Otherwise, each string in the string list designates one or more
13287 source directories.
13288
13289 @smallexample @c projectfile
13290    for Source_Dirs use ("sources", "test/drivers");
13291 @end smallexample
13292
13293 @noindent
13294 If a string in the list ends with @code{"/**"},  then the directory whose path
13295 name precedes the two asterisks, as well as all its subdirectories
13296 (recursively), are source directories.
13297
13298 @smallexample @c projectfile
13299    for Source_Dirs use ("/system/sources/**");
13300 @end smallexample
13301
13302 @noindent
13303 Here the directory @code{/system/sources} and all of its subdirectories
13304 (recursively) are source directories.
13305
13306 To specify that the source directories are the directory of the project file
13307 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13308 @smallexample @c projectfile
13309    for Source_Dirs use ("./**");
13310 @end smallexample
13311
13312 @noindent
13313 Each of the source directories must exist and be readable.
13314
13315 @node Source File Names
13316 @subsection Source File Names
13317
13318 @noindent
13319 In a project that contains source files, their names may be specified by the
13320 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13321 (a string). Source file names never include any directory information.
13322
13323 If the attribute @code{Source_Files} is given an explicit value, then each
13324 element of the list is a source file name.
13325
13326 @smallexample @c projectfile
13327    for Source_Files use ("main.adb");
13328    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13329 @end smallexample
13330
13331 @noindent
13332 If the attribute @code{Source_Files} is not given an explicit value,
13333 but the attribute @code{Source_List_File} is given a string value,
13334 then the source file names are contained in the text file whose path name
13335 (absolute or relative to the directory of the project file) is the
13336 value of the attribute @code{Source_List_File}.
13337
13338 Each line in the file that is not empty or is not a comment
13339 contains a source file name.
13340
13341 @smallexample @c projectfile
13342    for Source_List_File use "source_list.txt";
13343 @end smallexample
13344
13345 @noindent
13346 By default, if neither the attribute @code{Source_Files} nor the attribute
13347 @code{Source_List_File} is given an explicit value, then each file in the
13348 source directories that conforms to the project's naming scheme
13349 (@pxref{Naming Schemes}) is an immediate source of the project.
13350
13351 A warning is issued if both attributes @code{Source_Files} and
13352 @code{Source_List_File} are given explicit values. In this case, the attribute
13353 @code{Source_Files} prevails.
13354
13355 Each source file name must be the name of one existing source file
13356 in one of the source directories.
13357
13358 A @code{Source_Files} attribute whose value is an empty list
13359 indicates that there are no source files in the project.
13360
13361 If the order of the source directories is known statically, that is if
13362 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13363 be several files with the same source file name. In this case, only the file
13364 in the first directory is considered as an immediate source of the project
13365 file. If the order of the source directories is not known statically, it is
13366 an error to have several files with the same source file name.
13367
13368 Projects can be specified to have no Ada source
13369 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13370 list, or the @code{"Ada"} may be absent from @code{Languages}:
13371
13372 @smallexample @c projectfile
13373    for Source_Dirs use ();
13374    for Source_Files use ();
13375    for Languages use ("C", "C++");
13376 @end smallexample
13377
13378 @noindent
13379 Otherwise, a project must contain at least one immediate source.
13380
13381 Projects with no source files are useful as template packages
13382 (@pxref{Packages in Project Files}) for other projects; in particular to
13383 define a package @code{Naming} (@pxref{Naming Schemes}).
13384
13385 @c ****************************
13386 @c * Importing Projects *
13387 @c ****************************
13388
13389 @node  Importing Projects
13390 @section Importing Projects
13391 @cindex @code{ADA_PROJECT_PATH}
13392 @cindex @code{GPR_PROJECT_PATH}
13393
13394 @noindent
13395 An immediate source of a project P may depend on source files that
13396 are neither immediate sources of P nor in the predefined library.
13397 To get this effect, P must @emph{import} the projects that contain the needed
13398 source files.
13399
13400 @smallexample @c projectfile
13401 @group
13402   with "project1", "utilities.gpr";
13403   with "/namings/apex.gpr";
13404   project Main is
13405     @dots{}
13406 @end group
13407 @end smallexample
13408
13409 @noindent
13410 As can be seen in this example, the syntax for importing projects is similar
13411 to the syntax for importing compilation units in Ada. However, project files
13412 use literal strings instead of names, and the @code{with} clause identifies
13413 project files rather than packages.
13414
13415 Each literal string is the file name or path name (absolute or relative) of a
13416 project file. If a string corresponds to a file name, with no path or a
13417 relative path, then its location is determined by the @emph{project path}. The
13418 latter can be queried using @code{gnatls -v}. It contains:
13419
13420 @itemize @bullet
13421 @item
13422 In first position, the directory containing the current project file.
13423 @item
13424 In last position, the default project directory. This default project directory
13425 is part of the GNAT installation and is the standard place to install project
13426 files giving access to standard support libraries.
13427 @ifclear vms
13428 @ref{Installing a library}
13429 @end ifclear
13430
13431 @item
13432 In between, all the directories referenced in the
13433 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13434 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13435 @end itemize
13436
13437 @noindent
13438 If a relative pathname is used, as in
13439
13440 @smallexample @c projectfile
13441   with "tests/proj";
13442 @end smallexample
13443
13444 @noindent
13445 then the full path for the project is constructed by concatenating this
13446 relative path to those in the project path, in order, until a matching file is
13447 found. Any symbolic link will be fully resolved in the directory of the
13448 importing project file before the imported project file is examined.
13449
13450 If the @code{with}'ed project file name does not have an extension,
13451 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13452 then the file name as specified in the @code{with} clause (no extension) will
13453 be used. In the above example, if a file @code{project1.gpr} is found, then it
13454 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13455 then it will be used; if neither file exists, this is an error.
13456
13457 A warning is issued if the name of the project file does not match the
13458 name of the project; this check is case insensitive.
13459
13460 Any source file that is an immediate source of the imported project can be
13461 used by the immediate sources of the importing project, transitively. Thus
13462 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13463 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13464 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13465 because if and when @code{B} ceases to import @code{C}, some sources in
13466 @code{A} will no longer compile.
13467
13468 A side effect of this capability is that normally cyclic dependencies are not
13469 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13470 is not allowed to import @code{A}. However, there are cases when cyclic
13471 dependencies would be beneficial. For these cases, another form of import
13472 between projects exists, the @code{limited with}: a project @code{A} that
13473 imports a project @code{B} with a straight @code{with} may also be imported,
13474 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13475 to @code{A} include at least one @code{limited with}.
13476
13477 @smallexample @c 0projectfile
13478 with "../b/b.gpr";
13479 with "../c/c.gpr";
13480 project A is
13481 end A;
13482
13483 limited with "../a/a.gpr";
13484 project B is
13485 end B;
13486
13487 with "../d/d.gpr";
13488 project C is
13489 end C;
13490
13491 limited with "../a/a.gpr";
13492 project D is
13493 end D;
13494 @end smallexample
13495
13496 @noindent
13497 In the above legal example, there are two project cycles:
13498 @itemize @bullet
13499 @item A-> B-> A
13500 @item A -> C -> D -> A
13501 @end itemize
13502
13503 @noindent
13504 In each of these cycle there is one @code{limited with}: import of @code{A}
13505 from @code{B} and import of @code{A} from @code{D}.
13506
13507 The difference between straight @code{with} and @code{limited with} is that
13508 the name of a project imported with a @code{limited with} cannot be used in the
13509 project that imports it. In particular, its packages cannot be renamed and
13510 its variables cannot be referred to.
13511
13512 An exception to the above rules for @code{limited with} is that for the main
13513 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13514 @code{limited with} is equivalent to a straight @code{with}. For example,
13515 in the example above, projects @code{B} and @code{D} could not be main
13516 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13517 each have a @code{limited with} that is the only one in a cycle of importing
13518 projects.
13519
13520 @c *********************
13521 @c * Project Extension *
13522 @c *********************
13523
13524 @node Project Extension
13525 @section Project Extension
13526
13527 @noindent
13528 During development of a large system, it is sometimes necessary to use
13529 modified versions of some of the source files, without changing the original
13530 sources. This can be achieved through the @emph{project extension} facility.
13531
13532 @smallexample @c projectfile
13533    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13534 @end smallexample
13535
13536 @noindent
13537 A project extension declaration introduces an extending project
13538 (the @emph{child}) and a project being extended (the @emph{parent}).
13539
13540 By default, a child project inherits all the sources of its parent.
13541 However, inherited sources can be overridden: a unit in a parent is hidden
13542 by a unit of the same name in the child.
13543
13544 Inherited sources are considered to be sources (but not immediate sources)
13545 of the child project; see @ref{Project File Syntax}.
13546
13547 An inherited source file retains any switches specified in the parent project.
13548
13549 For example if the project @code{Utilities} contains the spec and the
13550 body of an Ada package @code{Util_IO}, then the project
13551 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13552 The original body of @code{Util_IO} will not be considered in program builds.
13553 However, the package spec will still be found in the project
13554 @code{Utilities}.
13555
13556 A child project can have only one parent, except when it is qualified as
13557 abstract. But it may import any number of other projects.
13558
13559 A project is not allowed to import directly or indirectly at the same time a
13560 child project and any of its ancestors.
13561
13562 @c *******************************
13563 @c * Project Hierarchy Extension *
13564 @c *******************************
13565
13566 @node Project Hierarchy Extension
13567 @section Project Hierarchy Extension
13568
13569 @noindent
13570 When extending a large system spanning multiple projects, it is often
13571 inconvenient to extend every project in the hierarchy that is impacted by a
13572 small change introduced. In such cases, it is possible to create a virtual
13573 extension of entire hierarchy using @code{extends all} relationship.
13574
13575 When the project is extended using @code{extends all} inheritance, all projects
13576 that are imported by it, both directly and indirectly, are considered virtually
13577 extended. That is, the Project Manager creates "virtual projects"
13578 that extend every project in the hierarchy; all these virtual projects have
13579 no sources of their own and have as object directory the object directory of
13580 the root of "extending all" project.
13581
13582 It is possible to explicitly extend one or more projects in the hierarchy
13583 in order to modify the sources. These extending projects must be imported by
13584 the "extending all" project, which will replace the corresponding virtual
13585 projects with the explicit ones.
13586
13587 When building such a project hierarchy extension, the Project Manager will
13588 ensure that both modified sources and sources in virtual extending projects
13589 that depend on them, are recompiled.
13590
13591 By means of example, consider the following hierarchy of projects.
13592
13593 @enumerate
13594 @item
13595 project A, containing package P1
13596 @item
13597 project B importing A and containing package P2 which depends on P1
13598 @item
13599 project C importing B and containing package P3 which depends on P2
13600 @end enumerate
13601
13602 @noindent
13603 We want to modify packages P1 and P3.
13604
13605 This project hierarchy will need to be extended as follows:
13606
13607 @enumerate
13608 @item
13609 Create project A1 that extends A, placing modified P1 there:
13610
13611 @smallexample @c 0projectfile
13612 project A1 extends "(@dots{})/A" is
13613 end A1;
13614 @end smallexample
13615
13616 @item
13617 Create project C1 that "extends all" C and imports A1, placing modified
13618 P3 there:
13619
13620 @smallexample @c 0projectfile
13621 with "(@dots{})/A1";
13622 project C1 extends all "(@dots{})/C" is
13623 end C1;
13624 @end smallexample
13625 @end enumerate
13626
13627 When you build project C1, your entire modified project space will be
13628 recompiled, including the virtual project B1 that has been impacted by the
13629 "extending all" inheritance of project C.
13630
13631 Note that if a Library Project in the hierarchy is virtually extended,
13632 the virtual project that extends the Library Project is not a Library Project.
13633
13634 @c ****************************************
13635 @c * External References in Project Files *
13636 @c ****************************************
13637
13638 @node  External References in Project Files
13639 @section External References in Project Files
13640
13641 @noindent
13642 A project file may contain references to external variables; such references
13643 are called @emph{external references}.
13644
13645 An external variable is either defined as part of the environment (an
13646 environment variable in Unix, for example) or else specified on the command
13647 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13648 If both, then the command line value is used.
13649
13650 The value of an external reference is obtained by means of the built-in
13651 function @code{external}, which returns a string value.
13652 This function has two forms:
13653 @itemize @bullet
13654 @item @code{external (external_variable_name)}
13655 @item @code{external (external_variable_name, default_value)}
13656 @end itemize
13657
13658 @noindent
13659 Each parameter must be a string literal.  For example:
13660
13661 @smallexample @c projectfile
13662    external ("USER")
13663    external ("OS", "GNU/Linux")
13664 @end smallexample
13665
13666 @noindent
13667 In the form with one parameter, the function returns the value of
13668 the external variable given as parameter. If this name is not present in the
13669 environment, the function returns an empty string.
13670
13671 In the form with two string parameters, the second argument is
13672 the value returned when the variable given as the first argument is not
13673 present in the environment. In the example above, if @code{"OS"} is not
13674 the name of ^an environment variable^a logical name^ and is not passed on
13675 the command line, then the returned value is @code{"GNU/Linux"}.
13676
13677 An external reference may be part of a string expression or of a string
13678 list expression, and can therefore appear in a variable declaration or
13679 an attribute declaration.
13680
13681 @smallexample @c projectfile
13682 @group
13683    type Mode_Type is ("Debug", "Release");
13684    Mode : Mode_Type := external ("MODE");
13685    case Mode is
13686      when "Debug" =>
13687         @dots{}
13688 @end group
13689 @end smallexample
13690
13691 @c *****************************
13692 @c * Packages in Project Files *
13693 @c *****************************
13694
13695 @node  Packages in Project Files
13696 @section Packages in Project Files
13697
13698 @noindent
13699 A @emph{package} defines the settings for project-aware tools within a
13700 project.
13701 For each such tool one can declare a package; the names for these
13702 packages are preset (@pxref{Packages}).
13703 A package may contain variable declarations, attribute declarations, and case
13704 constructions.
13705
13706 @smallexample @c projectfile
13707 @group
13708    project Proj is
13709       package Builder is  -- used by gnatmake
13710          for ^Default_Switches^Default_Switches^ ("Ada")
13711              use ("^-v^-v^",
13712                   "^-g^-g^");
13713       end Builder;
13714    end Proj;
13715 @end group
13716 @end smallexample
13717
13718 @noindent
13719 The syntax of package declarations mimics that of package in Ada.
13720
13721 Most of the packages have an attribute
13722 @code{^Default_Switches^Default_Switches^}.
13723 This attribute is an associative array, and its value is a string list.
13724 The index of the associative array is the name of a programming language (case
13725 insensitive). This attribute indicates the ^switch^switch^
13726 or ^switches^switches^ to be used
13727 with the corresponding tool.
13728
13729 Some packages also have another attribute, @code{^Switches^Switches^},
13730 an associative array whose value is a string list.
13731 The index is the name of a source file.
13732 This attribute indicates the ^switch^switch^
13733 or ^switches^switches^ to be used by the corresponding
13734 tool when dealing with this specific file.
13735
13736 Further information on these ^switch^switch^-related attributes is found in
13737 @ref{^Switches^Switches^ and Project Files}.
13738
13739 A package may be declared as a @emph{renaming} of another package; e.g., from
13740 the project file for an imported project.
13741
13742 @smallexample @c projectfile
13743 @group
13744   with "/global/apex.gpr";
13745   project Example is
13746     package Naming renames Apex.Naming;
13747     @dots{}
13748   end Example;
13749 @end group
13750 @end smallexample
13751
13752 @noindent
13753 Packages that are renamed in other project files often come from project files
13754 that have no sources: they are just used as templates. Any modification in the
13755 template will be reflected automatically in all the project files that rename
13756 a package from the template.
13757
13758 In addition to the tool-oriented packages, you can also declare a package
13759 named @code{Naming} to establish specialized source file naming conventions
13760 (@pxref{Naming Schemes}).
13761
13762 @c ************************************
13763 @c * Variables from Imported Projects *
13764 @c ************************************
13765
13766 @node Variables from Imported Projects
13767 @section Variables from Imported Projects
13768
13769 @noindent
13770 An attribute or variable defined in an imported or parent project can
13771 be used in expressions in the importing / extending project.
13772 Such an attribute or variable is denoted by an expanded name whose prefix
13773 is either the name of the project or the expanded name of a package within
13774 a project.
13775
13776 @smallexample @c projectfile
13777 @group
13778   with "imported";
13779   project Main extends "base" is
13780      Var1 := Imported.Var;
13781      Var2 := Base.Var & ".new";
13782 @end group
13783
13784 @group
13785      package Builder is
13786         for ^Default_Switches^Default_Switches^ ("Ada")
13787             use Imported.Builder'Ada_^Switches^Switches^ &
13788                 "^-gnatg^-gnatg^" &
13789                 "^-v^-v^";
13790      end Builder;
13791 @end group
13792
13793 @group
13794      package Compiler is
13795         for ^Default_Switches^Default_Switches^ ("Ada")
13796             use Base.Compiler'Ada_^Switches^Switches^;
13797      end Compiler;
13798   end Main;
13799 @end group
13800 @end smallexample
13801
13802 @noindent
13803 In this example:
13804
13805 @itemize @bullet
13806 @item
13807 The value of @code{Var1} is a copy of the variable @code{Var} defined
13808 in the project file @file{"imported.gpr"}
13809 @item
13810 the value of @code{Var2} is a copy of the value of variable @code{Var}
13811 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13812 @item
13813 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13814 @code{Builder} is a string list that includes in its value a copy of the value
13815 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13816 in project file @file{imported.gpr} plus two new elements:
13817 @option{"^-gnatg^-gnatg^"}
13818 and @option{"^-v^-v^"};
13819 @item
13820 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13821 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13822 defined in the @code{Compiler} package in project file @file{base.gpr},
13823 the project being extended.
13824 @end itemize
13825
13826 @c ******************
13827 @c * Naming Schemes *
13828 @c ******************
13829
13830 @node  Naming Schemes
13831 @section Naming Schemes
13832
13833 @noindent
13834 Sometimes an Ada software system is ported from a foreign compilation
13835 environment to GNAT, and the file names do not use the default GNAT
13836 conventions. Instead of changing all the file names (which for a variety
13837 of reasons might not be possible), you can define the relevant file
13838 naming scheme in the @code{Naming} package in your project file.
13839
13840 @noindent
13841 Note that the use of pragmas described in
13842 @ref{Alternative File Naming Schemes} by mean of a configuration
13843 pragmas file is not supported when using project files. You must use
13844 the features described in this paragraph. You can however use specify
13845 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13846
13847 @ifclear vms
13848 For example, the following
13849 package models the Apex file naming rules:
13850
13851 @smallexample @c projectfile
13852 @group
13853   package Naming is
13854     for Casing               use "lowercase";
13855     for Dot_Replacement      use ".";
13856     for Spec_Suffix ("Ada")  use ".1.ada";
13857     for Body_Suffix ("Ada")  use ".2.ada";
13858   end Naming;
13859 @end group
13860 @end smallexample
13861 @end ifclear
13862
13863 @ifset vms
13864 For example, the following package models the HP Ada file naming rules:
13865
13866 @smallexample @c projectfile
13867 @group
13868   package Naming is
13869     for Casing               use "lowercase";
13870     for Dot_Replacement      use "__";
13871     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13872     for Body_Suffix ("Ada")  use ".^ada^ada^";
13873   end Naming;
13874 @end group
13875 @end smallexample
13876
13877 @noindent
13878 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13879 names in lower case)
13880 @end ifset
13881
13882 @noindent
13883 You can define the following attributes in package @code{Naming}:
13884
13885 @table @code
13886
13887 @item @code{Casing}
13888 This must be a string with one of the three values @code{"lowercase"},
13889 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13890
13891 @noindent
13892 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13893
13894 @item @code{Dot_Replacement}
13895 This must be a string whose value satisfies the following conditions:
13896
13897 @itemize @bullet
13898 @item It must not be empty
13899 @item It cannot start or end with an alphanumeric character
13900 @item It cannot be a single underscore
13901 @item It cannot start with an underscore followed by an alphanumeric
13902 @item It cannot contain a dot @code{'.'} except if the entire string
13903 is @code{"."}
13904 @end itemize
13905
13906 @noindent
13907 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13908
13909 @item @code{Spec_Suffix}
13910 This is an associative array (indexed by the programming language name, case
13911 insensitive) whose value is a string that must satisfy the following
13912 conditions:
13913
13914 @itemize @bullet
13915 @item It must not be empty
13916 @item It must include at least one dot
13917 @end itemize
13918 @noindent
13919 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13920 @code{"^.ads^.ADS^"}.
13921
13922 @item @code{Body_Suffix}
13923 This is an associative array (indexed by the programming language name, case
13924 insensitive) whose value is a string that must satisfy the following
13925 conditions:
13926
13927 @itemize @bullet
13928 @item It must not be empty
13929 @item It must include at least one dot
13930 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13931 @end itemize
13932 @noindent
13933 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13934 same string, then a file name that ends with the longest of these two suffixes
13935 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13936 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13937
13938 If the suffix does not start with a '.', a file with a name exactly equal
13939 to the suffix will also be part of the project (for instance if you define
13940 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13941 of the project. This is not interesting in general when using projects to
13942 compile. However, it might become useful when a project is also used to
13943 find the list of source files in an editor, like the GNAT Programming System
13944 (GPS).
13945
13946 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13947 @code{"^.adb^.ADB^"}.
13948
13949 @item @code{Separate_Suffix}
13950 This must be a string whose value satisfies the same conditions as
13951 @code{Body_Suffix}. The same "longest suffix" rules apply.
13952
13953 @noindent
13954 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13955 value as @code{Body_Suffix ("Ada")}.
13956
13957 @item @code{Spec}
13958 @noindent
13959 You can use the associative array attribute @code{Spec}  to define
13960 the source file name for an individual Ada compilation unit's spec. The array
13961 index must be a string literal that identifies the Ada unit (case insensitive).
13962 The value of this attribute must be a string that identifies the file that
13963 contains this unit's spec (case sensitive or insensitive depending on the
13964 operating system).
13965
13966 @smallexample @c projectfile
13967    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13968 @end smallexample
13969
13970 When the source file contains several units, you can indicate at what
13971 position the unit occurs in the file, with the following. The first unit
13972 in the file has index 1
13973
13974 @smallexample @c projectfile
13975   for Body ("top") use "foo.a" at 1;
13976   for Body ("foo") use "foo.a" at 2;
13977 @end smallexample
13978
13979 @item @code{Body}
13980
13981 You can use the associative array attribute @code{Body} to
13982 define the source file name for an individual Ada compilation unit's body
13983 (possibly a subunit).  The array index must be a string literal that identifies
13984 the Ada unit (case insensitive).  The value of this attribute must be a string
13985 that identifies the file that contains this unit's body or subunit (case
13986 sensitive or insensitive depending on the operating system).
13987
13988 @smallexample @c projectfile
13989    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13990 @end smallexample
13991 @end table
13992
13993 @c ********************
13994 @c * Library Projects *
13995 @c ********************
13996
13997 @node Library Projects
13998 @section Library Projects
13999
14000 @noindent
14001 @emph{Library projects} are projects whose object code is placed in a library.
14002 (Note that this facility is not yet supported on all platforms).
14003
14004 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14005 single archive, which might either be a shared or a static library. This
14006 library can later on be linked with multiple executables, potentially
14007 reducing their sizes.
14008
14009 If your project file specifies languages other than Ada, but you are still
14010 using @code{gnatmake} to compile and link, the latter will not try to
14011 compile your sources other than Ada (you should use @code{gprbuild} if that
14012 is your intent). However, @code{gnatmake} will automatically link all object
14013 files found in the object directory, whether or not they were compiled from
14014 an Ada source file. This specific behavior only applies when multiple
14015 languages are specified.
14016
14017 To create a library project, you need to define in its project file
14018 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14019 Additionally, you may define other library-related attributes such as
14020 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14021 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14022
14023 The @code{Library_Name} attribute has a string value. There is no restriction
14024 on the name of a library. It is the responsibility of the developer to
14025 choose a name that will be accepted by the platform. It is recommended to
14026 choose names that could be Ada identifiers; such names are almost guaranteed
14027 to be acceptable on all platforms.
14028
14029 The @code{Library_Dir} attribute has a string value that designates the path
14030 (absolute or relative) of the directory where the library will reside.
14031 It must designate an existing directory, and this directory must be writable,
14032 different from the project's object directory and from any source directory
14033 in the project tree.
14034
14035 If both @code{Library_Name} and @code{Library_Dir} are specified and
14036 are legal, then the project file defines a library project.  The optional
14037 library-related attributes are checked only for such project files.
14038
14039 The @code{Library_Kind} attribute has a string value that must be one of the
14040 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14041 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14042 attribute is not specified, the library is a static library, that is
14043 an archive of object files that can be potentially linked into a
14044 static executable. Otherwise, the library may be dynamic or
14045 relocatable, that is a library that is loaded only at the start of execution.
14046
14047 If you need to build both a static and a dynamic library, you should use two
14048 different object directories, since in some cases some extra code needs to
14049 be generated for the latter. For such cases, it is recommended to either use
14050 two different project files, or a single one which uses external variables
14051 to indicate what kind of library should be build.
14052
14053 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14054 directory where the ALI files of the library will be copied. When it is
14055 not specified, the ALI files are copied to the directory specified in
14056 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14057 must be writable and different from the project's object directory and from
14058 any source directory in the project tree.
14059
14060 The @code{Library_Version} attribute has a string value whose interpretation
14061 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14062 used only for dynamic/relocatable libraries as the internal name of the
14063 library (the @code{"soname"}). If the library file name (built from the
14064 @code{Library_Name}) is different from the @code{Library_Version}, then the
14065 library file will be a symbolic link to the actual file whose name will be
14066 @code{Library_Version}.
14067
14068 Example (on Unix):
14069
14070 @smallexample @c projectfile
14071 @group
14072 project Plib is
14073
14074    Version := "1";
14075
14076    for Library_Dir use "lib_dir";
14077    for Library_Name use "dummy";
14078    for Library_Kind use "relocatable";
14079    for Library_Version use "libdummy.so." & Version;
14080
14081 end Plib;
14082 @end group
14083 @end smallexample
14084
14085 @noindent
14086 Directory @file{lib_dir} will contain the internal library file whose name
14087 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14088 @file{libdummy.so.1}.
14089
14090 When @command{gnatmake} detects that a project file
14091 is a library project file, it will check all immediate sources of the project
14092 and rebuild the library if any of the sources have been recompiled.
14093
14094 Standard project files can import library project files. In such cases,
14095 the libraries will only be rebuilt if some of its sources are recompiled
14096 because they are in the closure of some other source in an importing project.
14097 Sources of the library project files that are not in such a closure will
14098 not be checked, unless the full library is checked, because one of its sources
14099 needs to be recompiled.
14100
14101 For instance, assume the project file @code{A} imports the library project file
14102 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14103 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14104 @file{l2.ads}, @file{l2.adb}.
14105
14106 If @file{l1.adb} has been modified, then the library associated with @code{L}
14107 will be rebuilt when compiling all the immediate sources of @code{A} only
14108 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14109 @code{"with L1;"}.
14110
14111 To be sure that all the sources in the library associated with @code{L} are
14112 up to date, and that all the sources of project @code{A} are also up to date,
14113 the following two commands needs to be used:
14114
14115 @smallexample
14116 gnatmake -Pl.gpr
14117 gnatmake -Pa.gpr
14118 @end smallexample
14119
14120 When a library is built or rebuilt, an attempt is made first to delete all
14121 files in the library directory.
14122 All @file{ALI} files will also be copied from the object directory to the
14123 library directory. To build executables, @command{gnatmake} will use the
14124 library rather than the individual object files.
14125
14126 @ifclear vms
14127 It is also possible to create library project files for third-party libraries
14128 that are precompiled and cannot be compiled locally thanks to the
14129 @code{externally_built} attribute. (See @ref{Installing a library}).
14130 @end ifclear
14131
14132 @c *******************************
14133 @c * Stand-alone Library Projects *
14134 @c *******************************
14135
14136 @node Stand-alone Library Projects
14137 @section Stand-alone Library Projects
14138
14139 @noindent
14140 A Stand-alone Library is a library that contains the necessary code to
14141 elaborate the Ada units that are included in the library. A Stand-alone
14142 Library is suitable to be used in an executable when the main is not
14143 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14144 subprogram.
14145
14146 A Stand-alone Library Project is a Library Project where the library is
14147 a Stand-alone Library.
14148
14149 To be a Stand-alone Library Project, in addition to the two attributes
14150 that make a project a Library Project (@code{Library_Name} and
14151 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14152 @code{Library_Interface} must be defined.
14153
14154 @smallexample @c projectfile
14155 @group
14156    for Library_Dir use "lib_dir";
14157    for Library_Name use "dummy";
14158    for Library_Interface use ("int1", "int1.child");
14159 @end group
14160 @end smallexample
14161
14162 Attribute @code{Library_Interface} has a nonempty string list value,
14163 each string in the list designating a unit contained in an immediate source
14164 of the project file.
14165
14166 When a Stand-alone Library is built, first the binder is invoked to build
14167 a package whose name depends on the library name
14168 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14169 This binder-generated package includes initialization and
14170 finalization procedures whose
14171 names depend on the library name (dummyinit and dummyfinal in the example
14172 above). The object corresponding to this package is included in the library.
14173
14174 A dynamic or relocatable Stand-alone Library is automatically initialized
14175 if automatic initialization of Stand-alone Libraries is supported on the
14176 platform and if attribute @code{Library_Auto_Init} is not specified or
14177 is specified with the value "true". A static Stand-alone Library is never
14178 automatically initialized.
14179
14180 Single string attribute @code{Library_Auto_Init} may be specified with only
14181 two possible values: "false" or "true" (case-insensitive). Specifying
14182 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14183 initialization of dynamic or relocatable libraries.
14184
14185 When a non-automatically initialized Stand-alone Library is used
14186 in an executable, its initialization procedure must be called before
14187 any service of the library is used.
14188 When the main subprogram is in Ada, it may mean that the initialization
14189 procedure has to be called during elaboration of another package.
14190
14191 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14192 (those that are listed in attribute @code{Library_Interface}) are copied to
14193 the Library Directory. As a consequence, only the Interface Units may be
14194 imported from Ada units outside of the library. If other units are imported,
14195 the binding phase will fail.
14196
14197 When a Stand-Alone Library is bound, the switches that are specified in
14198 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14199 used in the call to @command{gnatbind}.
14200
14201 The string list attribute @code{Library_Options} may be used to specified
14202 additional switches to the call to @command{gcc} to link the library.
14203
14204 The attribute @code{Library_Src_Dir}, may be specified for a
14205 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14206 single string value. Its value must be the path (absolute or relative to the
14207 project directory) of an existing directory. This directory cannot be the
14208 object directory or one of the source directories, but it can be the same as
14209 the library directory. The sources of the Interface
14210 Units of the library, necessary to an Ada client of the library, will be
14211 copied to the designated directory, called Interface Copy directory.
14212 These sources includes the specs of the Interface Units, but they may also
14213 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14214 are used, or when there is a generic units in the spec. Before the sources
14215 are copied to the Interface Copy directory, an attempt is made to delete all
14216 files in the Interface Copy directory.
14217
14218 @c *************************************
14219 @c * Switches Related to Project Files *
14220 @c *************************************
14221 @node Switches Related to Project Files
14222 @section Switches Related to Project Files
14223
14224 @noindent
14225 The following switches are used by GNAT tools that support project files:
14226
14227 @table @option
14228
14229 @item ^-P^/PROJECT_FILE=^@var{project}
14230 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14231 Indicates the name of a project file. This project file will be parsed with
14232 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14233 if any, and using the external references indicated
14234 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14235 @ifclear vms
14236 There may zero, one or more spaces between @option{-P} and @var{project}.
14237 @end ifclear
14238
14239 @noindent
14240 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14241
14242 @noindent
14243 Since the Project Manager parses the project file only after all the switches
14244 on the command line are checked, the order of the switches
14245 @option{^-P^/PROJECT_FILE^},
14246 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14247 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14248
14249 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14250 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14251 Indicates that external variable @var{name} has the value @var{value}.
14252 The Project Manager will use this value for occurrences of
14253 @code{external(name)} when parsing the project file.
14254
14255 @ifclear vms
14256 @noindent
14257 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14258 put between quotes.
14259 @smallexample
14260   -XOS=NT
14261   -X"user=John Doe"
14262 @end smallexample
14263 @end ifclear
14264
14265 @noindent
14266 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14267 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14268 @var{name}, only the last one is used.
14269
14270 @noindent
14271 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14272 takes precedence over the value of the same name in the environment.
14273
14274 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14275 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14276 Indicates the verbosity of the parsing of GNAT project files.
14277
14278 @ifclear vms
14279 @option{-vP0} means Default;
14280 @option{-vP1} means Medium;
14281 @option{-vP2} means High.
14282 @end ifclear
14283
14284 @ifset vms
14285 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14286 HIGH.
14287 @end ifset
14288
14289 @noindent
14290 The default is ^Default^DEFAULT^: no output for syntactically correct
14291 project files.
14292 @noindent
14293 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14294 only the last one is used.
14295
14296 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14297 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14298 Add directory <dir> at the beginning of the project search path, in order,
14299 after the current working directory.
14300
14301 @ifclear vms
14302 @item -eL
14303 @cindex @option{-eL} (any project-aware tool)
14304 Follow all symbolic links when processing project files.
14305 @end ifclear
14306
14307 @item ^--subdirs^/SUBDIRS^=<subdir>
14308 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14309 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14310 directories (except the source directories) are the subdirectories <subdir>
14311 of the directories specified in the project files. This applies in particular
14312 to object directories, library directories and exec directories. If the
14313 subdirectories do not exist, they are created automatically.
14314
14315 @end table
14316
14317 @c **********************************
14318 @c * Tools Supporting Project Files *
14319 @c **********************************
14320
14321 @node  Tools Supporting Project Files
14322 @section Tools Supporting Project Files
14323
14324 @menu
14325 * gnatmake and Project Files::
14326 * The GNAT Driver and Project Files::
14327 @end menu
14328
14329 @node gnatmake and Project Files
14330 @subsection gnatmake and Project Files
14331
14332 @noindent
14333 This section covers several topics related to @command{gnatmake} and
14334 project files: defining ^switches^switches^ for @command{gnatmake}
14335 and for the tools that it invokes; specifying configuration pragmas;
14336 the use of the @code{Main} attribute; building and rebuilding library project
14337 files.
14338
14339 @menu
14340 * ^Switches^Switches^ and Project Files::
14341 * Specifying Configuration Pragmas::
14342 * Project Files and Main Subprograms::
14343 * Library Project Files::
14344 @end menu
14345
14346 @node ^Switches^Switches^ and Project Files
14347 @subsubsection ^Switches^Switches^ and Project Files
14348
14349 @ifset vms
14350 It is not currently possible to specify VMS style qualifiers in the project
14351 files; only Unix style ^switches^switches^ may be specified.
14352 @end ifset
14353
14354 @noindent
14355 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14356 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14357 attribute, a @code{^Switches^Switches^} attribute, or both;
14358 as their names imply, these ^switch^switch^-related
14359 attributes affect the ^switches^switches^ that are used for each of these GNAT
14360 components when
14361 @command{gnatmake} is invoked.  As will be explained below, these
14362 component-specific ^switches^switches^ precede
14363 the ^switches^switches^ provided on the @command{gnatmake} command line.
14364
14365 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14366 array indexed by language name (case insensitive) whose value is a string list.
14367 For example:
14368
14369 @smallexample @c projectfile
14370 @group
14371 package Compiler is
14372   for ^Default_Switches^Default_Switches^ ("Ada")
14373       use ("^-gnaty^-gnaty^",
14374            "^-v^-v^");
14375 end Compiler;
14376 @end group
14377 @end smallexample
14378
14379 @noindent
14380 The @code{^Switches^Switches^} attribute is also an associative array,
14381 indexed by a file name (which may or may not be case sensitive, depending
14382 on the operating system) whose value is a string list.  For example:
14383
14384 @smallexample @c projectfile
14385 @group
14386 package Builder is
14387    for ^Switches^Switches^ ("main1.adb")
14388        use ("^-O2^-O2^");
14389    for ^Switches^Switches^ ("main2.adb")
14390        use ("^-g^-g^");
14391 end Builder;
14392 @end group
14393 @end smallexample
14394
14395 @noindent
14396 For the @code{Builder} package, the file names must designate source files
14397 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14398 file names must designate @file{ALI} or source files for main subprograms.
14399 In each case just the file name without an explicit extension is acceptable.
14400
14401 For each tool used in a program build (@command{gnatmake}, the compiler, the
14402 binder, and the linker), the corresponding package @dfn{contributes} a set of
14403 ^switches^switches^ for each file on which the tool is invoked, based on the
14404 ^switch^switch^-related attributes defined in the package.
14405 In particular, the ^switches^switches^
14406 that each of these packages contributes for a given file @var{f} comprise:
14407
14408 @itemize @bullet
14409 @item
14410 the value of attribute @code{^Switches^Switches^ (@var{f})},
14411 if it is specified in the package for the given file,
14412 @item
14413 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14414 if it is specified in the package.
14415 @end itemize
14416
14417 @noindent
14418 If neither of these attributes is defined in the package, then the package does
14419 not contribute any ^switches^switches^ for the given file.
14420
14421 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14422 two sets, in the following order: those contributed for the file
14423 by the @code{Builder} package;
14424 and the switches passed on the command line.
14425
14426 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14427 the ^switches^switches^ passed to the tool comprise three sets,
14428 in the following order:
14429
14430 @enumerate
14431 @item
14432 the applicable ^switches^switches^ contributed for the file
14433 by the @code{Builder} package in the project file supplied on the command line;
14434
14435 @item
14436 those contributed for the file by the package (in the relevant project file --
14437 see below) corresponding to the tool; and
14438
14439 @item
14440 the applicable switches passed on the command line.
14441 @end enumerate
14442
14443 @noindent
14444 The term @emph{applicable ^switches^switches^} reflects the fact that
14445 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14446 tools, depending on the individual ^switch^switch^.
14447
14448 @command{gnatmake} may invoke the compiler on source files from different
14449 projects. The Project Manager will use the appropriate project file to
14450 determine the @code{Compiler} package for each source file being compiled.
14451 Likewise for the @code{Binder} and @code{Linker} packages.
14452
14453 As an example, consider the following package in a project file:
14454
14455 @smallexample @c projectfile
14456 @group
14457 project Proj1 is
14458    package Compiler is
14459       for ^Default_Switches^Default_Switches^ ("Ada")
14460           use ("^-g^-g^");
14461       for ^Switches^Switches^ ("a.adb")
14462           use ("^-O1^-O1^");
14463       for ^Switches^Switches^ ("b.adb")
14464           use ("^-O2^-O2^",
14465                "^-gnaty^-gnaty^");
14466    end Compiler;
14467 end Proj1;
14468 @end group
14469 @end smallexample
14470
14471 @noindent
14472 If @command{gnatmake} is invoked with this project file, and it needs to
14473 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14474 @file{a.adb} will be compiled with the ^switch^switch^
14475 @option{^-O1^-O1^},
14476 @file{b.adb} with ^switches^switches^
14477 @option{^-O2^-O2^}
14478 and @option{^-gnaty^-gnaty^},
14479 and @file{c.adb} with @option{^-g^-g^}.
14480
14481 The following example illustrates the ordering of the ^switches^switches^
14482 contributed by different packages:
14483
14484 @smallexample @c projectfile
14485 @group
14486 project Proj2 is
14487    package Builder is
14488       for ^Switches^Switches^ ("main.adb")
14489           use ("^-g^-g^",
14490                "^-O1^-)1^",
14491                "^-f^-f^");
14492    end Builder;
14493 @end group
14494
14495 @group
14496    package Compiler is
14497       for ^Switches^Switches^ ("main.adb")
14498           use ("^-O2^-O2^");
14499    end Compiler;
14500 end Proj2;
14501 @end group
14502 @end smallexample
14503
14504 @noindent
14505 If you issue the command:
14506
14507 @smallexample
14508     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14509 @end smallexample
14510
14511 @noindent
14512 then the compiler will be invoked on @file{main.adb} with the following
14513 sequence of ^switches^switches^
14514
14515 @smallexample
14516    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14517 @end smallexample
14518
14519 with the last @option{^-O^-O^}
14520 ^switch^switch^ having precedence over the earlier ones;
14521 several other ^switches^switches^
14522 (such as @option{^-c^-c^}) are added implicitly.
14523
14524 The ^switches^switches^
14525 @option{^-g^-g^}
14526 and @option{^-O1^-O1^} are contributed by package
14527 @code{Builder},  @option{^-O2^-O2^} is contributed
14528 by the package @code{Compiler}
14529 and @option{^-O0^-O0^} comes from the command line.
14530
14531 The @option{^-g^-g^}
14532 ^switch^switch^ will also be passed in the invocation of
14533 @command{Gnatlink.}
14534
14535 A final example illustrates switch contributions from packages in different
14536 project files:
14537
14538 @smallexample @c projectfile
14539 @group
14540 project Proj3 is
14541    for Source_Files use ("pack.ads", "pack.adb");
14542    package Compiler is
14543       for ^Default_Switches^Default_Switches^ ("Ada")
14544           use ("^-gnata^-gnata^");
14545    end Compiler;
14546 end Proj3;
14547 @end group
14548
14549 @group
14550 with "Proj3";
14551 project Proj4 is
14552    for Source_Files use ("foo_main.adb", "bar_main.adb");
14553    package Builder is
14554       for ^Switches^Switches^ ("foo_main.adb")
14555           use ("^-s^-s^",
14556                "^-g^-g^");
14557    end Builder;
14558 end Proj4;
14559 @end group
14560
14561 @group
14562 -- Ada source file:
14563 with Pack;
14564 procedure Foo_Main is
14565    @dots{}
14566 end Foo_Main;
14567 @end group
14568 @end smallexample
14569
14570 If the command is
14571 @smallexample
14572 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14573 @end smallexample
14574
14575 @noindent
14576 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14577 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14578 @option{^-gnato^-gnato^} (passed on the command line).
14579 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14580 are @option{^-g^-g^} from @code{Proj4.Builder},
14581 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14582 and @option{^-gnato^-gnato^} from the command line.
14583
14584 @noindent
14585 When using @command{gnatmake} with project files, some ^switches^switches^ or
14586 arguments may be expressed as relative paths. As the working directory where
14587 compilation occurs may change, these relative paths are converted to absolute
14588 paths. For the ^switches^switches^ found in a project file, the relative paths
14589 are relative to the project file directory, for the switches on the command
14590 line, they are relative to the directory where @command{gnatmake} is invoked.
14591 The ^switches^switches^ for which this occurs are:
14592 ^-I^-I^,
14593 ^-A^-A^,
14594 ^-L^-L^,
14595 ^-aO^-aO^,
14596 ^-aL^-aL^,
14597 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14598 ^switch^switch^
14599 ^-o^-o^, object files specified in package @code{Linker} or after
14600 -largs on the command line). The exception to this rule is the ^switch^switch^
14601 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14602
14603 @node Specifying Configuration Pragmas
14604 @subsubsection Specifying Configuration Pragmas
14605
14606 When using @command{gnatmake} with project files, if there exists a file
14607 @file{gnat.adc} that contains configuration pragmas, this file will be
14608 ignored.
14609
14610 Configuration pragmas can be defined by means of the following attributes in
14611 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14612 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14613
14614 Both these attributes are single string attributes. Their values is the path
14615 name of a file containing configuration pragmas. If a path name is relative,
14616 then it is relative to the project directory of the project file where the
14617 attribute is defined.
14618
14619 When compiling a source, the configuration pragmas used are, in order,
14620 those listed in the file designated by attribute
14621 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14622 project file, if it is specified, and those listed in the file designated by
14623 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14624 the project file of the source, if it exists.
14625
14626 @node Project Files and Main Subprograms
14627 @subsubsection Project Files and Main Subprograms
14628
14629 @noindent
14630 When using a project file, you can invoke @command{gnatmake}
14631 with one or several main subprograms, by specifying their source files on the
14632 command line.
14633
14634 @smallexample
14635     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14636 @end smallexample
14637
14638 @noindent
14639 Each of these needs to be a source file of the same project, except
14640 when the switch ^-u^/UNIQUE^ is used.
14641
14642 @noindent
14643 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14644 same project, one of the project in the tree rooted at the project specified
14645 on the command line. The package @code{Builder} of this common project, the
14646 "main project" is the one that is considered by @command{gnatmake}.
14647
14648 @noindent
14649 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14650 imported directly or indirectly by the project specified on the command line.
14651 Note that if such a source file is not part of the project specified on the
14652 command line, the ^switches^switches^ found in package @code{Builder} of the
14653 project specified on the command line, if any, that are transmitted
14654 to the compiler will still be used, not those found in the project file of
14655 the source file.
14656
14657 @noindent
14658 When using a project file, you can also invoke @command{gnatmake} without
14659 explicitly specifying any main, and the effect depends on whether you have
14660 defined the @code{Main} attribute.  This attribute has a string list value,
14661 where each element in the list is the name of a source file (the file
14662 extension is optional) that contains a unit that can be a main subprogram.
14663
14664 If the @code{Main} attribute is defined in a project file as a non-empty
14665 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14666 line, then invoking @command{gnatmake} with this project file but without any
14667 main on the command line is equivalent to invoking @command{gnatmake} with all
14668 the file names in the @code{Main} attribute on the command line.
14669
14670 Example:
14671 @smallexample @c projectfile
14672 @group
14673    project Prj is
14674       for Main use ("main1", "main2", "main3");
14675    end Prj;
14676 @end group
14677 @end smallexample
14678
14679 @noindent
14680 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14681 is equivalent to
14682 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14683
14684 When the project attribute @code{Main} is not specified, or is specified
14685 as an empty string list, or when the switch @option{-u} is used on the command
14686 line, then invoking @command{gnatmake} with no main on the command line will
14687 result in all immediate sources of the project file being checked, and
14688 potentially recompiled. Depending on the presence of the switch @option{-u},
14689 sources from other project files on which the immediate sources of the main
14690 project file depend are also checked and potentially recompiled. In other
14691 words, the @option{-u} switch is applied to all of the immediate sources of the
14692 main project file.
14693
14694 When no main is specified on the command line and attribute @code{Main} exists
14695 and includes several mains, or when several mains are specified on the
14696 command line, the default ^switches^switches^ in package @code{Builder} will
14697 be used for all mains, even if there are specific ^switches^switches^
14698 specified for one or several mains.
14699
14700 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14701 the specific ^switches^switches^ for each main, if they are specified.
14702
14703 @node Library Project Files
14704 @subsubsection Library Project Files
14705
14706 @noindent
14707 When @command{gnatmake} is invoked with a main project file that is a library
14708 project file, it is not allowed to specify one or more mains on the command
14709 line.
14710
14711 @noindent
14712 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14713 ^-l^/ACTION=LINK^ have special meanings.
14714
14715 @itemize @bullet
14716 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14717 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14718 library.
14719
14720 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14721 to @command{gnatmake} that the binder generated file should be compiled
14722 (in the case of a stand-alone library) and that the library should be built.
14723
14724 @end itemize
14725
14726 @node The GNAT Driver and Project Files
14727 @subsection The GNAT Driver and Project Files
14728
14729 @noindent
14730 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14731 can benefit from project files:
14732 @command{^gnatbind^gnatbind^},
14733 @command{^gnatcheck^gnatcheck^}),
14734 @command{^gnatclean^gnatclean^}),
14735 @command{^gnatelim^gnatelim^},
14736 @command{^gnatfind^gnatfind^},
14737 @command{^gnatlink^gnatlink^},
14738 @command{^gnatls^gnatls^},
14739 @command{^gnatmetric^gnatmetric^},
14740 @command{^gnatpp^gnatpp^},
14741 @command{^gnatstub^gnatstub^},
14742 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14743 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14744 They must be invoked through the @command{gnat} driver.
14745
14746 The @command{gnat} driver is a wrapper that accepts a number of commands and
14747 calls the corresponding tool. It was designed initially for VMS platforms (to
14748 convert VMS qualifiers to Unix-style switches), but it is now available on all
14749 GNAT platforms.
14750
14751 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14752 (case insensitive):
14753
14754 @itemize @bullet
14755 @item
14756 BIND to invoke @command{^gnatbind^gnatbind^}
14757 @item
14758 CHOP to invoke @command{^gnatchop^gnatchop^}
14759 @item
14760 CLEAN to invoke @command{^gnatclean^gnatclean^}
14761 @item
14762 COMP or COMPILE to invoke the compiler
14763 @item
14764 ELIM to invoke @command{^gnatelim^gnatelim^}
14765 @item
14766 FIND to invoke @command{^gnatfind^gnatfind^}
14767 @item
14768 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14769 @item
14770 LINK to invoke @command{^gnatlink^gnatlink^}
14771 @item
14772 LS or LIST to invoke @command{^gnatls^gnatls^}
14773 @item
14774 MAKE to invoke @command{^gnatmake^gnatmake^}
14775 @item
14776 NAME to invoke @command{^gnatname^gnatname^}
14777 @item
14778 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14779 @item
14780 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14781 @item
14782 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14783 @item
14784 STUB to invoke @command{^gnatstub^gnatstub^}
14785 @item
14786 XREF to invoke @command{^gnatxref^gnatxref^}
14787 @end itemize
14788
14789 @noindent
14790 (note that the compiler is invoked using the command
14791 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14792
14793 @noindent
14794 On non-VMS platforms, between @command{gnat} and the command, two
14795 special switches may be used:
14796
14797 @itemize @bullet
14798 @item
14799 @command{-v} to display the invocation of the tool.
14800 @item
14801 @command{-dn} to prevent the @command{gnat} driver from removing
14802 the temporary files it has created. These temporary files are
14803 configuration files and temporary file list files.
14804 @end itemize
14805
14806 @noindent
14807 The command may be followed by switches and arguments for the invoked
14808 tool.
14809
14810 @smallexample
14811   gnat bind -C main.ali
14812   gnat ls -a main
14813   gnat chop foo.txt
14814 @end smallexample
14815
14816 @noindent
14817 Switches may also be put in text files, one switch per line, and the text
14818 files may be specified with their path name preceded by '@@'.
14819
14820 @smallexample
14821    gnat bind @@args.txt main.ali
14822 @end smallexample
14823
14824 @noindent
14825 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14826 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14827 (@option{^-P^/PROJECT_FILE^},
14828 @option{^-X^/EXTERNAL_REFERENCE^} and
14829 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14830 the switches of the invoking tool.
14831
14832 @noindent
14833 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14834 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14835 the immediate sources of the specified project file.
14836
14837 @noindent
14838 When GNAT METRIC is used with a project file, but with no source
14839 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14840 with all the immediate sources of the specified project file and with
14841 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14842 of the project.
14843
14844 @noindent
14845 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14846 a project file, no source is specified on the command line and
14847 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14848 the underlying tool (^gnatpp^gnatpp^ or
14849 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14850 not only for the immediate sources of the main project.
14851 @ifclear vms
14852 (-U stands for Universal or Union of the project files of the project tree)
14853 @end ifclear
14854
14855 @noindent
14856 For each of the following commands, there is optionally a corresponding
14857 package in the main project.
14858
14859 @itemize @bullet
14860 @item
14861 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14862
14863 @item
14864 package @code{Check} for command CHECK (invoking
14865 @code{^gnatcheck^gnatcheck^})
14866
14867 @item
14868 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14869
14870 @item
14871 package @code{Cross_Reference} for command XREF (invoking
14872 @code{^gnatxref^gnatxref^})
14873
14874 @item
14875 package @code{Eliminate} for command ELIM (invoking
14876 @code{^gnatelim^gnatelim^})
14877
14878 @item
14879 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14880
14881 @item
14882 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14883
14884 @item
14885 package @code{Gnatstub} for command STUB
14886 (invoking @code{^gnatstub^gnatstub^})
14887
14888 @item
14889 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14890
14891 @item
14892 package @code{Metrics} for command METRIC
14893 (invoking @code{^gnatmetric^gnatmetric^})
14894
14895 @item
14896 package @code{Pretty_Printer} for command PP or PRETTY
14897 (invoking @code{^gnatpp^gnatpp^})
14898
14899 @end itemize
14900
14901 @noindent
14902 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14903 a simple variable with a string list value. It contains ^switches^switches^
14904 for the invocation of @code{^gnatls^gnatls^}.
14905
14906 @smallexample @c projectfile
14907 @group
14908 project Proj1 is
14909    package gnatls is
14910       for ^Switches^Switches^
14911           use ("^-a^-a^",
14912                "^-v^-v^");
14913    end gnatls;
14914 end Proj1;
14915 @end group
14916 @end smallexample
14917
14918 @noindent
14919 All other packages have two attribute @code{^Switches^Switches^} and
14920 @code{^Default_Switches^Default_Switches^}.
14921
14922 @noindent
14923 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14924 source file name, that has a string list value: the ^switches^switches^ to be
14925 used when the tool corresponding to the package is invoked for the specific
14926 source file.
14927
14928 @noindent
14929 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14930 indexed by  the programming language that has a string list value.
14931 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14932 ^switches^switches^ for the invocation of the tool corresponding
14933 to the package, except if a specific @code{^Switches^Switches^} attribute
14934 is specified for the source file.
14935
14936 @smallexample @c projectfile
14937 @group
14938 project Proj is
14939
14940    for Source_Dirs use ("./**");
14941
14942    package gnatls is
14943       for ^Switches^Switches^ use
14944           ("^-a^-a^",
14945            "^-v^-v^");
14946    end gnatls;
14947 @end group
14948 @group
14949
14950    package Compiler is
14951       for ^Default_Switches^Default_Switches^ ("Ada")
14952           use ("^-gnatv^-gnatv^",
14953                "^-gnatwa^-gnatwa^");
14954    end Binder;
14955 @end group
14956 @group
14957
14958    package Binder is
14959       for ^Default_Switches^Default_Switches^ ("Ada")
14960           use ("^-C^-C^",
14961                "^-e^-e^");
14962    end Binder;
14963 @end group
14964 @group
14965
14966    package Linker is
14967       for ^Default_Switches^Default_Switches^ ("Ada")
14968           use ("^-C^-C^");
14969       for ^Switches^Switches^ ("main.adb")
14970           use ("^-C^-C^",
14971                "^-v^-v^",
14972                "^-v^-v^");
14973    end Linker;
14974 @end group
14975 @group
14976
14977    package Finder is
14978       for ^Default_Switches^Default_Switches^ ("Ada")
14979            use ("^-a^-a^",
14980                 "^-f^-f^");
14981    end Finder;
14982 @end group
14983 @group
14984
14985    package Cross_Reference is
14986       for ^Default_Switches^Default_Switches^ ("Ada")
14987           use ("^-a^-a^",
14988                "^-f^-f^",
14989                "^-d^-d^",
14990                "^-u^-u^");
14991    end Cross_Reference;
14992 end Proj;
14993 @end group
14994 @end smallexample
14995
14996 @noindent
14997 With the above project file, commands such as
14998
14999 @smallexample
15000    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15001    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15002    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15003    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15004    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15005 @end smallexample
15006
15007 @noindent
15008 will set up the environment properly and invoke the tool with the switches
15009 found in the package corresponding to the tool:
15010 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15011 except @code{^Switches^Switches^ ("main.adb")}
15012 for @code{^gnatlink^gnatlink^}.
15013 It is also possible to invoke some of the tools,
15014 @code{^gnatcheck^gnatcheck^}),
15015 @code{^gnatmetric^gnatmetric^}),
15016 and @code{^gnatpp^gnatpp^})
15017 on a set of project units thanks to the combination of the switches
15018 @option{-P}, @option{-U} and possibly the main unit when one is interested
15019 in its closure. For instance,
15020 @smallexample
15021 gnat metric -Pproj
15022 @end smallexample
15023 will compute the metrics for all the immediate units of project
15024 @code{proj}.
15025 @smallexample
15026 gnat metric -Pproj -U
15027 @end smallexample
15028 will compute the metrics for all the units of the closure of projects
15029 rooted at @code{proj}.
15030 @smallexample
15031 gnat metric -Pproj -U main_unit
15032 @end smallexample
15033 will compute the metrics for the closure of units rooted at
15034 @code{main_unit}. This last possibility relies implicitly
15035 on @command{gnatbind}'s option @option{-R}.
15036
15037 @c **********************
15038 @node An Extended Example
15039 @section An Extended Example
15040
15041 @noindent
15042 Suppose that we have two programs, @var{prog1} and @var{prog2},
15043 whose sources are in corresponding directories. We would like
15044 to build them with a single @command{gnatmake} command, and we want to place
15045 their object files into @file{build} subdirectories of the source directories.
15046 Furthermore, we want to have to have two separate subdirectories
15047 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15048 the object files compiled with different set of compilation flags.
15049
15050 In other words, we have the following structure:
15051
15052 @smallexample
15053 @group
15054    main
15055      |- prog1
15056      |    |- build
15057      |         | debug
15058      |         | release
15059      |- prog2
15060           |- build
15061                | debug
15062                | release
15063 @end group
15064 @end smallexample
15065
15066 @noindent
15067 Here are the project files that we must place in a directory @file{main}
15068 to maintain this structure:
15069
15070 @enumerate
15071
15072 @item We create a @code{Common} project with a package @code{Compiler} that
15073 specifies the compilation ^switches^switches^:
15074
15075 @smallexample
15076 File "common.gpr":
15077 @group
15078 @b{project} Common @b{is}
15079
15080    @b{for} Source_Dirs @b{use} (); -- No source files
15081 @end group
15082
15083 @group
15084    @b{type} Build_Type @b{is} ("release", "debug");
15085    Build : Build_Type := External ("BUILD", "debug");
15086 @end group
15087 @group
15088    @b{package} Compiler @b{is}
15089       @b{case} Build @b{is}
15090          @b{when} "release" =>
15091            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15092                    @b{use} ("^-O2^-O2^");
15093          @b{when} "debug"   =>
15094            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15095                    @b{use} ("^-g^-g^");
15096       @b{end case};
15097    @b{end} Compiler;
15098
15099 @b{end} Common;
15100 @end group
15101 @end smallexample
15102
15103 @item We create separate projects for the two programs:
15104
15105 @smallexample
15106 @group
15107 File "prog1.gpr":
15108
15109 @b{with} "common";
15110 @b{project} Prog1 @b{is}
15111
15112     @b{for} Source_Dirs @b{use} ("prog1");
15113     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15114
15115     @b{package} Compiler @b{renames} Common.Compiler;
15116
15117 @b{end} Prog1;
15118 @end group
15119 @end smallexample
15120
15121 @smallexample
15122 @group
15123 File "prog2.gpr":
15124
15125 @b{with} "common";
15126 @b{project} Prog2 @b{is}
15127
15128     @b{for} Source_Dirs @b{use} ("prog2");
15129     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15130
15131     @b{package} Compiler @b{renames} Common.Compiler;
15132
15133 @end group
15134 @b{end} Prog2;
15135 @end smallexample
15136
15137 @item We create a wrapping project @code{Main}:
15138
15139 @smallexample
15140 @group
15141 File "main.gpr":
15142
15143 @b{with} "common";
15144 @b{with} "prog1";
15145 @b{with} "prog2";
15146 @b{project} Main @b{is}
15147
15148    @b{package} Compiler @b{renames} Common.Compiler;
15149
15150 @b{end} Main;
15151 @end group
15152 @end smallexample
15153
15154 @item Finally we need to create a dummy procedure that @code{with}s (either
15155 explicitly or implicitly) all the sources of our two programs.
15156
15157 @end enumerate
15158
15159 @noindent
15160 Now we can build the programs using the command
15161
15162 @smallexample
15163    gnatmake ^-P^/PROJECT_FILE=^main dummy
15164 @end smallexample
15165
15166 @noindent
15167 for the Debug mode, or
15168
15169 @ifclear vms
15170 @smallexample
15171    gnatmake -Pmain -XBUILD=release
15172 @end smallexample
15173 @end ifclear
15174
15175 @ifset vms
15176 @smallexample
15177    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15178 @end smallexample
15179 @end ifset
15180
15181 @noindent
15182 for the Release mode.
15183
15184 @c ********************************
15185 @c * Project File Complete Syntax *
15186 @c ********************************
15187
15188 @node Project File Complete Syntax
15189 @section Project File Complete Syntax
15190
15191 @smallexample
15192 project ::=
15193   context_clause project_declaration
15194
15195 context_clause ::=
15196   @{with_clause@}
15197
15198 with_clause ::=
15199   @b{with} path_name @{ , path_name @} ;
15200
15201 path_name ::=
15202    string_literal
15203
15204 project_declaration ::=
15205   simple_project_declaration | project_extension
15206
15207 simple_project_declaration ::=
15208   @b{project} <project_>simple_name @b{is}
15209     @{declarative_item@}
15210   @b{end} <project_>simple_name;
15211
15212 project_extension ::=
15213   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15214     @{declarative_item@}
15215   @b{end} <project_>simple_name;
15216
15217 declarative_item ::=
15218   package_declaration |
15219   typed_string_declaration |
15220   other_declarative_item
15221
15222 package_declaration ::=
15223   package_spec | package_renaming
15224
15225 package_spec ::=
15226   @b{package} package_identifier @b{is}
15227     @{simple_declarative_item@}
15228   @b{end} package_identifier ;
15229
15230 package_identifier ::=
15231   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15232   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15233   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15234
15235 package_renaming ::==
15236   @b{package} package_identifier @b{renames}
15237        <project_>simple_name.package_identifier ;
15238
15239 typed_string_declaration ::=
15240   @b{type} <typed_string_>_simple_name @b{is}
15241    ( string_literal @{, string_literal@} );
15242
15243 other_declarative_item ::=
15244   attribute_declaration |
15245   typed_variable_declaration |
15246   variable_declaration |
15247   case_construction
15248
15249 attribute_declaration ::=
15250   full_associative_array_declaration |
15251   @b{for} attribute_designator @b{use} expression ;
15252
15253 full_associative_array_declaration ::=
15254   @b{for} <associative_array_attribute_>simple_name @b{use}
15255   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15256
15257 attribute_designator ::=
15258   <simple_attribute_>simple_name |
15259   <associative_array_attribute_>simple_name ( string_literal )
15260
15261 typed_variable_declaration ::=
15262   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15263
15264 variable_declaration ::=
15265   <variable_>simple_name := expression;
15266
15267 expression ::=
15268   term @{& term@}
15269
15270 term ::=
15271   literal_string |
15272   string_list |
15273   <variable_>name |
15274   external_value |
15275   attribute_reference
15276
15277 string_literal ::=
15278   (same as Ada)
15279
15280 string_list ::=
15281   ( <string_>expression @{ , <string_>expression @} )
15282
15283 external_value ::=
15284   @b{external} ( string_literal [, string_literal] )
15285
15286 attribute_reference ::=
15287   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15288
15289 attribute_prefix ::=
15290   @b{project} |
15291   <project_>simple_name | package_identifier |
15292   <project_>simple_name . package_identifier
15293
15294 case_construction ::=
15295   @b{case} <typed_variable_>name @b{is}
15296     @{case_item@}
15297   @b{end case} ;
15298
15299 case_item ::=
15300   @b{when} discrete_choice_list =>
15301       @{case_construction | attribute_declaration@}
15302
15303 discrete_choice_list ::=
15304   string_literal @{| string_literal@} |
15305   @b{others}
15306
15307 name ::=
15308   simple_name @{. simple_name@}
15309
15310 simple_name ::=
15311   identifier (same as Ada)
15312
15313 @end smallexample
15314
15315 @node The Cross-Referencing Tools gnatxref and gnatfind
15316 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15317 @findex gnatxref
15318 @findex gnatfind
15319
15320 @noindent
15321 The compiler generates cross-referencing information (unless
15322 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15323 This information indicates where in the source each entity is declared and
15324 referenced. Note that entities in package Standard are not included, but
15325 entities in all other predefined units are included in the output.
15326
15327 Before using any of these two tools, you need to compile successfully your
15328 application, so that GNAT gets a chance to generate the cross-referencing
15329 information.
15330
15331 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15332 information to provide the user with the capability to easily locate the
15333 declaration and references to an entity. These tools are quite similar,
15334 the difference being that @code{gnatfind} is intended for locating
15335 definitions and/or references to a specified entity or entities, whereas
15336 @code{gnatxref} is oriented to generating a full report of all
15337 cross-references.
15338
15339 To use these tools, you must not compile your application using the
15340 @option{-gnatx} switch on the @command{gnatmake} command line
15341 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15342 information will not be generated.
15343
15344 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15345 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15346
15347 @menu
15348 * gnatxref Switches::
15349 * gnatfind Switches::
15350 * Project Files for gnatxref and gnatfind::
15351 * Regular Expressions in gnatfind and gnatxref::
15352 * Examples of gnatxref Usage::
15353 * Examples of gnatfind Usage::
15354 @end menu
15355
15356 @node gnatxref Switches
15357 @section @code{gnatxref} Switches
15358
15359 @noindent
15360 The command invocation for @code{gnatxref} is:
15361 @smallexample
15362 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15363 @end smallexample
15364
15365 @noindent
15366 where
15367
15368 @table @var
15369 @item sourcefile1
15370 @itemx sourcefile2
15371 identifies the source files for which a report is to be generated. The
15372 ``with''ed units will be processed too. You must provide at least one file.
15373
15374 These file names are considered to be regular expressions, so for instance
15375 specifying @file{source*.adb} is the same as giving every file in the current
15376 directory whose name starts with @file{source} and whose extension is
15377 @file{adb}.
15378
15379 You shouldn't specify any directory name, just base names. @command{gnatxref}
15380 and @command{gnatfind} will be able to locate these files by themselves using
15381 the source path. If you specify directories, no result is produced.
15382
15383 @end table
15384
15385 @noindent
15386 The switches can be:
15387 @table @option
15388 @c !sort!
15389 @item --version
15390 @cindex @option{--version} @command{gnatxref}
15391 Display Copyright and version, then exit disregarding all other options.
15392
15393 @item --help
15394 @cindex @option{--help} @command{gnatxref}
15395 If @option{--version} was not used, display usage, then exit disregarding
15396 all other options.
15397
15398 @item ^-a^/ALL_FILES^
15399 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15400 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15401 the read-only files found in the library search path. Otherwise, these files
15402 will be ignored. This option can be used to protect Gnat sources or your own
15403 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15404 much faster, and their output much smaller. Read-only here refers to access
15405 or permissions status in the file system for the current user.
15406
15407 @item -aIDIR
15408 @cindex @option{-aIDIR} (@command{gnatxref})
15409 When looking for source files also look in directory DIR. The order in which
15410 source file search is undertaken is the same as for @command{gnatmake}.
15411
15412 @item -aODIR
15413 @cindex @option{-aODIR} (@command{gnatxref})
15414 When searching for library and object files, look in directory
15415 DIR. The order in which library files are searched is the same as for
15416 @command{gnatmake}.
15417
15418 @item -nostdinc
15419 @cindex @option{-nostdinc} (@command{gnatxref})
15420 Do not look for sources in the system default directory.
15421
15422 @item -nostdlib
15423 @cindex @option{-nostdlib} (@command{gnatxref})
15424 Do not look for library files in the system default directory.
15425
15426 @item --RTS=@var{rts-path}
15427 @cindex @option{--RTS} (@command{gnatxref})
15428 Specifies the default location of the runtime library. Same meaning as the
15429 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15430
15431 @item ^-d^/DERIVED_TYPES^
15432 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15433 If this switch is set @code{gnatxref} will output the parent type
15434 reference for each matching derived types.
15435
15436 @item ^-f^/FULL_PATHNAME^
15437 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15438 If this switch is set, the output file names will be preceded by their
15439 directory (if the file was found in the search path). If this switch is
15440 not set, the directory will not be printed.
15441
15442 @item ^-g^/IGNORE_LOCALS^
15443 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15444 If this switch is set, information is output only for library-level
15445 entities, ignoring local entities. The use of this switch may accelerate
15446 @code{gnatfind} and @code{gnatxref}.
15447
15448 @item -IDIR
15449 @cindex @option{-IDIR} (@command{gnatxref})
15450 Equivalent to @samp{-aODIR -aIDIR}.
15451
15452 @item -pFILE
15453 @cindex @option{-pFILE} (@command{gnatxref})
15454 Specify a project file to use @xref{Project Files}.
15455 If you need to use the @file{.gpr}
15456 project files, you should use gnatxref through the GNAT driver
15457 (@command{gnat xref -Pproject}).
15458
15459 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15460 project file in the current directory.
15461
15462 If a project file is either specified or found by the tools, then the content
15463 of the source directory and object directory lines are added as if they
15464 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15465 and @samp{^-aO^OBJECT_SEARCH^}.
15466 @item ^-u^/UNUSED^
15467 Output only unused symbols. This may be really useful if you give your
15468 main compilation unit on the command line, as @code{gnatxref} will then
15469 display every unused entity and 'with'ed package.
15470
15471 @ifclear vms
15472 @item -v
15473 Instead of producing the default output, @code{gnatxref} will generate a
15474 @file{tags} file that can be used by vi. For examples how to use this
15475 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15476 to the standard output, thus you will have to redirect it to a file.
15477 @end ifclear
15478
15479 @end table
15480
15481 @noindent
15482 All these switches may be in any order on the command line, and may even
15483 appear after the file names. They need not be separated by spaces, thus
15484 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15485 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15486
15487 @node gnatfind Switches
15488 @section @code{gnatfind} Switches
15489
15490 @noindent
15491 The command line for @code{gnatfind} is:
15492
15493 @smallexample
15494 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15495       @r{[}@var{file1} @var{file2} @dots{}]
15496 @end smallexample
15497
15498 @noindent
15499 where
15500
15501 @table @var
15502 @item pattern
15503 An entity will be output only if it matches the regular expression found
15504 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15505
15506 Omitting the pattern is equivalent to specifying @samp{*}, which
15507 will match any entity. Note that if you do not provide a pattern, you
15508 have to provide both a sourcefile and a line.
15509
15510 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15511 for matching purposes. At the current time there is no support for
15512 8-bit codes other than Latin-1, or for wide characters in identifiers.
15513
15514 @item sourcefile
15515 @code{gnatfind} will look for references, bodies or declarations
15516 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15517 and column @var{column}. See @ref{Examples of gnatfind Usage}
15518 for syntax examples.
15519
15520 @item line
15521 is a decimal integer identifying the line number containing
15522 the reference to the entity (or entities) to be located.
15523
15524 @item column
15525 is a decimal integer identifying the exact location on the
15526 line of the first character of the identifier for the
15527 entity reference. Columns are numbered from 1.
15528
15529 @item file1 file2 @dots{}
15530 The search will be restricted to these source files. If none are given, then
15531 the search will be done for every library file in the search path.
15532 These file must appear only after the pattern or sourcefile.
15533
15534 These file names are considered to be regular expressions, so for instance
15535 specifying @file{source*.adb} is the same as giving every file in the current
15536 directory whose name starts with @file{source} and whose extension is
15537 @file{adb}.
15538
15539 The location of the spec of the entity will always be displayed, even if it
15540 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15541 occurrences of the entity in the separate units of the ones given on the
15542 command line will also be displayed.
15543
15544 Note that if you specify at least one file in this part, @code{gnatfind} may
15545 sometimes not be able to find the body of the subprograms.
15546
15547 @end table
15548
15549 @noindent
15550 At least one of 'sourcefile' or 'pattern' has to be present on
15551 the command line.
15552
15553 The following switches are available:
15554 @table @option
15555 @c !sort!
15556
15557 @cindex @option{--version} @command{gnatfind}
15558 Display Copyright and version, then exit disregarding all other options.
15559
15560 @item --help
15561 @cindex @option{--help} @command{gnatfind}
15562 If @option{--version} was not used, display usage, then exit disregarding
15563 all other options.
15564
15565 @item ^-a^/ALL_FILES^
15566 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15567 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15568 the read-only files found in the library search path. Otherwise, these files
15569 will be ignored. This option can be used to protect Gnat sources or your own
15570 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15571 much faster, and their output much smaller. Read-only here refers to access
15572 or permission status in the file system for the current user.
15573
15574 @item -aIDIR
15575 @cindex @option{-aIDIR} (@command{gnatfind})
15576 When looking for source files also look in directory DIR. The order in which
15577 source file search is undertaken is the same as for @command{gnatmake}.
15578
15579 @item -aODIR
15580 @cindex @option{-aODIR} (@command{gnatfind})
15581 When searching for library and object files, look in directory
15582 DIR. The order in which library files are searched is the same as for
15583 @command{gnatmake}.
15584
15585 @item -nostdinc
15586 @cindex @option{-nostdinc} (@command{gnatfind})
15587 Do not look for sources in the system default directory.
15588
15589 @item -nostdlib
15590 @cindex @option{-nostdlib} (@command{gnatfind})
15591 Do not look for library files in the system default directory.
15592
15593 @item --ext=@var{extension}
15594 @cindex @option{--ext} (@command{gnatfind})
15595 Specify an alternate ali file extension. The default is @code{ali} and other
15596 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15597 switch. Note that if this switch overrides the default, which means that only
15598 the new extension will be considered.
15599
15600 @item --RTS=@var{rts-path}
15601 @cindex @option{--RTS} (@command{gnatfind})
15602 Specifies the default location of the runtime library. Same meaning as the
15603 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15604
15605 @item ^-d^/DERIVED_TYPE_INFORMATION^
15606 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15607 If this switch is set, then @code{gnatfind} will output the parent type
15608 reference for each matching derived types.
15609
15610 @item ^-e^/EXPRESSIONS^
15611 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15612 By default, @code{gnatfind} accept the simple regular expression set for
15613 @samp{pattern}. If this switch is set, then the pattern will be
15614 considered as full Unix-style regular expression.
15615
15616 @item ^-f^/FULL_PATHNAME^
15617 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15618 If this switch is set, the output file names will be preceded by their
15619 directory (if the file was found in the search path). If this switch is
15620 not set, the directory will not be printed.
15621
15622 @item ^-g^/IGNORE_LOCALS^
15623 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15624 If this switch is set, information is output only for library-level
15625 entities, ignoring local entities. The use of this switch may accelerate
15626 @code{gnatfind} and @code{gnatxref}.
15627
15628 @item -IDIR
15629 @cindex @option{-IDIR} (@command{gnatfind})
15630 Equivalent to @samp{-aODIR -aIDIR}.
15631
15632 @item -pFILE
15633 @cindex @option{-pFILE} (@command{gnatfind})
15634 Specify a project file (@pxref{Project Files}) to use.
15635 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15636 project file in the current directory.
15637
15638 If a project file is either specified or found by the tools, then the content
15639 of the source directory and object directory lines are added as if they
15640 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15641 @samp{^-aO^/OBJECT_SEARCH^}.
15642
15643 @item ^-r^/REFERENCES^
15644 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15645 By default, @code{gnatfind} will output only the information about the
15646 declaration, body or type completion of the entities. If this switch is
15647 set, the @code{gnatfind} will locate every reference to the entities in
15648 the files specified on the command line (or in every file in the search
15649 path if no file is given on the command line).
15650
15651 @item ^-s^/PRINT_LINES^
15652 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15653 If this switch is set, then @code{gnatfind} will output the content
15654 of the Ada source file lines were the entity was found.
15655
15656 @item ^-t^/TYPE_HIERARCHY^
15657 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15658 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15659 the specified type. It act like -d option but recursively from parent
15660 type to parent type. When this switch is set it is not possible to
15661 specify more than one file.
15662
15663 @end table
15664
15665 @noindent
15666 All these switches may be in any order on the command line, and may even
15667 appear after the file names. They need not be separated by spaces, thus
15668 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15669 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15670
15671 As stated previously, gnatfind will search in every directory in the
15672 search path. You can force it to look only in the current directory if
15673 you specify @code{*} at the end of the command line.
15674
15675 @node Project Files for gnatxref and gnatfind
15676 @section Project Files for @command{gnatxref} and @command{gnatfind}
15677
15678 @noindent
15679 Project files allow a programmer to specify how to compile its
15680 application, where to find sources, etc.  These files are used
15681 @ifclear vms
15682 primarily by GPS, but they can also be used
15683 @end ifclear
15684 by the two tools
15685 @code{gnatxref} and @code{gnatfind}.
15686
15687 A project file name must end with @file{.gpr}. If a single one is
15688 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15689 extract the information from it. If multiple project files are found, none of
15690 them is read, and you have to use the @samp{-p} switch to specify the one
15691 you want to use.
15692
15693 The following lines can be included, even though most of them have default
15694 values which can be used in most cases.
15695 The lines can be entered in any order in the file.
15696 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15697 each line. If you have multiple instances, only the last one is taken into
15698 account.
15699
15700 @table @code
15701 @item src_dir=DIR
15702 [default: @code{"^./^[]^"}]
15703 specifies a directory where to look for source files. Multiple @code{src_dir}
15704 lines can be specified and they will be searched in the order they
15705 are specified.
15706
15707 @item obj_dir=DIR
15708 [default: @code{"^./^[]^"}]
15709 specifies a directory where to look for object and library files. Multiple
15710 @code{obj_dir} lines can be specified, and they will be searched in the order
15711 they are specified
15712
15713 @item comp_opt=SWITCHES
15714 [default: @code{""}]
15715 creates a variable which can be referred to subsequently by using
15716 the @code{$@{comp_opt@}} notation. This is intended to store the default
15717 switches given to @command{gnatmake} and @command{gcc}.
15718
15719 @item bind_opt=SWITCHES
15720 [default: @code{""}]
15721 creates a variable which can be referred to subsequently by using
15722 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15723 switches given to @command{gnatbind}.
15724
15725 @item link_opt=SWITCHES
15726 [default: @code{""}]
15727 creates a variable which can be referred to subsequently by using
15728 the @samp{$@{link_opt@}} notation. This is intended to store the default
15729 switches given to @command{gnatlink}.
15730
15731 @item main=EXECUTABLE
15732 [default: @code{""}]
15733 specifies the name of the executable for the application. This variable can
15734 be referred to in the following lines by using the @samp{$@{main@}} notation.
15735
15736 @ifset vms
15737 @item comp_cmd=COMMAND
15738 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15739 @end ifset
15740 @ifclear vms
15741 @item comp_cmd=COMMAND
15742 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15743 @end ifclear
15744 specifies the command used to compile a single file in the application.
15745
15746 @ifset vms
15747 @item make_cmd=COMMAND
15748 [default: @code{"GNAT MAKE $@{main@}
15749 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15750 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15751 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15752 @end ifset
15753 @ifclear vms
15754 @item make_cmd=COMMAND
15755 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15756 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15757 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15758 @end ifclear
15759 specifies the command used to recompile the whole application.
15760
15761 @item run_cmd=COMMAND
15762 [default: @code{"$@{main@}"}]
15763 specifies the command used to run the application.
15764
15765 @item debug_cmd=COMMAND
15766 [default: @code{"gdb $@{main@}"}]
15767 specifies the command used to debug the application
15768
15769 @end table
15770
15771 @noindent
15772 @command{gnatxref} and @command{gnatfind} only take into account the
15773 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15774
15775 @node Regular Expressions in gnatfind and gnatxref
15776 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15777
15778 @noindent
15779 As specified in the section about @command{gnatfind}, the pattern can be a
15780 regular expression. Actually, there are to set of regular expressions
15781 which are recognized by the program:
15782
15783 @table @code
15784 @item globbing patterns
15785 These are the most usual regular expression. They are the same that you
15786 generally used in a Unix shell command line, or in a DOS session.
15787
15788 Here is a more formal grammar:
15789 @smallexample
15790 @group
15791 @iftex
15792 @leftskip=.5cm
15793 @end iftex
15794 regexp ::= term
15795 term   ::= elmt            -- matches elmt
15796 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15797 term   ::= *               -- any string of 0 or more characters
15798 term   ::= ?               -- matches any character
15799 term   ::= [char @{char@}]   -- matches any character listed
15800 term   ::= [char - char]   -- matches any character in range
15801 @end group
15802 @end smallexample
15803
15804 @item full regular expression
15805 The second set of regular expressions is much more powerful. This is the
15806 type of regular expressions recognized by utilities such a @file{grep}.
15807
15808 The following is the form of a regular expression, expressed in Ada
15809 reference manual style BNF is as follows
15810
15811 @smallexample
15812 @iftex
15813 @leftskip=.5cm
15814 @end iftex
15815 @group
15816 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15817
15818 term ::= item @{item@}       -- concatenation (item then item)
15819
15820 item ::= elmt              -- match elmt
15821 item ::= elmt *            -- zero or more elmt's
15822 item ::= elmt +            -- one or more elmt's
15823 item ::= elmt ?            -- matches elmt or nothing
15824 @end group
15825 @group
15826 elmt ::= nschar            -- matches given character
15827 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15828 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15829 elmt ::= [char - char]     -- matches chars in given range
15830 elmt ::= \ char            -- matches given character
15831 elmt ::= .                 -- matches any single character
15832 elmt ::= ( regexp )        -- parens used for grouping
15833
15834 char ::= any character, including special characters
15835 nschar ::= any character except ()[].*+?^^^
15836 @end group
15837 @end smallexample
15838
15839 Following are a few examples:
15840
15841 @table @samp
15842 @item abcde|fghi
15843 will match any of the two strings @samp{abcde} and @samp{fghi},
15844
15845 @item abc*d
15846 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15847 @samp{abcccd}, and so on,
15848
15849 @item [a-z]+
15850 will match any string which has only lowercase characters in it (and at
15851 least one character.
15852
15853 @end table
15854 @end table
15855
15856 @node Examples of gnatxref Usage
15857 @section Examples of @code{gnatxref} Usage
15858
15859 @subsection General Usage
15860
15861 @noindent
15862 For the following examples, we will consider the following units:
15863
15864 @smallexample @c ada
15865 @group
15866 @cartouche
15867 main.ads:
15868 1: with Bar;
15869 2: package Main is
15870 3:     procedure Foo (B : in Integer);
15871 4:     C : Integer;
15872 5: private
15873 6:     D : Integer;
15874 7: end Main;
15875
15876 main.adb:
15877 1: package body Main is
15878 2:     procedure Foo (B : in Integer) is
15879 3:     begin
15880 4:        C := B;
15881 5:        D := B;
15882 6:        Bar.Print (B);
15883 7:        Bar.Print (C);
15884 8:     end Foo;
15885 9: end Main;
15886
15887 bar.ads:
15888 1: package Bar is
15889 2:     procedure Print (B : Integer);
15890 3: end bar;
15891 @end cartouche
15892 @end group
15893 @end smallexample
15894
15895 @table @code
15896
15897 @noindent
15898 The first thing to do is to recompile your application (for instance, in
15899 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15900 the cross-referencing information.
15901 You can then issue any of the following commands:
15902
15903 @item gnatxref main.adb
15904 @code{gnatxref} generates cross-reference information for main.adb
15905 and every unit 'with'ed by main.adb.
15906
15907 The output would be:
15908 @smallexample
15909 @iftex
15910 @leftskip=0cm
15911 @end iftex
15912 B                                                      Type: Integer
15913   Decl: bar.ads           2:22
15914 B                                                      Type: Integer
15915   Decl: main.ads          3:20
15916   Body: main.adb          2:20
15917   Ref:  main.adb          4:13     5:13     6:19
15918 Bar                                                    Type: Unit
15919   Decl: bar.ads           1:9
15920   Ref:  main.adb          6:8      7:8
15921        main.ads           1:6
15922 C                                                      Type: Integer
15923   Decl: main.ads          4:5
15924   Modi: main.adb          4:8
15925   Ref:  main.adb          7:19
15926 D                                                      Type: Integer
15927   Decl: main.ads          6:5
15928   Modi: main.adb          5:8
15929 Foo                                                    Type: Unit
15930   Decl: main.ads          3:15
15931   Body: main.adb          2:15
15932 Main                                                    Type: Unit
15933   Decl: main.ads          2:9
15934   Body: main.adb          1:14
15935 Print                                                   Type: Unit
15936   Decl: bar.ads           2:15
15937   Ref:  main.adb          6:12     7:12
15938 @end smallexample
15939
15940 @noindent
15941 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15942 its body is in main.adb, line 1, column 14 and is not referenced any where.
15943
15944 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15945 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15946
15947 @item gnatxref package1.adb package2.ads
15948 @code{gnatxref} will generates cross-reference information for
15949 package1.adb, package2.ads and any other package 'with'ed by any
15950 of these.
15951
15952 @end table
15953
15954 @ifclear vms
15955 @subsection Using gnatxref with vi
15956
15957 @code{gnatxref} can generate a tags file output, which can be used
15958 directly from @command{vi}. Note that the standard version of @command{vi}
15959 will not work properly with overloaded symbols. Consider using another
15960 free implementation of @command{vi}, such as @command{vim}.
15961
15962 @smallexample
15963 $ gnatxref -v gnatfind.adb > tags
15964 @end smallexample
15965
15966 @noindent
15967 will generate the tags file for @code{gnatfind} itself (if the sources
15968 are in the search path!).
15969
15970 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15971 (replacing @var{entity} by whatever you are looking for), and vi will
15972 display a new file with the corresponding declaration of entity.
15973 @end ifclear
15974
15975 @node Examples of gnatfind Usage
15976 @section Examples of @code{gnatfind} Usage
15977
15978 @table @code
15979
15980 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15981 Find declarations for all entities xyz referenced at least once in
15982 main.adb. The references are search in every library file in the search
15983 path.
15984
15985 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15986 switch is set)
15987
15988 The output will look like:
15989 @smallexample
15990 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15991 ^directory/^[directory]^main.adb:24:10: xyz <= body
15992 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15993 @end smallexample
15994
15995 @noindent
15996 that is to say, one of the entities xyz found in main.adb is declared at
15997 line 12 of main.ads (and its body is in main.adb), and another one is
15998 declared at line 45 of foo.ads
15999
16000 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16001 This is the same command as the previous one, instead @code{gnatfind} will
16002 display the content of the Ada source file lines.
16003
16004 The output will look like:
16005
16006 @smallexample
16007 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16008    procedure xyz;
16009 ^directory/^[directory]^main.adb:24:10: xyz <= body
16010    procedure xyz is
16011 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16012    xyz : Integer;
16013 @end smallexample
16014
16015 @noindent
16016 This can make it easier to find exactly the location your are looking
16017 for.
16018
16019 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16020 Find references to all entities containing an x that are
16021 referenced on line 123 of main.ads.
16022 The references will be searched only in main.ads and foo.adb.
16023
16024 @item gnatfind main.ads:123
16025 Find declarations and bodies for all entities that are referenced on
16026 line 123 of main.ads.
16027
16028 This is the same as @code{gnatfind "*":main.adb:123}.
16029
16030 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16031 Find the declaration for the entity referenced at column 45 in
16032 line 123 of file main.adb in directory mydir. Note that it
16033 is usual to omit the identifier name when the column is given,
16034 since the column position identifies a unique reference.
16035
16036 The column has to be the beginning of the identifier, and should not
16037 point to any character in the middle of the identifier.
16038
16039 @end table
16040
16041 @c *********************************
16042 @node The GNAT Pretty-Printer gnatpp
16043 @chapter The GNAT Pretty-Printer @command{gnatpp}
16044 @findex gnatpp
16045 @cindex Pretty-Printer
16046
16047 @noindent
16048 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16049 for source reformatting / pretty-printing.
16050 It takes an Ada source file as input and generates a reformatted
16051 version as output.
16052 You can specify various style directives via switches; e.g.,
16053 identifier case conventions, rules of indentation, and comment layout.
16054
16055 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16056 tree for the input source and thus requires the input to be syntactically and
16057 semantically legal.
16058 If this condition is not met, @command{gnatpp} will terminate with an
16059 error message; no output file will be generated.
16060
16061 If the source files presented to @command{gnatpp} contain
16062 preprocessing directives, then the output file will
16063 correspond to the generated source after all
16064 preprocessing is carried out. There is no way
16065 using @command{gnatpp} to obtain pretty printed files that
16066 include the preprocessing directives.
16067
16068 If the compilation unit
16069 contained in the input source depends semantically upon units located
16070 outside the current directory, you have to provide the source search path
16071 when invoking @command{gnatpp}, if these units are contained in files with
16072 names that do not follow the GNAT file naming rules, you have to provide
16073 the configuration file describing the corresponding naming scheme;
16074 see the description of the @command{gnatpp}
16075 switches below. Another possibility is to use a project file and to
16076 call @command{gnatpp} through the @command{gnat} driver
16077
16078 The @command{gnatpp} command has the form
16079
16080 @smallexample
16081 $ gnatpp @ovar{switches} @var{filename}
16082 @end smallexample
16083
16084 @noindent
16085 where
16086 @itemize @bullet
16087 @item
16088 @var{switches} is an optional sequence of switches defining such properties as
16089 the formatting rules, the source search path, and the destination for the
16090 output source file
16091
16092 @item
16093 @var{filename} is the name (including the extension) of the source file to
16094 reformat; ``wildcards'' or several file names on the same gnatpp command are
16095 allowed.  The file name may contain path information; it does not have to
16096 follow the GNAT file naming rules
16097 @end itemize
16098
16099 @menu
16100 * Switches for gnatpp::
16101 * Formatting Rules::
16102 @end menu
16103
16104 @node Switches for gnatpp
16105 @section Switches for @command{gnatpp}
16106
16107 @noindent
16108 The following subsections describe the various switches accepted by
16109 @command{gnatpp}, organized by category.
16110
16111 @ifclear vms
16112 You specify a switch by supplying a name and generally also a value.
16113 In many cases the values for a switch with a given name are incompatible with
16114 each other
16115 (for example the switch that controls the casing of a reserved word may have
16116 exactly one value: upper case, lower case, or
16117 mixed case) and thus exactly one such switch can be in effect for an
16118 invocation of @command{gnatpp}.
16119 If more than one is supplied, the last one is used.
16120 However, some values for the same switch are mutually compatible.
16121 You may supply several such switches to @command{gnatpp}, but then
16122 each must be specified in full, with both the name and the value.
16123 Abbreviated forms (the name appearing once, followed by each value) are
16124 not permitted.
16125 For example, to set
16126 the alignment of the assignment delimiter both in declarations and in
16127 assignment statements, you must write @option{-A2A3}
16128 (or @option{-A2 -A3}), but not @option{-A23}.
16129 @end ifclear
16130
16131 @ifset vms
16132 In many cases the set of options for a given qualifier are incompatible with
16133 each other (for example the qualifier that controls the casing of a reserved
16134 word may have exactly one option, which specifies either upper case, lower
16135 case, or mixed case), and thus exactly one such option can be in effect for
16136 an invocation of @command{gnatpp}.
16137 If more than one is supplied, the last one is used.
16138 However, some qualifiers have options that are mutually compatible,
16139 and then you may then supply several such options when invoking
16140 @command{gnatpp}.
16141 @end ifset
16142
16143 In most cases, it is obvious whether or not the
16144 ^values for a switch with a given name^options for a given qualifier^
16145 are compatible with each other.
16146 When the semantics might not be evident, the summaries below explicitly
16147 indicate the effect.
16148
16149 @menu
16150 * Alignment Control::
16151 * Casing Control::
16152 * Construct Layout Control::
16153 * General Text Layout Control::
16154 * Other Formatting Options::
16155 * Setting the Source Search Path::
16156 * Output File Control::
16157 * Other gnatpp Switches::
16158 @end menu
16159
16160 @node Alignment Control
16161 @subsection Alignment Control
16162 @cindex Alignment control in @command{gnatpp}
16163
16164 @noindent
16165 Programs can be easier to read if certain constructs are vertically aligned.
16166 By default all alignments are set ON.
16167 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16168 OFF, and then use one or more of the other
16169 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16170 to activate alignment for specific constructs.
16171
16172 @table @option
16173 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16174
16175 @ifset vms
16176 @item /ALIGN=ON
16177 Set all alignments to ON
16178 @end ifset
16179
16180 @item ^-A0^/ALIGN=OFF^
16181 Set all alignments to OFF
16182
16183 @item ^-A1^/ALIGN=COLONS^
16184 Align @code{:} in declarations
16185
16186 @item ^-A2^/ALIGN=DECLARATIONS^
16187 Align @code{:=} in initializations in declarations
16188
16189 @item ^-A3^/ALIGN=STATEMENTS^
16190 Align @code{:=} in assignment statements
16191
16192 @item ^-A4^/ALIGN=ARROWS^
16193 Align @code{=>} in associations
16194
16195 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16196 Align @code{at} keywords in the component clauses in record
16197 representation clauses
16198 @end table
16199
16200 @noindent
16201 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16202 is allowed.
16203
16204 @node Casing Control
16205 @subsection Casing Control
16206 @cindex Casing control in @command{gnatpp}
16207
16208 @noindent
16209 @command{gnatpp} allows you to specify the casing for reserved words,
16210 pragma names, attribute designators and identifiers.
16211 For identifiers you may define a
16212 general rule for name casing but also override this rule
16213 via a set of dictionary files.
16214
16215 Three types of casing are supported: lower case, upper case, and mixed case.
16216 Lower and upper case are self-explanatory (but since some letters in
16217 Latin1 and other GNAT-supported character sets
16218 exist only in lower-case form, an upper case conversion will have no
16219 effect on them.)
16220 ``Mixed case'' means that the first letter, and also each letter immediately
16221 following an underscore, are converted to their uppercase forms;
16222 all the other letters are converted to their lowercase forms.
16223
16224 @table @option
16225 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16226 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16227 Attribute designators are lower case
16228
16229 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16230 Attribute designators are upper case
16231
16232 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16233 Attribute designators are mixed case (this is the default)
16234
16235 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16236 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16237 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16238 lower case (this is the default)
16239
16240 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16241 Keywords are upper case
16242
16243 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16244 @item ^-nD^/NAME_CASING=AS_DECLARED^
16245 Name casing for defining occurrences are as they appear in the source file
16246 (this is the default)
16247
16248 @item ^-nU^/NAME_CASING=UPPER_CASE^
16249 Names are in upper case
16250
16251 @item ^-nL^/NAME_CASING=LOWER_CASE^
16252 Names are in lower case
16253
16254 @item ^-nM^/NAME_CASING=MIXED_CASE^
16255 Names are in mixed case
16256
16257 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16258 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16259 Pragma names are lower case
16260
16261 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16262 Pragma names are upper case
16263
16264 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16265 Pragma names are mixed case (this is the default)
16266
16267 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16268 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16269 Use @var{file} as a @emph{dictionary file} that defines
16270 the casing for a set of specified names,
16271 thereby overriding the effect on these names by
16272 any explicit or implicit
16273 ^-n^/NAME_CASING^ switch.
16274 To supply more than one dictionary file,
16275 use ^several @option{-D} switches^a list of files as options^.
16276
16277 @noindent
16278 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16279 to define the casing for the Ada predefined names and
16280 the names declared in the GNAT libraries.
16281
16282 @item ^-D-^/SPECIFIC_CASING^
16283 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16284 Do not use the default dictionary file;
16285 instead, use the casing
16286 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16287 dictionary file(s)
16288 @end table
16289
16290 @noindent
16291 The structure of a dictionary file, and details on the conventions
16292 used in the default dictionary file, are defined in @ref{Name Casing}.
16293
16294 The @option{^-D-^/SPECIFIC_CASING^} and
16295 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16296 compatible.
16297
16298 @node Construct Layout Control
16299 @subsection Construct Layout Control
16300 @cindex Layout control in @command{gnatpp}
16301
16302 @noindent
16303 This group of @command{gnatpp} switches controls the layout of comments and
16304 complex syntactic constructs.  See @ref{Formatting Comments} for details
16305 on their effect.
16306
16307 @table @option
16308 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16309 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16310 All the comments remain unchanged
16311
16312 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16313 GNAT-style comment line indentation (this is the default).
16314
16315 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16316 Reference-manual comment line indentation.
16317
16318 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16319 GNAT-style comment beginning
16320
16321 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16322 Reformat comment blocks
16323
16324 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16325 Keep unchanged special form comments
16326
16327 Reformat comment blocks
16328
16329 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16330 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16331 GNAT-style layout (this is the default)
16332
16333 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16334 Compact layout
16335
16336 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16337 Uncompact layout
16338
16339 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16340 @item ^-N^/NOTABS^
16341 All the VT characters are removed from the comment text. All the HT characters
16342 are expanded with the sequences of space characters to get to the next tab
16343 stops.
16344
16345 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16346 @item ^--no-separate-is^/NO_SEPARATE_IS^
16347 Do not place the keyword @code{is} on a separate line in a subprogram body in
16348 case if the spec occupies more then one line.
16349
16350 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16351 @item ^--separate-label^/SEPARATE_LABEL^
16352 Place statement label(s) on a separate line, with the following statement
16353 on the next line.
16354
16355 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16356 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16357 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16358 keyword @code{then} in IF statements on a separate line.
16359
16360 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16361 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16362 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16363 keyword @code{then} in IF statements on a separate line. This option is
16364 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16365
16366 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16367 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16368 Start each USE clause in a context clause from a separate line.
16369
16370 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16371 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16372 Use a separate line for a loop or block statement name, but do not use an extra
16373 indentation level for the statement itself.
16374
16375 @end table
16376
16377 @ifclear vms
16378 @noindent
16379 The @option{-c1} and @option{-c2} switches are incompatible.
16380 The @option{-c3} and @option{-c4} switches are compatible with each other and
16381 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16382 the other comment formatting switches.
16383
16384 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16385 @end ifclear
16386
16387 @ifset vms
16388 @noindent
16389 For the @option{/COMMENTS_LAYOUT} qualifier:
16390 @itemize @bullet
16391 @item
16392 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16393 @item
16394 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16395 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16396 @end itemize
16397
16398 @noindent
16399 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16400 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16401 @end ifset
16402
16403 @node General Text Layout Control
16404 @subsection General Text Layout Control
16405
16406 @noindent
16407 These switches allow control over line length and indentation.
16408
16409 @table @option
16410 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16411 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16412 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16413
16414 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16415 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16416 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16417
16418 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16419 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16420 Indentation level for continuation lines (relative to the line being
16421 continued), @var{nnn} from 1@dots{}9.
16422 The default
16423 value is one less then the (normal) indentation level, unless the
16424 indentation is set to 1 (in which case the default value for continuation
16425 line indentation is also 1)
16426 @end table
16427
16428 @node Other Formatting Options
16429 @subsection Other Formatting Options
16430
16431 @noindent
16432 These switches control the inclusion of missing end/exit labels, and
16433 the indentation level in @b{case} statements.
16434
16435 @table @option
16436 @item ^-e^/NO_MISSED_LABELS^
16437 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16438 Do not insert missing end/exit labels. An end label is the name of
16439 a construct that may optionally be repeated at the end of the
16440 construct's declaration;
16441 e.g., the names of packages, subprograms, and tasks.
16442 An exit label is the name of a loop that may appear as target
16443 of an exit statement within the loop.
16444 By default, @command{gnatpp} inserts these end/exit labels when
16445 they are absent from the original source. This option suppresses such
16446 insertion, so that the formatted source reflects the original.
16447
16448 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16449 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16450 Insert a Form Feed character after a pragma Page.
16451
16452 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16453 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16454 Do not use an additional indentation level for @b{case} alternatives
16455 and variants if there are @var{nnn} or more (the default
16456 value is 10).
16457 If @var{nnn} is 0, an additional indentation level is
16458 used for @b{case} alternatives and variants regardless of their number.
16459 @end table
16460
16461 @node Setting the Source Search Path
16462 @subsection Setting the Source Search Path
16463
16464 @noindent
16465 To define the search path for the input source file, @command{gnatpp}
16466 uses the same switches as the GNAT compiler, with the same effects.
16467
16468 @table @option
16469 @item ^-I^/SEARCH=^@var{dir}
16470 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16471 The same as the corresponding gcc switch
16472
16473 @item ^-I-^/NOCURRENT_DIRECTORY^
16474 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16475 The same as the corresponding gcc switch
16476
16477 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16478 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16479 The same as the corresponding gcc switch
16480
16481 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16482 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16483 The same as the corresponding gcc switch
16484
16485 @end table
16486
16487 @node Output File Control
16488 @subsection Output File Control
16489
16490 @noindent
16491 By default the output is sent to the file whose name is obtained by appending
16492 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16493 (if the file with this name already exists, it is unconditionally overwritten).
16494 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16495 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16496 as output file.
16497 The output may be redirected by the following switches:
16498
16499 @table @option
16500 @item ^-pipe^/STANDARD_OUTPUT^
16501 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16502 Send the output to @code{Standard_Output}
16503
16504 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16505 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16506 Write the output into @var{output_file}.
16507 If @var{output_file} already exists, @command{gnatpp} terminates without
16508 reading or processing the input file.
16509
16510 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16511 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16512 Write the output into @var{output_file}, overwriting the existing file
16513 (if one is present).
16514
16515 @item ^-r^/REPLACE^
16516 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16517 Replace the input source file with the reformatted output, and copy the
16518 original input source into the file whose name is obtained by appending the
16519 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16520 If a file with this name already exists, @command{gnatpp} terminates without
16521 reading or processing the input file.
16522
16523 @item ^-rf^/OVERRIDING_REPLACE^
16524 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16525 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16526 already exists, it is overwritten.
16527
16528 @item ^-rnb^/REPLACE_NO_BACKUP^
16529 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16530 Replace the input source file with the reformatted output without
16531 creating any backup copy of the input source.
16532
16533 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16534 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16535 Specifies the format of the reformatted output file. The @var{xxx}
16536 ^string specified with the switch^option^ may be either
16537 @itemize @bullet
16538 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16539 @item ``@option{^crlf^CRLF^}''
16540 the same as @option{^crlf^CRLF^}
16541 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16542 @item ``@option{^lf^LF^}''
16543 the same as @option{^unix^UNIX^}
16544 @end itemize
16545
16546 @item ^-W^/RESULT_ENCODING=^@var{e}
16547 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16548 Specify the wide character encoding method used to write the code in the
16549 result file
16550 @var{e} is one of the following:
16551
16552 @itemize @bullet
16553
16554 @item ^h^HEX^
16555 Hex encoding
16556
16557 @item ^u^UPPER^
16558 Upper half encoding
16559
16560 @item ^s^SHIFT_JIS^
16561 Shift/JIS encoding
16562
16563 @item ^e^EUC^
16564 EUC encoding
16565
16566 @item ^8^UTF8^
16567 UTF-8 encoding
16568
16569 @item ^b^BRACKETS^
16570 Brackets encoding (default value)
16571 @end itemize
16572
16573 @end table
16574
16575 @noindent
16576 Options @option{^-pipe^/STANDARD_OUTPUT^},
16577 @option{^-o^/OUTPUT^} and
16578 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16579 contains only one file to reformat.
16580 Option
16581 @option{^--eol^/END_OF_LINE^}
16582 and
16583 @option{^-W^/RESULT_ENCODING^}
16584 cannot be used together
16585 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16586
16587 @node Other gnatpp Switches
16588 @subsection Other @code{gnatpp} Switches
16589
16590 @noindent
16591 The additional @command{gnatpp} switches are defined in this subsection.
16592
16593 @table @option
16594 @item ^-files @var{filename}^/FILES=@var{output_file}^
16595 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16596 Take the argument source files from the specified file. This file should be an
16597 ordinary textual file containing file names separated by spaces or
16598 line breaks. You can use this switch more then once in the same call to
16599 @command{gnatpp}. You also can combine this switch with explicit list of
16600 files.
16601
16602 @item ^-v^/VERBOSE^
16603 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16604 Verbose mode;
16605 @command{gnatpp} generates version information and then
16606 a trace of the actions it takes to produce or obtain the ASIS tree.
16607
16608 @item ^-w^/WARNINGS^
16609 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16610 Warning mode;
16611 @command{gnatpp} generates a warning whenever it cannot provide
16612 a required layout in the result source.
16613 @end table
16614
16615 @node Formatting Rules
16616 @section Formatting Rules
16617
16618 @noindent
16619 The following subsections show how @command{gnatpp} treats ``white space'',
16620 comments, program layout, and name casing.
16621 They provide the detailed descriptions of the switches shown above.
16622
16623 @menu
16624 * White Space and Empty Lines::
16625 * Formatting Comments::
16626 * Construct Layout::
16627 * Name Casing::
16628 @end menu
16629
16630 @node White Space and Empty Lines
16631 @subsection White Space and Empty Lines
16632
16633 @noindent
16634 @command{gnatpp} does not have an option to control space characters.
16635 It will add or remove spaces according to the style illustrated by the
16636 examples in the @cite{Ada Reference Manual}.
16637
16638 The only format effectors
16639 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16640 that will appear in the output file are platform-specific line breaks,
16641 and also format effectors within (but not at the end of) comments.
16642 In particular, each horizontal tab character that is not inside
16643 a comment will be treated as a space and thus will appear in the
16644 output file as zero or more spaces depending on
16645 the reformatting of the line in which it appears.
16646 The only exception is a Form Feed character, which is inserted after a
16647 pragma @code{Page} when @option{-ff} is set.
16648
16649 The output file will contain no lines with trailing ``white space'' (spaces,
16650 format effectors).
16651
16652 Empty lines in the original source are preserved
16653 only if they separate declarations or statements.
16654 In such contexts, a
16655 sequence of two or more empty lines is replaced by exactly one empty line.
16656 Note that a blank line will be removed if it separates two ``comment blocks''
16657 (a comment block is a sequence of whole-line comments).
16658 In order to preserve a visual separation between comment blocks, use an
16659 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16660 Likewise, if for some reason you wish to have a sequence of empty lines,
16661 use a sequence of empty comments instead.
16662
16663 @node Formatting Comments
16664 @subsection Formatting Comments
16665
16666 @noindent
16667 Comments in Ada code are of two kinds:
16668 @itemize @bullet
16669 @item
16670 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16671 ``white space'') on a line
16672
16673 @item
16674 an @emph{end-of-line comment}, which follows some other Ada lexical element
16675 on the same line.
16676 @end itemize
16677
16678 @noindent
16679 The indentation of a whole-line comment is that of either
16680 the preceding or following line in
16681 the formatted source, depending on switch settings as will be described below.
16682
16683 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16684 between the end of the preceding Ada lexical element and the beginning
16685 of the comment as appear in the original source,
16686 unless either the comment has to be split to
16687 satisfy the line length limitation, or else the next line contains a
16688 whole line comment that is considered a continuation of this end-of-line
16689 comment (because it starts at the same position).
16690 In the latter two
16691 cases, the start of the end-of-line comment is moved right to the nearest
16692 multiple of the indentation level.
16693 This may result in a ``line overflow'' (the right-shifted comment extending
16694 beyond the maximum line length), in which case the comment is split as
16695 described below.
16696
16697 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16698 (GNAT-style comment line indentation)
16699 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16700 (reference-manual comment line indentation).
16701 With reference-manual style, a whole-line comment is indented as if it
16702 were a declaration or statement at the same place
16703 (i.e., according to the indentation of the preceding line(s)).
16704 With GNAT style, a whole-line comment that is immediately followed by an
16705 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16706 word @b{begin}, is indented based on the construct that follows it.
16707
16708 For example:
16709 @smallexample @c ada
16710 @cartouche
16711 if A then
16712     null;
16713        -- some comment
16714 else
16715    null;
16716 end if;
16717 @end cartouche
16718 @end smallexample
16719
16720 @noindent
16721 Reference-manual indentation produces:
16722
16723 @smallexample @c ada
16724 @cartouche
16725 if A then
16726    null;
16727    --  some comment
16728 else
16729    null;
16730 end if;
16731 @end cartouche
16732 @end smallexample
16733
16734 @noindent
16735 while GNAT-style indentation produces:
16736
16737 @smallexample @c ada
16738 @cartouche
16739 if A then
16740    null;
16741 --  some comment
16742 else
16743    null;
16744 end if;
16745 @end cartouche
16746 @end smallexample
16747
16748 @noindent
16749 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16750 (GNAT style comment beginning) has the following
16751 effect:
16752
16753 @itemize @bullet
16754 @item
16755 For each whole-line comment that does not end with two hyphens,
16756 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16757 to ensure that there are at least two spaces between these hyphens and the
16758 first non-blank character of the comment.
16759 @end itemize
16760
16761 @noindent
16762 For an end-of-line comment, if in the original source the next line is a
16763 whole-line comment that starts at the same position
16764 as the end-of-line comment,
16765 then the whole-line comment (and all whole-line comments
16766 that follow it and that start at the same position)
16767 will start at this position in the output file.
16768
16769 @noindent
16770 That is, if in the original source we have:
16771
16772 @smallexample @c ada
16773 @cartouche
16774 begin
16775 A := B + C;            --  B must be in the range Low1..High1
16776                        --  C must be in the range Low2..High2
16777              --B+C will be in the range Low1+Low2..High1+High2
16778 X := X + 1;
16779 @end cartouche
16780 @end smallexample
16781
16782 @noindent
16783 Then in the formatted source we get
16784
16785 @smallexample @c ada
16786 @cartouche
16787 begin
16788    A := B + C;            --  B must be in the range Low1..High1
16789                           --  C must be in the range Low2..High2
16790    --  B+C will be in the range Low1+Low2..High1+High2
16791    X := X + 1;
16792 @end cartouche
16793 @end smallexample
16794
16795 @noindent
16796 A comment that exceeds the line length limit will be split.
16797 Unless switch
16798 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16799 the line belongs to a reformattable block, splitting the line generates a
16800 @command{gnatpp} warning.
16801 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16802 comments may be reformatted in typical
16803 word processor style (that is, moving words between lines and putting as
16804 many words in a line as possible).
16805
16806 @noindent
16807 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16808 that has a special format (that is, a character that is neither a letter nor digit
16809 not white space nor line break immediately following the leading @code{--} of
16810 the comment) should be without any change moved from the argument source
16811 into reformatted source. This switch allows to preserve comments that are used
16812 as a special marks in the code (e.g.@: SPARK annotation).
16813
16814 @node Construct Layout
16815 @subsection Construct Layout
16816
16817 @noindent
16818 In several cases the suggested layout in the Ada Reference Manual includes
16819 an extra level of indentation that many programmers prefer to avoid. The
16820 affected cases include:
16821
16822 @itemize @bullet
16823
16824 @item Record type declaration (RM 3.8)
16825
16826 @item Record representation clause (RM 13.5.1)
16827
16828 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16829
16830 @item Block statement in case if a block has a statement identifier (RM 5.6)
16831 @end itemize
16832
16833 @noindent
16834 In compact mode (when GNAT style layout or compact layout is set),
16835 the pretty printer uses one level of indentation instead
16836 of two. This is achieved in the record definition and record representation
16837 clause cases by putting the @code{record} keyword on the same line as the
16838 start of the declaration or representation clause, and in the block and loop
16839 case by putting the block or loop header on the same line as the statement
16840 identifier.
16841
16842 @noindent
16843 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16844 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16845 layout on the one hand, and uncompact layout
16846 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16847 can be illustrated by the following examples:
16848
16849 @iftex
16850 @cartouche
16851 @multitable @columnfractions .5 .5
16852 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16853
16854 @item
16855 @smallexample @c ada
16856 type q is record
16857    a : integer;
16858    b : integer;
16859 end record;
16860 @end smallexample
16861 @tab
16862 @smallexample @c ada
16863 type q is
16864    record
16865       a : integer;
16866       b : integer;
16867    end record;
16868 @end smallexample
16869
16870 @item
16871 @smallexample @c ada
16872 for q use record
16873    a at 0 range  0 .. 31;
16874    b at 4 range  0 .. 31;
16875 end record;
16876 @end smallexample
16877 @tab
16878 @smallexample @c ada
16879 for q use
16880    record
16881       a at 0 range  0 .. 31;
16882       b at 4 range  0 .. 31;
16883    end record;
16884 @end smallexample
16885
16886 @item
16887 @smallexample @c ada
16888 Block : declare
16889    A : Integer := 3;
16890 begin
16891    Proc (A, A);
16892 end Block;
16893 @end smallexample
16894 @tab
16895 @smallexample @c ada
16896 Block :
16897    declare
16898       A : Integer := 3;
16899    begin
16900       Proc (A, A);
16901    end Block;
16902 @end smallexample
16903
16904 @item
16905 @smallexample @c ada
16906 Clear : for J in 1 .. 10 loop
16907    A (J) := 0;
16908 end loop Clear;
16909 @end smallexample
16910 @tab
16911 @smallexample @c ada
16912 Clear :
16913    for J in 1 .. 10 loop
16914       A (J) := 0;
16915    end loop Clear;
16916 @end smallexample
16917 @end multitable
16918 @end cartouche
16919 @end iftex
16920
16921 @ifnottex
16922 @smallexample
16923 @cartouche
16924 GNAT style, compact layout              Uncompact layout
16925
16926 type q is record                        type q is
16927    a : integer;                            record
16928    b : integer;                               a : integer;
16929 end record;                                   b : integer;
16930                                            end record;
16931
16932 for q use record                        for q use
16933    a at 0 range  0 .. 31;                  record
16934    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16935 end record;                                   b at 4 range  0 .. 31;
16936                                            end record;
16937
16938 Block : declare                         Block :
16939    A : Integer := 3;                       declare
16940 begin                                         A : Integer := 3;
16941    Proc (A, A);                            begin
16942 end Block;                                    Proc (A, A);
16943                                            end Block;
16944
16945 Clear : for J in 1 .. 10 loop           Clear :
16946    A (J) := 0;                             for J in 1 .. 10 loop
16947 end loop Clear;                               A (J) := 0;
16948                                            end loop Clear;
16949 @end cartouche
16950 @end smallexample
16951 @end ifnottex
16952
16953 @noindent
16954 A further difference between GNAT style layout and compact layout is that
16955 GNAT style layout inserts empty lines as separation for
16956 compound statements, return statements and bodies.
16957
16958 Note that the layout specified by
16959 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16960 for named block and loop statements overrides the layout defined by these
16961 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16962 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16963 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16964
16965 @node Name Casing
16966 @subsection Name Casing
16967
16968 @noindent
16969 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16970 the same casing as the corresponding defining identifier.
16971
16972 You control the casing for defining occurrences via the
16973 @option{^-n^/NAME_CASING^} switch.
16974 @ifclear vms
16975 With @option{-nD} (``as declared'', which is the default),
16976 @end ifclear
16977 @ifset vms
16978 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16979 @end ifset
16980 defining occurrences appear exactly as in the source file
16981 where they are declared.
16982 The other ^values for this switch^options for this qualifier^ ---
16983 @option{^-nU^UPPER_CASE^},
16984 @option{^-nL^LOWER_CASE^},
16985 @option{^-nM^MIXED_CASE^} ---
16986 result in
16987 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16988 If @command{gnatpp} changes the casing of a defining
16989 occurrence, it analogously changes the casing of all the
16990 usage occurrences of this name.
16991
16992 If the defining occurrence of a name is not in the source compilation unit
16993 currently being processed by @command{gnatpp}, the casing of each reference to
16994 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16995 switch (subject to the dictionary file mechanism described below).
16996 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16997 had affected the
16998 casing for the defining occurrence of the name.
16999
17000 Some names may need to be spelled with casing conventions that are not
17001 covered by the upper-, lower-, and mixed-case transformations.
17002 You can arrange correct casing by placing such names in a
17003 @emph{dictionary file},
17004 and then supplying a @option{^-D^/DICTIONARY^} switch.
17005 The casing of names from dictionary files overrides
17006 any @option{^-n^/NAME_CASING^} switch.
17007
17008 To handle the casing of Ada predefined names and the names from GNAT libraries,
17009 @command{gnatpp} assumes a default dictionary file.
17010 The name of each predefined entity is spelled with the same casing as is used
17011 for the entity in the @cite{Ada Reference Manual}.
17012 The name of each entity in the GNAT libraries is spelled with the same casing
17013 as is used in the declaration of that entity.
17014
17015 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17016 default dictionary file.
17017 Instead, the casing for predefined and GNAT-defined names will be established
17018 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17019 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17020 will appear as just shown,
17021 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17022 To ensure that even such names are rendered in uppercase,
17023 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17024 (or else, less conveniently, place these names in upper case in a dictionary
17025 file).
17026
17027 A dictionary file is
17028 a plain text file; each line in this file can be either a blank line
17029 (containing only space characters and ASCII.HT characters), an Ada comment
17030 line, or the specification of exactly one @emph{casing schema}.
17031
17032 A casing schema is a string that has the following syntax:
17033
17034 @smallexample
17035 @cartouche
17036   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17037
17038   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17039 @end cartouche
17040 @end smallexample
17041
17042 @noindent
17043 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17044 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17045
17046 The casing schema string can be followed by white space and/or an Ada-style
17047 comment; any amount of white space is allowed before the string.
17048
17049 If a dictionary file is passed as
17050 @ifclear vms
17051 the value of a @option{-D@var{file}} switch
17052 @end ifclear
17053 @ifset vms
17054 an option to the @option{/DICTIONARY} qualifier
17055 @end ifset
17056 then for every
17057 simple name and every identifier, @command{gnatpp} checks if the dictionary
17058 defines the casing for the name or for some of its parts (the term ``subword''
17059 is used below to denote the part of a name which is delimited by ``_'' or by
17060 the beginning or end of the word and which does not contain any ``_'' inside):
17061
17062 @itemize @bullet
17063 @item
17064 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17065 the casing defined by the dictionary; no subwords are checked for this word
17066
17067 @item
17068 for every subword @command{gnatpp} checks if the dictionary contains the
17069 corresponding string of the form @code{*@var{simple_identifier}*},
17070 and if it does, the casing of this @var{simple_identifier} is used
17071 for this subword
17072
17073 @item
17074 if the whole name does not contain any ``_'' inside, and if for this name
17075 the dictionary contains two entries - one of the form @var{identifier},
17076 and another - of the form *@var{simple_identifier}*, then the first one
17077 is applied to define the casing of this name
17078
17079 @item
17080 if more than one dictionary file is passed as @command{gnatpp} switches, each
17081 dictionary adds new casing exceptions and overrides all the existing casing
17082 exceptions set by the previous dictionaries
17083
17084 @item
17085 when @command{gnatpp} checks if the word or subword is in the dictionary,
17086 this check is not case sensitive
17087 @end itemize
17088
17089 @noindent
17090 For example, suppose we have the following source to reformat:
17091
17092 @smallexample @c ada
17093 @cartouche
17094 procedure test is
17095    name1 : integer := 1;
17096    name4_name3_name2 : integer := 2;
17097    name2_name3_name4 : Boolean;
17098    name1_var : Float;
17099 begin
17100    name2_name3_name4 := name4_name3_name2 > name1;
17101 end;
17102 @end cartouche
17103 @end smallexample
17104
17105 @noindent
17106 And suppose we have two dictionaries:
17107
17108 @smallexample
17109 @cartouche
17110 @i{dict1:}
17111    NAME1
17112    *NaMe3*
17113    *Name1*
17114 @end cartouche
17115
17116 @cartouche
17117 @i{dict2:}
17118   *NAME3*
17119 @end cartouche
17120 @end smallexample
17121
17122 @noindent
17123 If @command{gnatpp} is called with the following switches:
17124
17125 @smallexample
17126 @ifclear vms
17127 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17128 @end ifclear
17129 @ifset vms
17130 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17131 @end ifset
17132 @end smallexample
17133
17134 @noindent
17135 then we will get the following name casing in the @command{gnatpp} output:
17136
17137 @smallexample @c ada
17138 @cartouche
17139 procedure Test is
17140    NAME1             : Integer := 1;
17141    Name4_NAME3_Name2 : Integer := 2;
17142    Name2_NAME3_Name4 : Boolean;
17143    Name1_Var         : Float;
17144 begin
17145    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17146 end Test;
17147 @end cartouche
17148 @end smallexample
17149
17150 @c *********************************
17151 @node The GNAT Metric Tool gnatmetric
17152 @chapter The GNAT Metric Tool @command{gnatmetric}
17153 @findex gnatmetric
17154 @cindex Metric tool
17155
17156 @noindent
17157 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17158 for computing various program metrics.
17159 It takes an Ada source file as input and generates a file containing the
17160 metrics data as output. Various switches control which
17161 metrics are computed and output.
17162
17163 @command{gnatmetric} generates and uses the ASIS
17164 tree for the input source and thus requires the input to be syntactically and
17165 semantically legal.
17166 If this condition is not met, @command{gnatmetric} will generate
17167 an error message; no metric information for this file will be
17168 computed and reported.
17169
17170 If the compilation unit contained in the input source depends semantically
17171 upon units in files located outside the current directory, you have to provide
17172 the source search path when invoking @command{gnatmetric}.
17173 If it depends semantically upon units that are contained
17174 in files with names that do not follow the GNAT file naming rules, you have to
17175 provide the configuration file describing the corresponding naming scheme (see
17176 the description of the @command{gnatmetric} switches below.)
17177 Alternatively, you may use a project file and invoke @command{gnatmetric}
17178 through the @command{gnat} driver.
17179
17180 The @command{gnatmetric} command has the form
17181
17182 @smallexample
17183 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17184 @end smallexample
17185
17186 @noindent
17187 where
17188 @itemize @bullet
17189 @item
17190 @var{switches} specify the metrics to compute and define the destination for
17191 the output
17192
17193 @item
17194 Each @var{filename} is the name (including the extension) of a source
17195 file to process. ``Wildcards'' are allowed, and
17196 the file name may contain path information.
17197 If no @var{filename} is supplied, then the @var{switches} list must contain
17198 at least one
17199 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17200 Including both a @option{-files} switch and one or more
17201 @var{filename} arguments is permitted.
17202
17203 @item
17204 @samp{-cargs @var{gcc_switches}} is a list of switches for
17205 @command{gcc}. They will be passed on to all compiler invocations made by
17206 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17207 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17208 and use the @option{-gnatec} switch to set the configuration file.
17209 @end itemize
17210
17211 @menu
17212 * Switches for gnatmetric::
17213 @end menu
17214
17215 @node Switches for gnatmetric
17216 @section Switches for @command{gnatmetric}
17217
17218 @noindent
17219 The following subsections describe the various switches accepted by
17220 @command{gnatmetric}, organized by category.
17221
17222 @menu
17223 * Output Files Control::
17224 * Disable Metrics For Local Units::
17225 * Specifying a set of metrics to compute::
17226 * Other gnatmetric Switches::
17227 * Generate project-wide metrics::
17228 @end menu
17229
17230 @node Output Files Control
17231 @subsection Output File Control
17232 @cindex Output file control in @command{gnatmetric}
17233
17234 @noindent
17235 @command{gnatmetric} has two output formats. It can generate a
17236 textual (human-readable) form, and also XML. By default only textual
17237 output is generated.
17238
17239 When generating the output in textual form, @command{gnatmetric} creates
17240 for each Ada source file a corresponding text file
17241 containing the computed metrics, except for the case when the set of metrics
17242 specified by gnatmetric parameters consists only of metrics that are computed
17243 for the whole set of analyzed sources, but not for each Ada source.
17244 By default, this file is placed in the same directory as where the source
17245 file is located, and its name is obtained
17246 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17247 input file.
17248
17249 All the output information generated in XML format is placed in a single
17250 file. By default this file is placed in the current directory and has the
17251 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17252
17253 Some of the computed metrics are summed over the units passed to
17254 @command{gnatmetric}; for example, the total number of lines of code.
17255 By default this information is sent to @file{stdout}, but a file
17256 can be specified with the @option{-og} switch.
17257
17258 The following switches control the @command{gnatmetric} output:
17259
17260 @table @option
17261 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17262 @item ^-x^/XML^
17263 Generate the XML output
17264
17265 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17266 @item ^-xs^/XSD^
17267 Generate the XML output and the XML schema file that describes the structure
17268 of the XML metric report, this schema is assigned to the XML file. The schema
17269 file has the same name as the XML output file with @file{.xml} suffix replaced
17270 with @file{.xsd}
17271
17272 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17273 @item ^-nt^/NO_TEXT^
17274 Do not generate the output in text form (implies @option{^-x^/XML^})
17275
17276 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17277 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17278 Put textual files with detailed metrics into @var{output_dir}
17279
17280 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17281 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17282 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17283 in the name of the output file.
17284
17285 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17286 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17287 Put global metrics into @var{file_name}
17288
17289 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17290 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17291 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17292
17293 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17294 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17295 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17296 output includes the name(s) of the Ada source file(s) from which the metrics
17297 are computed.  By default each name includes the absolute path. The
17298 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17299 to exclude all directory information from the file names that are output.)
17300
17301 @end table
17302
17303 @node Disable Metrics For Local Units
17304 @subsection Disable Metrics For Local Units
17305 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17306
17307 @noindent
17308 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17309 one compilation
17310 unit per one source file. It computes line metrics for the whole source
17311 file, and it also computes syntax
17312 and complexity metrics for the file's outermost unit.
17313
17314 By default, @command{gnatmetric} will also compute all metrics for certain
17315 kinds of locally declared program units:
17316
17317 @itemize @bullet
17318 @item
17319 subprogram (and generic subprogram) bodies;
17320
17321 @item
17322 package (and generic package) specs and bodies;
17323
17324 @item
17325 task object and type specifications and bodies;
17326
17327 @item
17328 protected object and type specifications and bodies.
17329 @end itemize
17330
17331 @noindent
17332 These kinds of entities will be referred to as
17333 @emph{eligible local program units}, or simply @emph{eligible local units},
17334 @cindex Eligible local unit (for @command{gnatmetric})
17335 in the discussion below.
17336
17337 Note that a subprogram declaration, generic instantiation,
17338 or renaming declaration only receives metrics
17339 computation when it appear as the outermost entity
17340 in a source file.
17341
17342 Suppression of metrics computation for eligible local units can be
17343 obtained via the following switch:
17344
17345 @table @option
17346 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17347 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17348 Do not compute detailed metrics for eligible local program units
17349
17350 @end table
17351
17352 @node Specifying a set of metrics to compute
17353 @subsection Specifying a set of metrics to compute
17354
17355 @noindent
17356 By default all the metrics are computed and reported. The switches
17357 described in this subsection allow you to control, on an individual
17358 basis, whether metrics are computed and
17359 reported. If at least one positive metric
17360 switch is specified (that is, a switch that defines that a given
17361 metric or set of metrics is to be computed), then only
17362 explicitly specified metrics are reported.
17363
17364 @menu
17365 * Line Metrics Control::
17366 * Syntax Metrics Control::
17367 * Complexity Metrics Control::
17368 * Object-Oriented Metrics Control::
17369 @end menu
17370
17371 @node Line Metrics Control
17372 @subsubsection Line Metrics Control
17373 @cindex Line metrics control in @command{gnatmetric}
17374
17375 @noindent
17376 For any (legal) source file, and for each of its
17377 eligible local program units, @command{gnatmetric} computes the following
17378 metrics:
17379
17380 @itemize @bullet
17381 @item
17382 the total number of lines;
17383
17384 @item
17385 the total number of code lines (i.e., non-blank lines that are not comments)
17386
17387 @item
17388 the number of comment lines
17389
17390 @item
17391 the number of code lines containing end-of-line comments;
17392
17393 @item
17394 the comment percentage: the ratio between the number of lines that contain
17395 comments and the number of all non-blank lines, expressed as a percentage;
17396
17397 @item
17398 the number of empty lines and lines containing only space characters and/or
17399 format effectors (blank lines)
17400
17401 @item
17402 the average number of code lines in subprogram bodies, task bodies, entry
17403 bodies and statement sequences in package bodies (this metric is only computed
17404 across the whole set of the analyzed units)
17405
17406 @end itemize
17407
17408 @noindent
17409 @command{gnatmetric} sums the values of the line metrics for all the
17410 files being processed and then generates the cumulative results. The tool
17411 also computes for all the files being processed the average number of code
17412 lines in bodies.
17413
17414 You can use the following switches to select the specific line metrics
17415 to be computed and reported.
17416
17417 @table @option
17418 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17419
17420 @ifclear vms
17421 @cindex @option{--no-lines@var{x}}
17422 @end ifclear
17423
17424 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17425 Report all the line metrics
17426
17427 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17428 Do not report any of line metrics
17429
17430 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17431 Report the number of all lines
17432
17433 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17434 Do not report the number of all lines
17435
17436 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17437 Report the number of code lines
17438
17439 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17440 Do not report the number of code lines
17441
17442 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17443 Report the number of comment lines
17444
17445 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17446 Do not report the number of comment lines
17447
17448 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17449 Report the number of code lines containing
17450 end-of-line comments
17451
17452 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17453 Do not report the number of code lines containing
17454 end-of-line comments
17455
17456 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17457 Report the comment percentage in the program text
17458
17459 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17460 Do not report the comment percentage in the program text
17461
17462 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17463 Report the number of blank lines
17464
17465 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17466 Do not report the number of blank lines
17467
17468 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17469 Report the average number of code lines in subprogram bodies, task bodies,
17470 entry bodies and statement sequences in package bodies. The metric is computed
17471 and reported for the whole set of processed Ada sources only.
17472
17473 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17474 Do not report the average number of code lines in subprogram bodies,
17475 task bodies, entry bodies and statement sequences in package bodies.
17476
17477 @end table
17478
17479 @node Syntax Metrics Control
17480 @subsubsection Syntax Metrics Control
17481 @cindex Syntax metrics control in @command{gnatmetric}
17482
17483 @noindent
17484 @command{gnatmetric} computes various syntactic metrics for the
17485 outermost unit and for each eligible local unit:
17486
17487 @table @emph
17488 @item LSLOC (``Logical Source Lines Of Code'')
17489 The total number of declarations and the total number of statements
17490
17491 @item Maximal static nesting level of inner program units
17492 According to
17493 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17494 package, a task unit, a protected unit, a
17495 protected entry, a generic unit, or an explicitly declared subprogram other
17496 than an enumeration literal.''
17497
17498 @item Maximal nesting level of composite syntactic constructs
17499 This corresponds to the notion of the
17500 maximum nesting level in the GNAT built-in style checks
17501 (@pxref{Style Checking})
17502 @end table
17503
17504 @noindent
17505 For the outermost unit in the file, @command{gnatmetric} additionally computes
17506 the following metrics:
17507
17508 @table @emph
17509 @item Public subprograms
17510 This metric is computed for package specs. It is the
17511 number of subprograms and generic subprograms declared in the visible
17512 part (including the visible part of nested packages, protected objects, and
17513 protected types).
17514
17515 @item All subprograms
17516 This metric is computed for bodies and subunits. The
17517 metric is equal to a total number of subprogram bodies in the compilation
17518 unit.
17519 Neither generic instantiations nor renamings-as-a-body nor body stubs
17520 are counted. Any subprogram body is counted, independently of its nesting
17521 level and enclosing constructs. Generic bodies and bodies of protected
17522 subprograms are counted in the same way as ``usual'' subprogram bodies.
17523
17524 @item Public types
17525 This metric is computed for package specs and
17526 generic package declarations. It is the total number of types
17527 that can be referenced from outside this compilation unit, plus the
17528 number of types from all the visible parts of all the visible generic
17529 packages. Generic formal types are not counted.  Only types, not subtypes,
17530 are included.
17531
17532 @noindent
17533 Along with the total number of public types, the following
17534 types are counted and reported separately:
17535
17536 @itemize @bullet
17537 @item
17538 Abstract types
17539
17540 @item
17541 Root tagged types (abstract, non-abstract, private, non-private). Type
17542 extensions are @emph{not} counted
17543
17544 @item
17545 Private types (including private extensions)
17546
17547 @item
17548 Task types
17549
17550 @item
17551 Protected types
17552
17553 @end itemize
17554
17555 @item All types
17556 This metric is computed for any compilation unit. It is equal to the total
17557 number of the declarations of different types given in the compilation unit.
17558 The private and the corresponding full type declaration are counted as one
17559 type declaration. Incomplete type declarations and generic formal types
17560 are not counted.
17561 No distinction is made among different kinds of types (abstract,
17562 private etc.); the total number of types is computed and reported.
17563
17564 @end table
17565
17566 @noindent
17567 By default, all the syntax metrics are computed and reported. You can use the
17568 following switches to select specific syntax metrics.
17569
17570 @table @option
17571
17572 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17573
17574 @ifclear vms
17575 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17576 @end ifclear
17577
17578 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17579 Report all the syntax metrics
17580
17581 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17582 Do not report any of syntax metrics
17583
17584 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17585 Report the total number of declarations
17586
17587 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17588 Do not report the total number of declarations
17589
17590 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17591 Report the total number of statements
17592
17593 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17594 Do not report the total number of statements
17595
17596 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17597 Report the number of public subprograms in a compilation unit
17598
17599 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17600 Do not report the number of public subprograms in a compilation unit
17601
17602 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17603 Report the number of all the subprograms in a compilation unit
17604
17605 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17606 Do not report the number of all the subprograms in a compilation unit
17607
17608 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17609 Report the number of public types in a compilation unit
17610
17611 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17612 Do not report the number of public types in a compilation unit
17613
17614 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17615 Report the number of all the types in a compilation unit
17616
17617 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17618 Do not report the number of all the types in a compilation unit
17619
17620 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17621 Report the maximal program unit nesting level
17622
17623 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17624 Do not report the maximal program unit nesting level
17625
17626 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17627 Report the maximal construct nesting level
17628
17629 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17630 Do not report the maximal construct nesting level
17631
17632 @end table
17633
17634 @node Complexity Metrics Control
17635 @subsubsection Complexity Metrics Control
17636 @cindex Complexity metrics control in @command{gnatmetric}
17637
17638 @noindent
17639 For a program unit that is an executable body (a subprogram body (including
17640 generic bodies), task body, entry body or a package body containing
17641 its own statement sequence) @command{gnatmetric} computes the following
17642 complexity metrics:
17643
17644 @itemize @bullet
17645 @item
17646 McCabe cyclomatic complexity;
17647
17648 @item
17649 McCabe essential complexity;
17650
17651 @item
17652 maximal loop nesting level
17653
17654 @end itemize
17655
17656 @noindent
17657 The McCabe complexity metrics are defined
17658 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17659
17660 According to McCabe, both control statements and short-circuit control forms
17661 should be taken into account when computing cyclomatic complexity. For each
17662 body, we compute three metric values:
17663
17664 @itemize @bullet
17665 @item
17666 the complexity introduced by control
17667 statements only, without taking into account short-circuit forms,
17668
17669 @item
17670 the complexity introduced by short-circuit control forms only, and
17671
17672 @item
17673 the total
17674 cyclomatic complexity, which is the sum of these two values.
17675 @end itemize
17676
17677 @noindent
17678 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17679 the code in the exception handlers and in all the nested program units.
17680
17681 By default, all the complexity metrics are computed and reported.
17682 For more fine-grained control you can use
17683 the following switches:
17684
17685 @table @option
17686 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17687
17688 @ifclear vms
17689 @cindex @option{--no-complexity@var{x}}
17690 @end ifclear
17691
17692 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17693 Report all the complexity metrics
17694
17695 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17696 Do not report any of complexity metrics
17697
17698 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17699 Report the McCabe Cyclomatic Complexity
17700
17701 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17702 Do not report the McCabe Cyclomatic Complexity
17703
17704 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17705 Report the Essential Complexity
17706
17707 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17708 Do not report the Essential Complexity
17709
17710 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17711 Report maximal loop nesting level
17712
17713 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17714 Do not report maximal loop nesting level
17715
17716 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17717 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17718 task bodies, entry bodies and statement sequences in package bodies.
17719 The metric is computed and reported for whole set of processed Ada sources
17720 only.
17721
17722 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17723 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17724 bodies, task bodies, entry bodies and statement sequences in package bodies
17725
17726 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17727 @item ^-ne^/NO_EXITS_AS_GOTOS^
17728 Do not consider @code{exit} statements as @code{goto}s when
17729 computing Essential Complexity
17730
17731 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17732 Report the extra exit points for subprogram bodies. As an exit point, this
17733 metric counts @code{return} statements and raise statements in case when the
17734 raised exception is not handled in the same body. In case of a function this
17735 metric subtracts 1 from the number of exit points, because a function body
17736 must contain at least one @code{return} statement.
17737
17738 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17739 Do not report the extra exit points for subprogram bodies
17740 @end table
17741
17742
17743 @node Object-Oriented Metrics Control
17744 @subsubsection Object-Oriented Metrics Control
17745 @cindex Object-Oriented metrics control in @command{gnatmetric}
17746
17747 @noindent
17748 @cindex Coupling metrics (in in @command{gnatmetric})
17749 Coupling metrics are object-oriented metrics that measure the
17750 dependencies between a given class (or a group of classes) and the
17751 ``external world'' (that is, the other classes in the program). In this
17752 subsection the term ``class'' is used in its
17753 traditional object-oriented programming sense
17754 (an instantiable module that contains data and/or method members).
17755 A @emph{category} (of classes)
17756 is a group of closely related classes that are reused and/or
17757 modified together.
17758
17759 A class @code{K}'s @emph{efferent coupling} is the number of classes
17760 that @code{K} depends upon.
17761 A category's efferent coupling is the number of classes outside the
17762 category that the classes inside the category depend upon.
17763
17764 A class @code{K}'s @emph{afferent coupling} is the number of classes
17765 that depend upon @code{K}.
17766 A category's afferent coupling is the number of classes outside the
17767 category that depend on classes belonging to the category.
17768
17769 Ada's implementation of the object-oriented paradigm does not use the
17770 traditional class notion, so the definition of the coupling
17771 metrics for Ada maps the class and class category notions
17772 onto Ada constructs.
17773
17774 For the coupling metrics, several kinds of modules -- a library package,
17775 a library generic package, and a library generic package instantiation --
17776 that define a tagged type or an interface type are
17777 considered to be a class. A category consists of a library package (or
17778 a library generic package) that defines a tagged or an interface type,
17779 together with all its descendant (generic) packages that define tagged
17780 or interface types. For any package counted as a class,
17781 its body and subunits (if any) are considered
17782 together with its spec when counting the dependencies, and coupling
17783 metrics are reported for spec units only. For dependencies
17784 between classes, the Ada semantic dependencies are considered.
17785 For coupling metrics, only dependencies on units that are considered as
17786 classes, are considered.
17787
17788 When computing coupling metrics, @command{gnatmetric} counts only
17789 dependencies between units that are arguments of the gnatmetric call.
17790 Coupling metrics are program-wide (or project-wide) metrics, so to
17791 get a valid result, you should call @command{gnatmetric} for
17792 the whole set of sources that make up your program. It can be done
17793 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17794 option (see See @ref{The GNAT Driver and Project Files} for details.
17795
17796 By default, all the coupling metrics are disabled. You can use the following
17797 switches to specify the coupling metrics to be computed and reported:
17798
17799 @table @option
17800
17801 @ifclear vms
17802 @cindex @option{--package@var{x}} (@command{gnatmetric})
17803 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17804 @cindex @option{--category@var{x}} (@command{gnatmetric})
17805 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17806 @end ifclear
17807
17808 @ifset vms
17809 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17810 @end ifset
17811
17812 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17813 Report all the coupling metrics
17814
17815 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17816 Do not report any of  metrics
17817
17818 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17819 Report package efferent coupling
17820
17821 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17822 Do not report package efferent coupling
17823
17824 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17825 Report package afferent coupling
17826
17827 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17828 Do not report package afferent coupling
17829
17830 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17831 Report category efferent coupling
17832
17833 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17834 Do not report category efferent coupling
17835
17836 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17837 Report category afferent coupling
17838
17839 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17840 Do not report category afferent coupling
17841
17842 @end table
17843
17844 @node Other gnatmetric Switches
17845 @subsection Other @code{gnatmetric} Switches
17846
17847 @noindent
17848 Additional @command{gnatmetric} switches are as follows:
17849
17850 @table @option
17851 @item ^-files @var{filename}^/FILES=@var{filename}^
17852 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17853 Take the argument source files from the specified file. This file should be an
17854 ordinary text file containing file names separated by spaces or
17855 line breaks. You can use this switch more then once in the same call to
17856 @command{gnatmetric}. You also can combine this switch with
17857 an explicit list of files.
17858
17859 @item ^-v^/VERBOSE^
17860 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17861 Verbose mode;
17862 @command{gnatmetric} generates version information and then
17863 a trace of sources being processed.
17864
17865 @item ^-dv^/DEBUG_OUTPUT^
17866 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17867 Debug mode;
17868 @command{gnatmetric} generates various messages useful to understand what
17869 happens during the metrics computation
17870
17871 @item ^-q^/QUIET^
17872 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17873 Quiet mode.
17874 @end table
17875
17876 @node Generate project-wide metrics
17877 @subsection Generate project-wide metrics
17878
17879 In order to compute metrics on all units of a given project, you can use
17880 the @command{gnat} driver along with the @option{-P} option:
17881 @smallexample
17882    gnat metric -Pproj
17883 @end smallexample
17884
17885 @noindent
17886 If the project @code{proj} depends upon other projects, you can compute
17887 the metrics on the project closure using the @option{-U} option:
17888 @smallexample
17889    gnat metric -Pproj -U
17890 @end smallexample
17891
17892 @noindent
17893 Finally, if not all the units are relevant to a particular main
17894 program in the project closure, you can generate metrics for the set
17895 of units needed to create a given main program (unit closure) using
17896 the @option{-U} option followed by the name of the main unit:
17897 @smallexample
17898    gnat metric -Pproj -U main
17899 @end smallexample
17900
17901
17902 @c ***********************************
17903 @node File Name Krunching Using gnatkr
17904 @chapter File Name Krunching Using @code{gnatkr}
17905 @findex gnatkr
17906
17907 @noindent
17908 This chapter discusses the method used by the compiler to shorten
17909 the default file names chosen for Ada units so that they do not
17910 exceed the maximum length permitted. It also describes the
17911 @code{gnatkr} utility that can be used to determine the result of
17912 applying this shortening.
17913 @menu
17914 * About gnatkr::
17915 * Using gnatkr::
17916 * Krunching Method::
17917 * Examples of gnatkr Usage::
17918 @end menu
17919
17920 @node About gnatkr
17921 @section About @code{gnatkr}
17922
17923 @noindent
17924 The default file naming rule in GNAT
17925 is that the file name must be derived from
17926 the unit name. The exact default rule is as follows:
17927 @itemize @bullet
17928 @item
17929 Take the unit name and replace all dots by hyphens.
17930 @item
17931 If such a replacement occurs in the
17932 second character position of a name, and the first character is
17933 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17934 then replace the dot by the character
17935 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17936 instead of a minus.
17937 @end itemize
17938 The reason for this exception is to avoid clashes
17939 with the standard names for children of System, Ada, Interfaces,
17940 and GNAT, which use the prefixes
17941 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17942 respectively.
17943
17944 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17945 switch of the compiler activates a ``krunching''
17946 circuit that limits file names to nn characters (where nn is a decimal
17947 integer). For example, using OpenVMS,
17948 where the maximum file name length is
17949 39, the value of nn is usually set to 39, but if you want to generate
17950 a set of files that would be usable if ported to a system with some
17951 different maximum file length, then a different value can be specified.
17952 The default value of 39 for OpenVMS need not be specified.
17953
17954 The @code{gnatkr} utility can be used to determine the krunched name for
17955 a given file, when krunched to a specified maximum length.
17956
17957 @node Using gnatkr
17958 @section Using @code{gnatkr}
17959
17960 @noindent
17961 The @code{gnatkr} command has the form
17962
17963 @ifclear vms
17964 @smallexample
17965 $ gnatkr @var{name} @ovar{length}
17966 @end smallexample
17967 @end ifclear
17968
17969 @ifset vms
17970 @smallexample
17971 $ gnatkr @var{name} /COUNT=nn
17972 @end smallexample
17973 @end ifset
17974
17975 @noindent
17976 @var{name} is the uncrunched file name, derived from the name of the unit
17977 in the standard manner described in the previous section (i.e., in particular
17978 all dots are replaced by hyphens). The file name may or may not have an
17979 extension (defined as a suffix of the form period followed by arbitrary
17980 characters other than period). If an extension is present then it will
17981 be preserved in the output. For example, when krunching @file{hellofile.ads}
17982 to eight characters, the result will be hellofil.ads.
17983
17984 Note: for compatibility with previous versions of @code{gnatkr} dots may
17985 appear in the name instead of hyphens, but the last dot will always be
17986 taken as the start of an extension. So if @code{gnatkr} is given an argument
17987 such as @file{Hello.World.adb} it will be treated exactly as if the first
17988 period had been a hyphen, and for example krunching to eight characters
17989 gives the result @file{hellworl.adb}.
17990
17991 Note that the result is always all lower case (except on OpenVMS where it is
17992 all upper case). Characters of the other case are folded as required.
17993
17994 @var{length} represents the length of the krunched name. The default
17995 when no argument is given is ^8^39^ characters. A length of zero stands for
17996 unlimited, in other words do not chop except for system files where the
17997 implied crunching length is always eight characters.
17998
17999 @noindent
18000 The output is the krunched name. The output has an extension only if the
18001 original argument was a file name with an extension.
18002
18003 @node Krunching Method
18004 @section Krunching Method
18005
18006 @noindent
18007 The initial file name is determined by the name of the unit that the file
18008 contains. The name is formed by taking the full expanded name of the
18009 unit and replacing the separating dots with hyphens and
18010 using ^lowercase^uppercase^
18011 for all letters, except that a hyphen in the second character position is
18012 replaced by a ^tilde^dollar sign^ if the first character is
18013 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18014 The extension is @code{.ads} for a
18015 spec and @code{.adb} for a body.
18016 Krunching does not affect the extension, but the file name is shortened to
18017 the specified length by following these rules:
18018
18019 @itemize @bullet
18020 @item
18021 The name is divided into segments separated by hyphens, tildes or
18022 underscores and all hyphens, tildes, and underscores are
18023 eliminated. If this leaves the name short enough, we are done.
18024
18025 @item
18026 If the name is too long, the longest segment is located (left-most
18027 if there are two of equal length), and shortened by dropping
18028 its last character. This is repeated until the name is short enough.
18029
18030 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18031 to fit the name into 8 characters as required by some operating systems.
18032
18033 @smallexample
18034 our-strings-wide_fixed 22
18035 our strings wide fixed 19
18036 our string  wide fixed 18
18037 our strin   wide fixed 17
18038 our stri    wide fixed 16
18039 our stri    wide fixe  15
18040 our str     wide fixe  14
18041 our str     wid  fixe  13
18042 our str     wid  fix   12
18043 ou  str     wid  fix   11
18044 ou  st      wid  fix   10
18045 ou  st      wi   fix   9
18046 ou  st      wi   fi    8
18047 Final file name: oustwifi.adb
18048 @end smallexample
18049
18050 @item
18051 The file names for all predefined units are always krunched to eight
18052 characters. The krunching of these predefined units uses the following
18053 special prefix replacements:
18054
18055 @table @file
18056 @item ada-
18057 replaced by @file{^a^A^-}
18058
18059 @item gnat-
18060 replaced by @file{^g^G^-}
18061
18062 @item interfaces-
18063 replaced by @file{^i^I^-}
18064
18065 @item system-
18066 replaced by @file{^s^S^-}
18067 @end table
18068
18069 These system files have a hyphen in the second character position. That
18070 is why normal user files replace such a character with a
18071 ^tilde^dollar sign^, to
18072 avoid confusion with system file names.
18073
18074 As an example of this special rule, consider
18075 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18076
18077 @smallexample
18078 ada-strings-wide_fixed 22
18079 a-  strings wide fixed 18
18080 a-  string  wide fixed 17
18081 a-  strin   wide fixed 16
18082 a-  stri    wide fixed 15
18083 a-  stri    wide fixe  14
18084 a-  str     wide fixe  13
18085 a-  str     wid  fixe  12
18086 a-  str     wid  fix   11
18087 a-  st      wid  fix   10
18088 a-  st      wi   fix   9
18089 a-  st      wi   fi    8
18090 Final file name: a-stwifi.adb
18091 @end smallexample
18092 @end itemize
18093
18094 Of course no file shortening algorithm can guarantee uniqueness over all
18095 possible unit names, and if file name krunching is used then it is your
18096 responsibility to ensure that no name clashes occur. The utility
18097 program @code{gnatkr} is supplied for conveniently determining the
18098 krunched name of a file.
18099
18100 @node Examples of gnatkr Usage
18101 @section Examples of @code{gnatkr} Usage
18102
18103 @smallexample
18104 @iftex
18105 @leftskip=0cm
18106 @end iftex
18107 @ifclear vms
18108 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18109 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18110 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18111 $ gnatkr grandparent-parent-child     --> grparchi
18112 @end ifclear
18113 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18114 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18115 @end smallexample
18116
18117 @node Preprocessing Using gnatprep
18118 @chapter Preprocessing Using @code{gnatprep}
18119 @findex gnatprep
18120
18121 @noindent
18122 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18123 preprocessing.
18124 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18125 special GNAT features.
18126 For further discussion of conditional compilation in general, see
18127 @ref{Conditional Compilation}.
18128
18129 @menu
18130 * Preprocessing Symbols::
18131 * Using gnatprep::
18132 * Switches for gnatprep::
18133 * Form of Definitions File::
18134 * Form of Input Text for gnatprep::
18135 @end menu
18136
18137 @node Preprocessing Symbols
18138 @section Preprocessing Symbols
18139
18140 @noindent
18141 Preprocessing symbols are defined in definition files and referred to in
18142 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18143 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18144 all characters need to be in the ASCII set (no accented letters).
18145
18146 @node Using gnatprep
18147 @section Using @code{gnatprep}
18148
18149 @noindent
18150 To call @code{gnatprep} use
18151
18152 @smallexample
18153 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18154 @end smallexample
18155
18156 @noindent
18157 where
18158 @table @var
18159 @item switches
18160 is an optional sequence of switches as described in the next section.
18161
18162 @item infile
18163 is the full name of the input file, which is an Ada source
18164 file containing preprocessor directives.
18165
18166 @item outfile
18167 is the full name of the output file, which is an Ada source
18168 in standard Ada form. When used with GNAT, this file name will
18169 normally have an ads or adb suffix.
18170
18171 @item deffile
18172 is the full name of a text file containing definitions of
18173 preprocessing symbols to be referenced by the preprocessor. This argument is
18174 optional, and can be replaced by the use of the @option{-D} switch.
18175
18176 @end table
18177
18178 @node Switches for gnatprep
18179 @section Switches for @code{gnatprep}
18180
18181 @table @option
18182 @c !sort!
18183
18184 @item ^-b^/BLANK_LINES^
18185 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18186 Causes both preprocessor lines and the lines deleted by
18187 preprocessing to be replaced by blank lines in the output source file,
18188 preserving line numbers in the output file.
18189
18190 @item ^-c^/COMMENTS^
18191 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18192 Causes both preprocessor lines and the lines deleted
18193 by preprocessing to be retained in the output source as comments marked
18194 with the special string @code{"--! "}. This option will result in line numbers
18195 being preserved in the output file.
18196
18197 @item ^-C^/REPLACE_IN_COMMENTS^
18198 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18199 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18200 If this option is specified, then comments are scanned and any $symbol
18201 substitutions performed as in program text. This is particularly useful
18202 when structured comments are used (e.g., when writing programs in the
18203 SPARK dialect of Ada). Note that this switch is not available when
18204 doing integrated preprocessing (it would be useless in this context
18205 since comments are ignored by the compiler in any case).
18206
18207 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18208 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18209 Defines a new preprocessing symbol, associated with value. If no value is given
18210 on the command line, then symbol is considered to be @code{True}. This switch
18211 can be used in place of a definition file.
18212
18213 @ifset vms
18214 @item /REMOVE
18215 @cindex @option{/REMOVE} (@command{gnatprep})
18216 This is the default setting which causes lines deleted by preprocessing
18217 to be entirely removed from the output file.
18218 @end ifset
18219
18220 @item ^-r^/REFERENCE^
18221 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18222 Causes a @code{Source_Reference} pragma to be generated that
18223 references the original input file, so that error messages will use
18224 the file name of this original file. The use of this switch implies
18225 that preprocessor lines are not to be removed from the file, so its
18226 use will force @option{^-b^/BLANK_LINES^} mode if
18227 @option{^-c^/COMMENTS^}
18228 has not been specified explicitly.
18229
18230 Note that if the file to be preprocessed contains multiple units, then
18231 it will be necessary to @code{gnatchop} the output file from
18232 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18233 in the preprocessed file, it will be respected by
18234 @code{gnatchop ^-r^/REFERENCE^}
18235 so that the final chopped files will correctly refer to the original
18236 input source file for @code{gnatprep}.
18237
18238 @item ^-s^/SYMBOLS^
18239 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18240 Causes a sorted list of symbol names and values to be
18241 listed on the standard output file.
18242
18243 @item ^-u^/UNDEFINED^
18244 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18245 Causes undefined symbols to be treated as having the value FALSE in the context
18246 of a preprocessor test. In the absence of this option, an undefined symbol in
18247 a @code{#if} or @code{#elsif} test will be treated as an error.
18248
18249 @end table
18250
18251 @ifclear vms
18252 @noindent
18253 Note: if neither @option{-b} nor @option{-c} is present,
18254 then preprocessor lines and
18255 deleted lines are completely removed from the output, unless -r is
18256 specified, in which case -b is assumed.
18257 @end ifclear
18258
18259 @node Form of Definitions File
18260 @section Form of Definitions File
18261
18262 @noindent
18263 The definitions file contains lines of the form
18264
18265 @smallexample
18266 symbol := value
18267 @end smallexample
18268
18269 @noindent
18270 where symbol is a preprocessing symbol, and value is one of the following:
18271
18272 @itemize @bullet
18273 @item
18274 Empty, corresponding to a null substitution
18275 @item
18276 A string literal using normal Ada syntax
18277 @item
18278 Any sequence of characters from the set
18279 (letters, digits, period, underline).
18280 @end itemize
18281
18282 @noindent
18283 Comment lines may also appear in the definitions file, starting with
18284 the usual @code{--},
18285 and comments may be added to the definitions lines.
18286
18287 @node Form of Input Text for gnatprep
18288 @section Form of Input Text for @code{gnatprep}
18289
18290 @noindent
18291 The input text may contain preprocessor conditional inclusion lines,
18292 as well as general symbol substitution sequences.
18293
18294 The preprocessor conditional inclusion commands have the form
18295
18296 @smallexample
18297 @group
18298 @cartouche
18299 #if @i{expression} @r{[}then@r{]}
18300    lines
18301 #elsif @i{expression} @r{[}then@r{]}
18302    lines
18303 #elsif @i{expression} @r{[}then@r{]}
18304    lines
18305 @dots{}
18306 #else
18307    lines
18308 #end if;
18309 @end cartouche
18310 @end group
18311 @end smallexample
18312
18313 @noindent
18314 In this example, @i{expression} is defined by the following grammar:
18315 @smallexample
18316 @i{expression} ::=  <symbol>
18317 @i{expression} ::=  <symbol> = "<value>"
18318 @i{expression} ::=  <symbol> = <symbol>
18319 @i{expression} ::=  <symbol> 'Defined
18320 @i{expression} ::=  not @i{expression}
18321 @i{expression} ::=  @i{expression} and @i{expression}
18322 @i{expression} ::=  @i{expression} or @i{expression}
18323 @i{expression} ::=  @i{expression} and then @i{expression}
18324 @i{expression} ::=  @i{expression} or else @i{expression}
18325 @i{expression} ::=  ( @i{expression} )
18326 @end smallexample
18327
18328 The following restriction exists: it is not allowed to have "and" or "or"
18329 following "not" in the same expression without parentheses. For example, this
18330 is not allowed:
18331
18332 @smallexample
18333    not X or Y
18334 @end smallexample
18335
18336 This should be one of the following:
18337
18338 @smallexample
18339    (not X) or Y
18340    not (X or Y)
18341 @end smallexample
18342
18343 @noindent
18344 For the first test (@i{expression} ::= <symbol>) the symbol must have
18345 either the value true or false, that is to say the right-hand of the
18346 symbol definition must be one of the (case-insensitive) literals
18347 @code{True} or @code{False}. If the value is true, then the
18348 corresponding lines are included, and if the value is false, they are
18349 excluded.
18350
18351 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18352 the symbol has been defined in the definition file or by a @option{-D}
18353 switch on the command line. Otherwise, the test is false.
18354
18355 The equality tests are case insensitive, as are all the preprocessor lines.
18356
18357 If the symbol referenced is not defined in the symbol definitions file,
18358 then the effect depends on whether or not switch @option{-u}
18359 is specified. If so, then the symbol is treated as if it had the value
18360 false and the test fails. If this switch is not specified, then
18361 it is an error to reference an undefined symbol. It is also an error to
18362 reference a symbol that is defined with a value other than @code{True}
18363 or @code{False}.
18364
18365 The use of the @code{not} operator inverts the sense of this logical test.
18366 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18367 operators, without parentheses. For example, "if not X or Y then" is not
18368 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18369
18370 The @code{then} keyword is optional as shown
18371
18372 The @code{#} must be the first non-blank character on a line, but
18373 otherwise the format is free form. Spaces or tabs may appear between
18374 the @code{#} and the keyword. The keywords and the symbols are case
18375 insensitive as in normal Ada code. Comments may be used on a
18376 preprocessor line, but other than that, no other tokens may appear on a
18377 preprocessor line. Any number of @code{elsif} clauses can be present,
18378 including none at all. The @code{else} is optional, as in Ada.
18379
18380 The @code{#} marking the start of a preprocessor line must be the first
18381 non-blank character on the line, i.e., it must be preceded only by
18382 spaces or horizontal tabs.
18383
18384 Symbol substitution outside of preprocessor lines is obtained by using
18385 the sequence
18386
18387 @smallexample
18388 $symbol
18389 @end smallexample
18390
18391 @noindent
18392 anywhere within a source line, except in a comment or within a
18393 string literal. The identifier
18394 following the @code{$} must match one of the symbols defined in the symbol
18395 definition file, and the result is to substitute the value of the
18396 symbol in place of @code{$symbol} in the output file.
18397
18398 Note that although the substitution of strings within a string literal
18399 is not possible, it is possible to have a symbol whose defined value is
18400 a string literal. So instead of setting XYZ to @code{hello} and writing:
18401
18402 @smallexample
18403 Header : String := "$XYZ";
18404 @end smallexample
18405
18406 @noindent
18407 you should set XYZ to @code{"hello"} and write:
18408
18409 @smallexample
18410 Header : String := $XYZ;
18411 @end smallexample
18412
18413 @noindent
18414 and then the substitution will occur as desired.
18415
18416 @ifset vms
18417 @node The GNAT Run-Time Library Builder gnatlbr
18418 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18419 @findex gnatlbr
18420 @cindex Library builder
18421
18422 @noindent
18423 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18424 supplied configuration pragmas.
18425
18426 @menu
18427 * Running gnatlbr::
18428 * Switches for gnatlbr::
18429 * Examples of gnatlbr Usage::
18430 @end menu
18431
18432 @node Running gnatlbr
18433 @section Running @code{gnatlbr}
18434
18435 @noindent
18436 The @code{gnatlbr} command has the form
18437
18438 @smallexample
18439 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18440 @end smallexample
18441
18442 @node Switches for gnatlbr
18443 @section Switches for @code{gnatlbr}
18444
18445 @noindent
18446 @code{gnatlbr} recognizes the following switches:
18447
18448 @table @option
18449 @c !sort!
18450 @item /CREATE=directory
18451 @cindex @code{/CREATE} (@code{gnatlbr})
18452 Create the new run-time library in the specified directory.
18453
18454 @item /SET=directory
18455 @cindex @code{/SET} (@code{gnatlbr})
18456 Make the library in the specified directory the current run-time library.
18457
18458 @item /DELETE=directory
18459 @cindex @code{/DELETE} (@code{gnatlbr})
18460 Delete the run-time library in the specified directory.
18461
18462 @item /CONFIG=file
18463 @cindex @code{/CONFIG} (@code{gnatlbr})
18464 With /CREATE: Use the configuration pragmas in the specified file when
18465 building the library.
18466
18467 With /SET: Use the configuration pragmas in the specified file when
18468 compiling.
18469
18470 @end table
18471
18472 @node Examples of gnatlbr Usage
18473 @section Example of @code{gnatlbr} Usage
18474
18475 @smallexample
18476 Contents of VAXFLOAT.ADC:
18477 pragma Float_Representation (VAX_Float);
18478
18479 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18480
18481 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18482
18483 @end smallexample
18484 @end ifset
18485
18486 @node The GNAT Library Browser gnatls
18487 @chapter The GNAT Library Browser @code{gnatls}
18488 @findex gnatls
18489 @cindex Library browser
18490
18491 @noindent
18492 @code{gnatls} is a tool that outputs information about compiled
18493 units. It gives the relationship between objects, unit names and source
18494 files. It can also be used to check the source dependencies of a unit
18495 as well as various characteristics.
18496
18497 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18498 driver (see @ref{The GNAT Driver and Project Files}).
18499
18500 @menu
18501 * Running gnatls::
18502 * Switches for gnatls::
18503 * Examples of gnatls Usage::
18504 @end menu
18505
18506 @node Running gnatls
18507 @section Running @code{gnatls}
18508
18509 @noindent
18510 The @code{gnatls} command has the form
18511
18512 @smallexample
18513 $ gnatls switches @var{object_or_ali_file}
18514 @end smallexample
18515
18516 @noindent
18517 The main argument is the list of object or @file{ali} files
18518 (@pxref{The Ada Library Information Files})
18519 for which information is requested.
18520
18521 In normal mode, without additional option, @code{gnatls} produces a
18522 four-column listing. Each line represents information for a specific
18523 object. The first column gives the full path of the object, the second
18524 column gives the name of the principal unit in this object, the third
18525 column gives the status of the source and the fourth column gives the
18526 full path of the source representing this unit.
18527 Here is a simple example of use:
18528
18529 @smallexample
18530 $ gnatls *.o
18531 ^./^[]^demo1.o            demo1            DIF demo1.adb
18532 ^./^[]^demo2.o            demo2             OK demo2.adb
18533 ^./^[]^hello.o            h1                OK hello.adb
18534 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18535 ^./^[]^instr.o            instr             OK instr.adb
18536 ^./^[]^tef.o              tef              DIF tef.adb
18537 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18538 ^./^[]^tgef.o             tgef             DIF tgef.adb
18539 @end smallexample
18540
18541 @noindent
18542 The first line can be interpreted as follows: the main unit which is
18543 contained in
18544 object file @file{demo1.o} is demo1, whose main source is in
18545 @file{demo1.adb}. Furthermore, the version of the source used for the
18546 compilation of demo1 has been modified (DIF). Each source file has a status
18547 qualifier which can be:
18548
18549 @table @code
18550 @item OK (unchanged)
18551 The version of the source file used for the compilation of the
18552 specified unit corresponds exactly to the actual source file.
18553
18554 @item MOK (slightly modified)
18555 The version of the source file used for the compilation of the
18556 specified unit differs from the actual source file but not enough to
18557 require recompilation. If you use gnatmake with the qualifier
18558 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18559 MOK will not be recompiled.
18560
18561 @item DIF (modified)
18562 No version of the source found on the path corresponds to the source
18563 used to build this object.
18564
18565 @item ??? (file not found)
18566 No source file was found for this unit.
18567
18568 @item HID (hidden,  unchanged version not first on PATH)
18569 The version of the source that corresponds exactly to the source used
18570 for compilation has been found on the path but it is hidden by another
18571 version of the same source that has been modified.
18572
18573 @end table
18574
18575 @node Switches for gnatls
18576 @section Switches for @code{gnatls}
18577
18578 @noindent
18579 @code{gnatls} recognizes the following switches:
18580
18581 @table @option
18582 @c !sort!
18583 @cindex @option{--version} @command{gnatls}
18584 Display Copyright and version, then exit disregarding all other options.
18585
18586 @item --help
18587 @cindex @option{--help} @command{gnatls}
18588 If @option{--version} was not used, display usage, then exit disregarding
18589 all other options.
18590
18591 @item ^-a^/ALL_UNITS^
18592 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18593 Consider all units, including those of the predefined Ada library.
18594 Especially useful with @option{^-d^/DEPENDENCIES^}.
18595
18596 @item ^-d^/DEPENDENCIES^
18597 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18598 List sources from which specified units depend on.
18599
18600 @item ^-h^/OUTPUT=OPTIONS^
18601 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18602 Output the list of options.
18603
18604 @item ^-o^/OUTPUT=OBJECTS^
18605 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18606 Only output information about object files.
18607
18608 @item ^-s^/OUTPUT=SOURCES^
18609 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18610 Only output information about source files.
18611
18612 @item ^-u^/OUTPUT=UNITS^
18613 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18614 Only output information about compilation units.
18615
18616 @item ^-files^/FILES^=@var{file}
18617 @cindex @option{^-files^/FILES^} (@code{gnatls})
18618 Take as arguments the files listed in text file @var{file}.
18619 Text file @var{file} may contain empty lines that are ignored.
18620 Each nonempty line should contain the name of an existing file.
18621 Several such switches may be specified simultaneously.
18622
18623 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18624 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18625 @itemx ^-I^/SEARCH=^@var{dir}
18626 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18627 @itemx -nostdinc
18628 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18629 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18630 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18631 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18632 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18633 flags (@pxref{Switches for gnatmake}).
18634
18635 @item --RTS=@var{rts-path}
18636 @cindex @option{--RTS} (@code{gnatls})
18637 Specifies the default location of the runtime library. Same meaning as the
18638 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18639
18640 @item ^-v^/OUTPUT=VERBOSE^
18641 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18642 Verbose mode. Output the complete source, object and project paths. Do not use
18643 the default column layout but instead use long format giving as much as
18644 information possible on each requested units, including special
18645 characteristics such as:
18646
18647 @table @code
18648 @item  Preelaborable
18649 The unit is preelaborable in the Ada sense.
18650
18651 @item No_Elab_Code
18652 No elaboration code has been produced by the compiler for this unit.
18653
18654 @item Pure
18655 The unit is pure in the Ada sense.
18656
18657 @item Elaborate_Body
18658 The unit contains a pragma Elaborate_Body.
18659
18660 @item Remote_Types
18661 The unit contains a pragma Remote_Types.
18662
18663 @item Shared_Passive
18664 The unit contains a pragma Shared_Passive.
18665
18666 @item Predefined
18667 This unit is part of the predefined environment and cannot be modified
18668 by the user.
18669
18670 @item Remote_Call_Interface
18671 The unit contains a pragma Remote_Call_Interface.
18672
18673 @end table
18674
18675 @end table
18676
18677 @node Examples of gnatls Usage
18678 @section Example of @code{gnatls} Usage
18679 @ifclear vms
18680
18681 @noindent
18682 Example of using the verbose switch. Note how the source and
18683 object paths are affected by the -I switch.
18684
18685 @smallexample
18686 $ gnatls -v -I.. demo1.o
18687
18688 GNATLS 5.03w (20041123-34)
18689 Copyright 1997-2004 Free Software Foundation, Inc.
18690
18691 Source Search Path:
18692    <Current_Directory>
18693    ../
18694    /home/comar/local/adainclude/
18695
18696 Object Search Path:
18697    <Current_Directory>
18698    ../
18699    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18700
18701 Project Search Path:
18702    <Current_Directory>
18703    /home/comar/local/lib/gnat/
18704
18705 ./demo1.o
18706    Unit =>
18707      Name   => demo1
18708      Kind   => subprogram body
18709      Flags  => No_Elab_Code
18710      Source => demo1.adb    modified
18711 @end smallexample
18712
18713 @noindent
18714 The following is an example of use of the dependency list.
18715 Note the use of the -s switch
18716 which gives a straight list of source files. This can be useful for
18717 building specialized scripts.
18718
18719 @smallexample
18720 $ gnatls -d demo2.o
18721 ./demo2.o   demo2        OK demo2.adb
18722                          OK gen_list.ads
18723                          OK gen_list.adb
18724                          OK instr.ads
18725                          OK instr-child.ads
18726
18727 $ gnatls -d -s -a demo1.o
18728 demo1.adb
18729 /home/comar/local/adainclude/ada.ads
18730 /home/comar/local/adainclude/a-finali.ads
18731 /home/comar/local/adainclude/a-filico.ads
18732 /home/comar/local/adainclude/a-stream.ads
18733 /home/comar/local/adainclude/a-tags.ads
18734 gen_list.ads
18735 gen_list.adb
18736 /home/comar/local/adainclude/gnat.ads
18737 /home/comar/local/adainclude/g-io.ads
18738 instr.ads
18739 /home/comar/local/adainclude/system.ads
18740 /home/comar/local/adainclude/s-exctab.ads
18741 /home/comar/local/adainclude/s-finimp.ads
18742 /home/comar/local/adainclude/s-finroo.ads
18743 /home/comar/local/adainclude/s-secsta.ads
18744 /home/comar/local/adainclude/s-stalib.ads
18745 /home/comar/local/adainclude/s-stoele.ads
18746 /home/comar/local/adainclude/s-stratt.ads
18747 /home/comar/local/adainclude/s-tasoli.ads
18748 /home/comar/local/adainclude/s-unstyp.ads
18749 /home/comar/local/adainclude/unchconv.ads
18750 @end smallexample
18751 @end ifclear
18752
18753 @ifset vms
18754 @smallexample
18755 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18756
18757 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18758 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18759 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18760 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18761 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18762 demo1.adb
18763 gen_list.ads
18764 gen_list.adb
18765 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18766 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18767 instr.ads
18768 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18769 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18770 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18771 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18772 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18773 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18774 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18775 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18776 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18777 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18778 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18779 @end smallexample
18780 @end ifset
18781
18782 @node Cleaning Up Using gnatclean
18783 @chapter Cleaning Up Using @code{gnatclean}
18784 @findex gnatclean
18785 @cindex Cleaning tool
18786
18787 @noindent
18788 @code{gnatclean} is a tool that allows the deletion of files produced by the
18789 compiler, binder and linker, including ALI files, object files, tree files,
18790 expanded source files, library files, interface copy source files, binder
18791 generated files and executable files.
18792
18793 @menu
18794 * Running gnatclean::
18795 * Switches for gnatclean::
18796 @c * Examples of gnatclean Usage::
18797 @end menu
18798
18799 @node Running gnatclean
18800 @section Running @code{gnatclean}
18801
18802 @noindent
18803 The @code{gnatclean} command has the form:
18804
18805 @smallexample
18806 $ gnatclean switches @var{names}
18807 @end smallexample
18808
18809 @noindent
18810 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18811 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18812 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18813
18814 @noindent
18815 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18816 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18817 the linker. In informative-only mode, specified by switch
18818 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18819 normal mode is listed, but no file is actually deleted.
18820
18821 @node Switches for gnatclean
18822 @section Switches for @code{gnatclean}
18823
18824 @noindent
18825 @code{gnatclean} recognizes the following switches:
18826
18827 @table @option
18828 @c !sort!
18829 @cindex @option{--version} @command{gnatclean}
18830 Display Copyright and version, then exit disregarding all other options.
18831
18832 @item --help
18833 @cindex @option{--help} @command{gnatclean}
18834 If @option{--version} was not used, display usage, then exit disregarding
18835 all other options.
18836
18837 @item ^-c^/COMPILER_FILES_ONLY^
18838 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18839 Only attempt to delete the files produced by the compiler, not those produced
18840 by the binder or the linker. The files that are not to be deleted are library
18841 files, interface copy files, binder generated files and executable files.
18842
18843 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18844 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18845 Indicate that ALI and object files should normally be found in directory
18846 @var{dir}.
18847
18848 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18849 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18850 When using project files, if some errors or warnings are detected during
18851 parsing and verbose mode is not in effect (no use of switch
18852 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18853 file, rather than its simple file name.
18854
18855 @item ^-h^/HELP^
18856 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18857 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18858
18859 @item ^-n^/NODELETE^
18860 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18861 Informative-only mode. Do not delete any files. Output the list of the files
18862 that would have been deleted if this switch was not specified.
18863
18864 @item ^-P^/PROJECT_FILE=^@var{project}
18865 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18866 Use project file @var{project}. Only one such switch can be used.
18867 When cleaning a project file, the files produced by the compilation of the
18868 immediate sources or inherited sources of the project files are to be
18869 deleted. This is not depending on the presence or not of executable names
18870 on the command line.
18871
18872 @item ^-q^/QUIET^
18873 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18874 Quiet output. If there are no errors, do not output anything, except in
18875 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18876 (switch ^-n^/NODELETE^).
18877
18878 @item ^-r^/RECURSIVE^
18879 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18880 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18881 clean all imported and extended project files, recursively. If this switch
18882 is not specified, only the files related to the main project file are to be
18883 deleted. This switch has no effect if no project file is specified.
18884
18885 @item ^-v^/VERBOSE^
18886 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18887 Verbose mode.
18888
18889 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18890 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18891 Indicates the verbosity of the parsing of GNAT project files.
18892 @xref{Switches Related to Project Files}.
18893
18894 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18895 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18896 Indicates that external variable @var{name} has the value @var{value}.
18897 The Project Manager will use this value for occurrences of
18898 @code{external(name)} when parsing the project file.
18899 @xref{Switches Related to Project Files}.
18900
18901 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18902 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18903 When searching for ALI and object files, look in directory
18904 @var{dir}.
18905
18906 @item ^-I^/SEARCH=^@var{dir}
18907 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18908 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18909
18910 @item ^-I-^/NOCURRENT_DIRECTORY^
18911 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18912 @cindex Source files, suppressing search
18913 Do not look for ALI or object files in the directory
18914 where @code{gnatclean} was invoked.
18915
18916 @end table
18917
18918 @c @node Examples of gnatclean Usage
18919 @c @section Examples of @code{gnatclean} Usage
18920
18921 @ifclear vms
18922 @node GNAT and Libraries
18923 @chapter GNAT and Libraries
18924 @cindex Library, building, installing, using
18925
18926 @noindent
18927 This chapter describes how to build and use libraries with GNAT, and also shows
18928 how to recompile the GNAT run-time library. You should be familiar with the
18929 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18930 chapter.
18931
18932 @menu
18933 * Introduction to Libraries in GNAT::
18934 * General Ada Libraries::
18935 * Stand-alone Ada Libraries::
18936 * Rebuilding the GNAT Run-Time Library::
18937 @end menu
18938
18939 @node Introduction to Libraries in GNAT
18940 @section Introduction to Libraries in GNAT
18941
18942 @noindent
18943 A library is, conceptually, a collection of objects which does not have its
18944 own main thread of execution, but rather provides certain services to the
18945 applications that use it. A library can be either statically linked with the
18946 application, in which case its code is directly included in the application,
18947 or, on platforms that support it, be dynamically linked, in which case
18948 its code is shared by all applications making use of this library.
18949
18950 GNAT supports both types of libraries.
18951 In the static case, the compiled code can be provided in different ways. The
18952 simplest approach is to provide directly the set of objects resulting from
18953 compilation of the library source files. Alternatively, you can group the
18954 objects into an archive using whatever commands are provided by the operating
18955 system. For the latter case, the objects are grouped into a shared library.
18956
18957 In the GNAT environment, a library has three types of components:
18958 @itemize @bullet
18959 @item
18960 Source files.
18961 @item
18962 @file{ALI} files.
18963 @xref{The Ada Library Information Files}.
18964 @item
18965 Object files, an archive or a shared library.
18966 @end itemize
18967
18968 @noindent
18969 A GNAT library may expose all its source files, which is useful for
18970 documentation purposes. Alternatively, it may expose only the units needed by
18971 an external user to make use of the library. That is to say, the specs
18972 reflecting the library services along with all the units needed to compile
18973 those specs, which can include generic bodies or any body implementing an
18974 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18975 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18976
18977 All compilation units comprising an application, including those in a library,
18978 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18979 computes the elaboration order from the @file{ALI} files and this is why they
18980 constitute a mandatory part of GNAT libraries.
18981 @emph{Stand-alone libraries} are the exception to this rule because a specific
18982 library elaboration routine is produced independently of the application(s)
18983 using the library.
18984
18985 @node General Ada Libraries
18986 @section General Ada Libraries
18987
18988 @menu
18989 * Building a library::
18990 * Installing a library::
18991 * Using a library::
18992 @end menu
18993
18994 @node Building a library
18995 @subsection Building a library
18996
18997 @noindent
18998 The easiest way to build a library is to use the Project Manager,
18999 which supports a special type of project called a @emph{Library Project}
19000 (@pxref{Library Projects}).
19001
19002 A project is considered a library project, when two project-level attributes
19003 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19004 control different aspects of library configuration, additional optional
19005 project-level attributes can be specified:
19006 @table @code
19007 @item Library_Kind
19008 This attribute controls whether the library is to be static or dynamic
19009
19010 @item Library_Version
19011 This attribute specifies the library version; this value is used
19012 during dynamic linking of shared libraries to determine if the currently
19013 installed versions of the binaries are compatible.
19014
19015 @item Library_Options
19016 @item Library_GCC
19017 These attributes specify additional low-level options to be used during
19018 library generation, and redefine the actual application used to generate
19019 library.
19020 @end table
19021
19022 @noindent
19023 The GNAT Project Manager takes full care of the library maintenance task,
19024 including recompilation of the source files for which objects do not exist
19025 or are not up to date, assembly of the library archive, and installation of
19026 the library (i.e., copying associated source, object and @file{ALI} files
19027 to the specified location).
19028
19029 Here is a simple library project file:
19030 @smallexample @c ada
19031 project My_Lib is
19032    for Source_Dirs use ("src1", "src2");
19033    for Object_Dir use "obj";
19034    for Library_Name use "mylib";
19035    for Library_Dir use "lib";
19036    for Library_Kind use "dynamic";
19037 end My_lib;
19038 @end smallexample
19039
19040 @noindent
19041 and the compilation command to build and install the library:
19042
19043 @smallexample @c ada
19044   $ gnatmake -Pmy_lib
19045 @end smallexample
19046
19047 @noindent
19048 It is not entirely trivial to perform manually all the steps required to
19049 produce a library. We recommend that you use the GNAT Project Manager
19050 for this task. In special cases where this is not desired, the necessary
19051 steps are discussed below.
19052
19053 There are various possibilities for compiling the units that make up the
19054 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19055 with a conventional script. For simple libraries, it is also possible to create
19056 a dummy main program which depends upon all the packages that comprise the
19057 interface of the library. This dummy main program can then be given to
19058 @command{gnatmake}, which will ensure that all necessary objects are built.
19059
19060 After this task is accomplished, you should follow the standard procedure
19061 of the underlying operating system to produce the static or shared library.
19062
19063 Here is an example of such a dummy program:
19064 @smallexample @c ada
19065 @group
19066 with My_Lib.Service1;
19067 with My_Lib.Service2;
19068 with My_Lib.Service3;
19069 procedure My_Lib_Dummy is
19070 begin
19071    null;
19072 end;
19073 @end group
19074 @end smallexample
19075
19076 @noindent
19077 Here are the generic commands that will build an archive or a shared library.
19078
19079 @smallexample
19080 # compiling the library
19081 $ gnatmake -c my_lib_dummy.adb
19082
19083 # we don't need the dummy object itself
19084 $ rm my_lib_dummy.o my_lib_dummy.ali
19085
19086 # create an archive with the remaining objects
19087 $ ar rc libmy_lib.a *.o
19088 # some systems may require "ranlib" to be run as well
19089
19090 # or create a shared library
19091 $ gcc -shared -o libmy_lib.so *.o
19092 # some systems may require the code to have been compiled with -fPIC
19093
19094 # remove the object files that are now in the library
19095 $ rm *.o
19096
19097 # Make the ALI files read-only so that gnatmake will not try to
19098 # regenerate the objects that are in the library
19099 $ chmod -w *.ali
19100 @end smallexample
19101
19102 @noindent
19103 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19104 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19105 be accessed by the directive @option{-l@var{xxx}} at link time.
19106
19107 @node Installing a library
19108 @subsection Installing a library
19109 @cindex @code{ADA_PROJECT_PATH}
19110 @cindex @code{GPR_PROJECT_PATH}
19111
19112 @noindent
19113 If you use project files, library installation is part of the library build
19114 process. Thus no further action is needed in order to make use of the
19115 libraries that are built as part of the general application build. A usable
19116 version of the library is installed in the directory specified by the
19117 @code{Library_Dir} attribute of the library project file.
19118
19119 You may want to install a library in a context different from where the library
19120 is built. This situation arises with third party suppliers, who may want
19121 to distribute a library in binary form where the user is not expected to be
19122 able to recompile the library. The simplest option in this case is to provide
19123 a project file slightly different from the one used to build the library, by
19124 using the @code{externally_built} attribute. For instance, the project
19125 file used to build the library in the previous section can be changed into the
19126 following one when the library is installed:
19127
19128 @smallexample @c projectfile
19129 project My_Lib is
19130    for Source_Dirs use ("src1", "src2");
19131    for Library_Name use "mylib";
19132    for Library_Dir use "lib";
19133    for Library_Kind use "dynamic";
19134    for Externally_Built use "true";
19135 end My_lib;
19136 @end smallexample
19137
19138 @noindent
19139 This project file assumes that the directories @file{src1},
19140 @file{src2}, and @file{lib} exist in
19141 the directory containing the project file. The @code{externally_built}
19142 attribute makes it clear to the GNAT builder that it should not attempt to
19143 recompile any of the units from this library. It allows the library provider to
19144 restrict the source set to the minimum necessary for clients to make use of the
19145 library as described in the first section of this chapter. It is the
19146 responsibility of the library provider to install the necessary sources, ALI
19147 files and libraries in the directories mentioned in the project file. For
19148 convenience, the user's library project file should be installed in a location
19149 that will be searched automatically by the GNAT
19150 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19151 environment variable (@pxref{Importing Projects}), and also the default GNAT
19152 library location that can be queried with @command{gnatls -v} and is usually of
19153 the form $gnat_install_root/lib/gnat.
19154
19155 When project files are not an option, it is also possible, but not recommended,
19156 to install the library so that the sources needed to use the library are on the
19157 Ada source path and the ALI files & libraries be on the Ada Object path (see
19158 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19159 administrator can place general-purpose libraries in the default compiler
19160 paths, by specifying the libraries' location in the configuration files
19161 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19162 must be located in the GNAT installation tree at the same place as the gcc spec
19163 file. The location of the gcc spec file can be determined as follows:
19164 @smallexample
19165 $ gcc -v
19166 @end smallexample
19167
19168 @noindent
19169 The configuration files mentioned above have a simple format: each line
19170 must contain one unique directory name.
19171 Those names are added to the corresponding path
19172 in their order of appearance in the file. The names can be either absolute
19173 or relative; in the latter case, they are relative to where theses files
19174 are located.
19175
19176 The files @file{ada_source_path} and @file{ada_object_path} might not be
19177 present in a
19178 GNAT installation, in which case, GNAT will look for its run-time library in
19179 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19180 objects and @file{ALI} files). When the files exist, the compiler does not
19181 look in @file{adainclude} and @file{adalib}, and thus the
19182 @file{ada_source_path} file
19183 must contain the location for the GNAT run-time sources (which can simply
19184 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19185 contain the location for the GNAT run-time objects (which can simply
19186 be @file{adalib}).
19187
19188 You can also specify a new default path to the run-time library at compilation
19189 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19190 the run-time library you want your program to be compiled with. This switch is
19191 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19192 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19193
19194 It is possible to install a library before or after the standard GNAT
19195 library, by reordering the lines in the configuration files. In general, a
19196 library must be installed before the GNAT library if it redefines
19197 any part of it.
19198
19199 @node Using a library
19200 @subsection Using a library
19201
19202 @noindent Once again, the project facility greatly simplifies the use of
19203 libraries. In this context, using a library is just a matter of adding a
19204 @code{with} clause in the user project. For instance, to make use of the
19205 library @code{My_Lib} shown in examples in earlier sections, you can
19206 write:
19207
19208 @smallexample @c projectfile
19209 with "my_lib";
19210 project My_Proj is
19211   @dots{}
19212 end My_Proj;
19213 @end smallexample
19214
19215 Even if you have a third-party, non-Ada library, you can still use GNAT's
19216 Project Manager facility to provide a wrapper for it. For example, the
19217 following project, when @code{with}ed by your main project, will link with the
19218 third-party library @file{liba.a}:
19219
19220 @smallexample @c projectfile
19221 @group
19222 project Liba is
19223    for Externally_Built use "true";
19224    for Source_Files use ();
19225    for Library_Dir use "lib";
19226    for Library_Name use "a";
19227    for Library_Kind use "static";
19228 end Liba;
19229 @end group
19230 @end smallexample
19231 This is an alternative to the use of @code{pragma Linker_Options}. It is
19232 especially interesting in the context of systems with several interdependent
19233 static libraries where finding a proper linker order is not easy and best be
19234 left to the tools having visibility over project dependence information.
19235
19236 @noindent
19237 In order to use an Ada library manually, you need to make sure that this
19238 library is on both your source and object path
19239 (see @ref{Search Paths and the Run-Time Library (RTL)}
19240 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19241 in an archive or a shared library, you need to specify the desired
19242 library at link time.
19243
19244 For example, you can use the library @file{mylib} installed in
19245 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19246
19247 @smallexample
19248 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19249   -largs -lmy_lib
19250 @end smallexample
19251
19252 @noindent
19253 This can be expressed more simply:
19254 @smallexample
19255 $ gnatmake my_appl
19256 @end smallexample
19257 @noindent
19258 when the following conditions are met:
19259 @itemize @bullet
19260 @item
19261 @file{/dir/my_lib_src} has been added by the user to the environment
19262 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19263 @file{ada_source_path}
19264 @item
19265 @file{/dir/my_lib_obj} has been added by the user to the environment
19266 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19267 @file{ada_object_path}
19268 @item
19269 a pragma @code{Linker_Options} has been added to one of the sources.
19270 For example:
19271
19272 @smallexample @c ada
19273 pragma Linker_Options ("-lmy_lib");
19274 @end smallexample
19275 @end itemize
19276
19277 @node Stand-alone Ada Libraries
19278 @section Stand-alone Ada Libraries
19279 @cindex Stand-alone library, building, using
19280
19281 @menu
19282 * Introduction to Stand-alone Libraries::
19283 * Building a Stand-alone Library::
19284 * Creating a Stand-alone Library to be used in a non-Ada context::
19285 * Restrictions in Stand-alone Libraries::
19286 @end menu
19287
19288 @node Introduction to Stand-alone Libraries
19289 @subsection Introduction to Stand-alone Libraries
19290
19291 @noindent
19292 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19293 necessary code to
19294 elaborate the Ada units that are included in the library. In contrast with
19295 an ordinary library, which consists of all sources, objects and @file{ALI}
19296 files of the
19297 library, a SAL may specify a restricted subset of compilation units
19298 to serve as a library interface. In this case, the fully
19299 self-sufficient set of files will normally consist of an objects
19300 archive, the sources of interface units' specs, and the @file{ALI}
19301 files of interface units.
19302 If an interface spec contains a generic unit or an inlined subprogram,
19303 the body's
19304 source must also be provided; if the units that must be provided in the source
19305 form depend on other units, the source and @file{ALI} files of those must
19306 also be provided.
19307
19308 The main purpose of a SAL is to minimize the recompilation overhead of client
19309 applications when a new version of the library is installed. Specifically,
19310 if the interface sources have not changed, client applications do not need to
19311 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19312 version, controlled by @code{Library_Version} attribute, is not changed,
19313 then the clients do not need to be relinked.
19314
19315 SALs also allow the library providers to minimize the amount of library source
19316 text exposed to the clients.  Such ``information hiding'' might be useful or
19317 necessary for various reasons.
19318
19319 Stand-alone libraries are also well suited to be used in an executable whose
19320 main routine is not written in Ada.
19321
19322 @node Building a Stand-alone Library
19323 @subsection Building a Stand-alone Library
19324
19325 @noindent
19326 GNAT's Project facility provides a simple way of building and installing
19327 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19328 To be a Stand-alone Library Project, in addition to the two attributes
19329 that make a project a Library Project (@code{Library_Name} and
19330 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19331 @code{Library_Interface} must be defined.  For example:
19332
19333 @smallexample @c projectfile
19334 @group
19335    for Library_Dir use "lib_dir";
19336    for Library_Name use "dummy";
19337    for Library_Interface use ("int1", "int1.child");
19338 @end group
19339 @end smallexample
19340
19341 @noindent
19342 Attribute @code{Library_Interface} has a non-empty string list value,
19343 each string in the list designating a unit contained in an immediate source
19344 of the project file.
19345
19346 When a Stand-alone Library is built, first the binder is invoked to build
19347 a package whose name depends on the library name
19348 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19349 This binder-generated package includes initialization and
19350 finalization procedures whose
19351 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19352 in the example
19353 above). The object corresponding to this package is included in the library.
19354
19355 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19356 calling of these procedures if a static SAL is built, or if a shared SAL
19357 is built
19358 with the project-level attribute @code{Library_Auto_Init} set to
19359 @code{"false"}.
19360
19361 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19362 (those that are listed in attribute @code{Library_Interface}) are copied to
19363 the Library Directory. As a consequence, only the Interface Units may be
19364 imported from Ada units outside of the library. If other units are imported,
19365 the binding phase will fail.
19366
19367 The attribute @code{Library_Src_Dir} may be specified for a
19368 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19369 single string value. Its value must be the path (absolute or relative to the
19370 project directory) of an existing directory. This directory cannot be the
19371 object directory or one of the source directories, but it can be the same as
19372 the library directory. The sources of the Interface
19373 Units of the library that are needed by an Ada client of the library will be
19374 copied to the designated directory, called the Interface Copy directory.
19375 These sources include the specs of the Interface Units, but they may also
19376 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19377 are used, or when there is a generic unit in the spec. Before the sources
19378 are copied to the Interface Copy directory, an attempt is made to delete all
19379 files in the Interface Copy directory.
19380
19381 Building stand-alone libraries by hand is somewhat tedious, but for those
19382 occasions when it is necessary here are the steps that you need to perform:
19383 @itemize @bullet
19384 @item
19385 Compile all library sources.
19386
19387 @item
19388 Invoke the binder with the switch @option{-n} (No Ada main program),
19389 with all the @file{ALI} files of the interfaces, and
19390 with the switch @option{-L} to give specific names to the @code{init}
19391 and @code{final} procedures.  For example:
19392 @smallexample
19393   gnatbind -n int1.ali int2.ali -Lsal1
19394 @end smallexample
19395
19396 @item
19397 Compile the binder generated file:
19398 @smallexample
19399   gcc -c b~int2.adb
19400 @end smallexample
19401
19402 @item
19403 Link the dynamic library with all the necessary object files,
19404 indicating to the linker the names of the @code{init} (and possibly
19405 @code{final}) procedures for automatic initialization (and finalization).
19406 The built library should be placed in a directory different from
19407 the object directory.
19408
19409 @item
19410 Copy the @code{ALI} files of the interface to the library directory,
19411 add in this copy an indication that it is an interface to a SAL
19412 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19413 with letter ``P'') and make the modified copy of the @file{ALI} file
19414 read-only.
19415 @end itemize
19416
19417 @noindent
19418 Using SALs is not different from using other libraries
19419 (see @ref{Using a library}).
19420
19421 @node Creating a Stand-alone Library to be used in a non-Ada context
19422 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19423
19424 @noindent
19425 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19426 a non-Ada context.
19427
19428 The only extra step required is to ensure that library interface subprograms
19429 are compatible with the main program, by means of @code{pragma Export}
19430 or @code{pragma Convention}.
19431
19432 Here is an example of simple library interface for use with C main program:
19433
19434 @smallexample @c ada
19435 package Interface is
19436
19437    procedure Do_Something;
19438    pragma Export (C, Do_Something, "do_something");
19439
19440    procedure Do_Something_Else;
19441    pragma Export (C, Do_Something_Else, "do_something_else");
19442
19443 end Interface;
19444 @end smallexample
19445
19446 @noindent
19447 On the foreign language side, you must provide a ``foreign'' view of the
19448 library interface; remember that it should contain elaboration routines in
19449 addition to interface subprograms.
19450
19451 The example below shows the content of @code{mylib_interface.h} (note
19452 that there is no rule for the naming of this file, any name can be used)
19453 @smallexample
19454 /* the library elaboration procedure */
19455 extern void mylibinit (void);
19456
19457 /* the library finalization procedure */
19458 extern void mylibfinal (void);
19459
19460 /* the interface exported by the library */
19461 extern void do_something (void);
19462 extern void do_something_else (void);
19463 @end smallexample
19464
19465 @noindent
19466 Libraries built as explained above can be used from any program, provided
19467 that the elaboration procedures (named @code{mylibinit} in the previous
19468 example) are called before the library services are used. Any number of
19469 libraries can be used simultaneously, as long as the elaboration
19470 procedure of each library is called.
19471
19472 Below is an example of a C program that uses the @code{mylib} library.
19473
19474 @smallexample
19475 #include "mylib_interface.h"
19476
19477 int
19478 main (void)
19479 @{
19480    /* First, elaborate the library before using it */
19481    mylibinit ();
19482
19483    /* Main program, using the library exported entities */
19484    do_something ();
19485    do_something_else ();
19486
19487    /* Library finalization at the end of the program */
19488    mylibfinal ();
19489    return 0;
19490 @}
19491 @end smallexample
19492
19493 @noindent
19494 Note that invoking any library finalization procedure generated by
19495 @code{gnatbind} shuts down the Ada run-time environment.
19496 Consequently, the
19497 finalization of all Ada libraries must be performed at the end of the program.
19498 No call to these libraries or to the Ada run-time library should be made
19499 after the finalization phase.
19500
19501 @node Restrictions in Stand-alone Libraries
19502 @subsection Restrictions in Stand-alone Libraries
19503
19504 @noindent
19505 The pragmas listed below should be used with caution inside libraries,
19506 as they can create incompatibilities with other Ada libraries:
19507 @itemize @bullet
19508 @item pragma @code{Locking_Policy}
19509 @item pragma @code{Queuing_Policy}
19510 @item pragma @code{Task_Dispatching_Policy}
19511 @item pragma @code{Unreserve_All_Interrupts}
19512 @end itemize
19513
19514 @noindent
19515 When using a library that contains such pragmas, the user must make sure
19516 that all libraries use the same pragmas with the same values. Otherwise,
19517 @code{Program_Error} will
19518 be raised during the elaboration of the conflicting
19519 libraries. The usage of these pragmas and its consequences for the user
19520 should therefore be well documented.
19521
19522 Similarly, the traceback in the exception occurrence mechanism should be
19523 enabled or disabled in a consistent manner across all libraries.
19524 Otherwise, Program_Error will be raised during the elaboration of the
19525 conflicting libraries.
19526
19527 If the @code{Version} or @code{Body_Version}
19528 attributes are used inside a library, then you need to
19529 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19530 libraries, so that version identifiers can be properly computed.
19531 In practice these attributes are rarely used, so this is unlikely
19532 to be a consideration.
19533
19534 @node  Rebuilding the GNAT Run-Time Library
19535 @section Rebuilding the GNAT Run-Time Library
19536 @cindex GNAT Run-Time Library, rebuilding
19537 @cindex Building the GNAT Run-Time Library
19538 @cindex Rebuilding the GNAT Run-Time Library
19539 @cindex Run-Time Library, rebuilding
19540
19541 @noindent
19542 It may be useful to recompile the GNAT library in various contexts, the
19543 most important one being the use of partition-wide configuration pragmas
19544 such as @code{Normalize_Scalars}. A special Makefile called
19545 @code{Makefile.adalib} is provided to that effect and can be found in
19546 the directory containing the GNAT library. The location of this
19547 directory depends on the way the GNAT environment has been installed and can
19548 be determined by means of the command:
19549
19550 @smallexample
19551 $ gnatls -v
19552 @end smallexample
19553
19554 @noindent
19555 The last entry in the object search path usually contains the
19556 gnat library. This Makefile contains its own documentation and in
19557 particular the set of instructions needed to rebuild a new library and
19558 to use it.
19559
19560 @node Using the GNU make Utility
19561 @chapter Using the GNU @code{make} Utility
19562 @findex make
19563
19564 @noindent
19565 This chapter offers some examples of makefiles that solve specific
19566 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19567 make, make, GNU @code{make}}), nor does it try to replace the
19568 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19569
19570 All the examples in this section are specific to the GNU version of
19571 make. Although @command{make} is a standard utility, and the basic language
19572 is the same, these examples use some advanced features found only in
19573 @code{GNU make}.
19574
19575 @menu
19576 * Using gnatmake in a Makefile::
19577 * Automatically Creating a List of Directories::
19578 * Generating the Command Line Switches::
19579 * Overcoming Command Line Length Limits::
19580 @end menu
19581
19582 @node Using gnatmake in a Makefile
19583 @section Using gnatmake in a Makefile
19584 @findex makefile
19585 @cindex GNU make
19586
19587 @noindent
19588 Complex project organizations can be handled in a very powerful way by
19589 using GNU make combined with gnatmake. For instance, here is a Makefile
19590 which allows you to build each subsystem of a big project into a separate
19591 shared library. Such a makefile allows you to significantly reduce the link
19592 time of very big applications while maintaining full coherence at
19593 each step of the build process.
19594
19595 The list of dependencies are handled automatically by
19596 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19597 the appropriate directories.
19598
19599 Note that you should also read the example on how to automatically
19600 create the list of directories
19601 (@pxref{Automatically Creating a List of Directories})
19602 which might help you in case your project has a lot of subdirectories.
19603
19604 @smallexample
19605 @iftex
19606 @leftskip=0cm
19607 @font@heightrm=cmr8
19608 @heightrm
19609 @end iftex
19610 ## This Makefile is intended to be used with the following directory
19611 ## configuration:
19612 ##  - The sources are split into a series of csc (computer software components)
19613 ##    Each of these csc is put in its own directory.
19614 ##    Their name are referenced by the directory names.
19615 ##    They will be compiled into shared library (although this would also work
19616 ##    with static libraries
19617 ##  - The main program (and possibly other packages that do not belong to any
19618 ##    csc is put in the top level directory (where the Makefile is).
19619 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19620 ##                    \_ second_csc (sources) __ lib (will contain the library)
19621 ##                    \_ @dots{}
19622 ## Although this Makefile is build for shared library, it is easy to modify
19623 ## to build partial link objects instead (modify the lines with -shared and
19624 ## gnatlink below)
19625 ##
19626 ## With this makefile, you can change any file in the system or add any new
19627 ## file, and everything will be recompiled correctly (only the relevant shared
19628 ## objects will be recompiled, and the main program will be re-linked).
19629
19630 # The list of computer software component for your project. This might be
19631 # generated automatically.
19632 CSC_LIST=aa bb cc
19633
19634 # Name of the main program (no extension)
19635 MAIN=main
19636
19637 # If we need to build objects with -fPIC, uncomment the following line
19638 #NEED_FPIC=-fPIC
19639
19640 # The following variable should give the directory containing libgnat.so
19641 # You can get this directory through 'gnatls -v'. This is usually the last
19642 # directory in the Object_Path.
19643 GLIB=@dots{}
19644
19645 # The directories for the libraries
19646 # (This macro expands the list of CSC to the list of shared libraries, you
19647 # could simply use the expanded form:
19648 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19649 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19650
19651 $@{MAIN@}: objects $@{LIB_DIR@}
19652     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19653     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19654
19655 objects::
19656     # recompile the sources
19657     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19658
19659 # Note: In a future version of GNAT, the following commands will be simplified
19660 # by a new tool, gnatmlib
19661 $@{LIB_DIR@}:
19662     mkdir -p $@{dir $@@ @}
19663     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19664     cd $@{dir $@@ @} && cp -f ../*.ali .
19665
19666 # The dependencies for the modules
19667 # Note that we have to force the expansion of *.o, since in some cases
19668 # make won't be able to do it itself.
19669 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19670 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19671 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19672
19673 # Make sure all of the shared libraries are in the path before starting the
19674 # program
19675 run::
19676     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19677
19678 clean::
19679     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19680     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19681     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19682     $@{RM@} *.o *.ali $@{MAIN@}
19683 @end smallexample
19684
19685 @node Automatically Creating a List of Directories
19686 @section Automatically Creating a List of Directories
19687
19688 @noindent
19689 In most makefiles, you will have to specify a list of directories, and
19690 store it in a variable. For small projects, it is often easier to
19691 specify each of them by hand, since you then have full control over what
19692 is the proper order for these directories, which ones should be
19693 included.
19694
19695 However, in larger projects, which might involve hundreds of
19696 subdirectories, it might be more convenient to generate this list
19697 automatically.
19698
19699 The example below presents two methods. The first one, although less
19700 general, gives you more control over the list. It involves wildcard
19701 characters, that are automatically expanded by @command{make}. Its
19702 shortcoming is that you need to explicitly specify some of the
19703 organization of your project, such as for instance the directory tree
19704 depth, whether some directories are found in a separate tree, @enddots{}
19705
19706 The second method is the most general one. It requires an external
19707 program, called @command{find}, which is standard on all Unix systems. All
19708 the directories found under a given root directory will be added to the
19709 list.
19710
19711 @smallexample
19712 @iftex
19713 @leftskip=0cm
19714 @font@heightrm=cmr8
19715 @heightrm
19716 @end iftex
19717 # The examples below are based on the following directory hierarchy:
19718 # All the directories can contain any number of files
19719 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19720 #                       ->  ab
19721 #                       ->  ac
19722 #                ->  b  ->  ba  ->  baa
19723 #                       ->  bb
19724 #                       ->  bc
19725 # This Makefile creates a variable called DIRS, that can be reused any time
19726 # you need this list (see the other examples in this section)
19727
19728 # The root of your project's directory hierarchy
19729 ROOT_DIRECTORY=.
19730
19731 ####
19732 # First method: specify explicitly the list of directories
19733 # This allows you to specify any subset of all the directories you need.
19734 ####
19735
19736 DIRS := a/aa/ a/ab/ b/ba/
19737
19738 ####
19739 # Second method: use wildcards
19740 # Note that the argument(s) to wildcard below should end with a '/'.
19741 # Since wildcards also return file names, we have to filter them out
19742 # to avoid duplicate directory names.
19743 # We thus use make's @code{dir} and @code{sort} functions.
19744 # It sets DIRs to the following value (note that the directories aaa and baa
19745 # are not given, unless you change the arguments to wildcard).
19746 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19747 ####
19748
19749 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19750                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19751
19752 ####
19753 # Third method: use an external program
19754 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19755 # This is the most complete command: it sets DIRs to the following value:
19756 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19757 ####
19758
19759 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19760
19761 @end smallexample
19762
19763 @node Generating the Command Line Switches
19764 @section Generating the Command Line Switches
19765
19766 @noindent
19767 Once you have created the list of directories as explained in the
19768 previous section (@pxref{Automatically Creating a List of Directories}),
19769 you can easily generate the command line arguments to pass to gnatmake.
19770
19771 For the sake of completeness, this example assumes that the source path
19772 is not the same as the object path, and that you have two separate lists
19773 of directories.
19774
19775 @smallexample
19776 # see "Automatically creating a list of directories" to create
19777 # these variables
19778 SOURCE_DIRS=
19779 OBJECT_DIRS=
19780
19781 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19782 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19783
19784 all:
19785         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19786 @end smallexample
19787
19788 @node Overcoming Command Line Length Limits
19789 @section Overcoming Command Line Length Limits
19790
19791 @noindent
19792 One problem that might be encountered on big projects is that many
19793 operating systems limit the length of the command line. It is thus hard to give
19794 gnatmake the list of source and object directories.
19795
19796 This example shows how you can set up environment variables, which will
19797 make @command{gnatmake} behave exactly as if the directories had been
19798 specified on the command line, but have a much higher length limit (or
19799 even none on most systems).
19800
19801 It assumes that you have created a list of directories in your Makefile,
19802 using one of the methods presented in
19803 @ref{Automatically Creating a List of Directories}.
19804 For the sake of completeness, we assume that the object
19805 path (where the ALI files are found) is different from the sources patch.
19806
19807 Note a small trick in the Makefile below: for efficiency reasons, we
19808 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19809 expanded immediately by @code{make}. This way we overcome the standard
19810 make behavior which is to expand the variables only when they are
19811 actually used.
19812
19813 On Windows, if you are using the standard Windows command shell, you must
19814 replace colons with semicolons in the assignments to these variables.
19815
19816 @smallexample
19817 @iftex
19818 @leftskip=0cm
19819 @font@heightrm=cmr8
19820 @heightrm
19821 @end iftex
19822 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19823 # This is the same thing as putting the -I arguments on the command line.
19824 # (the equivalent of using -aI on the command line would be to define
19825 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19826 # You can of course have different values for these variables.
19827 #
19828 # Note also that we need to keep the previous values of these variables, since
19829 # they might have been set before running 'make' to specify where the GNAT
19830 # library is installed.
19831
19832 # see "Automatically creating a list of directories" to create these
19833 # variables
19834 SOURCE_DIRS=
19835 OBJECT_DIRS=
19836
19837 empty:=
19838 space:=$@{empty@} $@{empty@}
19839 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19840 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19841 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19842 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19843 export ADA_INCLUDE_PATH
19844 export ADA_OBJECT_PATH
19845
19846 all:
19847         gnatmake main_unit
19848 @end smallexample
19849 @end ifclear
19850
19851 @node Memory Management Issues
19852 @chapter Memory Management Issues
19853
19854 @noindent
19855 This chapter describes some useful memory pools provided in the GNAT library
19856 and in particular the GNAT Debug Pool facility, which can be used to detect
19857 incorrect uses of access values (including ``dangling references'').
19858 @ifclear vms
19859 It also describes the @command{gnatmem} tool, which can be used to track down
19860 ``memory leaks''.
19861 @end ifclear
19862
19863 @menu
19864 * Some Useful Memory Pools::
19865 * The GNAT Debug Pool Facility::
19866 @ifclear vms
19867 * The gnatmem Tool::
19868 @end ifclear
19869 @end menu
19870
19871 @node Some Useful Memory Pools
19872 @section Some Useful Memory Pools
19873 @findex Memory Pool
19874 @cindex storage, pool
19875
19876 @noindent
19877 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19878 storage pool. Allocations use the standard system call @code{malloc} while
19879 deallocations use the standard system call @code{free}. No reclamation is
19880 performed when the pool goes out of scope. For performance reasons, the
19881 standard default Ada allocators/deallocators do not use any explicit storage
19882 pools but if they did, they could use this storage pool without any change in
19883 behavior. That is why this storage pool is used  when the user
19884 manages to make the default implicit allocator explicit as in this example:
19885 @smallexample @c ada
19886    type T1 is access Something;
19887     -- no Storage pool is defined for T2
19888    type T2 is access Something_Else;
19889    for T2'Storage_Pool use T1'Storage_Pool;
19890    -- the above is equivalent to
19891    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19892 @end smallexample
19893
19894 @noindent
19895 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19896 pool. The allocation strategy is similar to @code{Pool_Local}'s
19897 except that the all
19898 storage allocated with this pool is reclaimed when the pool object goes out of
19899 scope. This pool provides a explicit mechanism similar to the implicit one
19900 provided by several Ada 83 compilers for allocations performed through a local
19901 access type and whose purpose was to reclaim memory when exiting the
19902 scope of a given local access. As an example, the following program does not
19903 leak memory even though it does not perform explicit deallocation:
19904
19905 @smallexample @c ada
19906 with System.Pool_Local;
19907 procedure Pooloc1 is
19908    procedure Internal is
19909       type A is access Integer;
19910       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19911       for A'Storage_Pool use X;
19912       v : A;
19913    begin
19914       for I in  1 .. 50 loop
19915          v := new Integer;
19916       end loop;
19917    end Internal;
19918 begin
19919    for I in  1 .. 100 loop
19920       Internal;
19921    end loop;
19922 end Pooloc1;
19923 @end smallexample
19924
19925 @noindent
19926 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19927 @code{Storage_Size} is specified for an access type.
19928 The whole storage for the pool is
19929 allocated at once, usually on the stack at the point where the access type is
19930 elaborated. It is automatically reclaimed when exiting the scope where the
19931 access type is defined. This package is not intended to be used directly by the
19932 user and it is implicitly used for each such declaration:
19933
19934 @smallexample @c ada
19935    type T1 is access Something;
19936    for T1'Storage_Size use 10_000;
19937 @end smallexample
19938
19939 @node The GNAT Debug Pool Facility
19940 @section The GNAT Debug Pool Facility
19941 @findex Debug Pool
19942 @cindex storage, pool, memory corruption
19943
19944 @noindent
19945 The use of unchecked deallocation and unchecked conversion can easily
19946 lead to incorrect memory references. The problems generated by such
19947 references are usually difficult to tackle because the symptoms can be
19948 very remote from the origin of the problem. In such cases, it is
19949 very helpful to detect the problem as early as possible. This is the
19950 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19951
19952 In order to use the GNAT specific debugging pool, the user must
19953 associate a debug pool object with each of the access types that may be
19954 related to suspected memory problems. See Ada Reference Manual 13.11.
19955 @smallexample @c ada
19956 type Ptr is access Some_Type;
19957 Pool : GNAT.Debug_Pools.Debug_Pool;
19958 for Ptr'Storage_Pool use Pool;
19959 @end smallexample
19960
19961 @noindent
19962 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19963 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19964 allow the user to redefine allocation and deallocation strategies. They
19965 also provide a checkpoint for each dereference, through the use of
19966 the primitive operation @code{Dereference} which is implicitly called at
19967 each dereference of an access value.
19968
19969 Once an access type has been associated with a debug pool, operations on
19970 values of the type may raise four distinct exceptions,
19971 which correspond to four potential kinds of memory corruption:
19972 @itemize @bullet
19973 @item
19974 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19975 @item
19976 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19977 @item
19978 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19979 @item
19980 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19981 @end itemize
19982
19983 @noindent
19984 For types associated with a Debug_Pool, dynamic allocation is performed using
19985 the standard GNAT allocation routine. References to all allocated chunks of
19986 memory are kept in an internal dictionary. Several deallocation strategies are
19987 provided, whereupon the user can choose to release the memory to the system,
19988 keep it allocated for further invalid access checks, or fill it with an easily
19989 recognizable pattern for debug sessions. The memory pattern is the old IBM
19990 hexadecimal convention: @code{16#DEADBEEF#}.
19991
19992 See the documentation in the file g-debpoo.ads for more information on the
19993 various strategies.
19994
19995 Upon each dereference, a check is made that the access value denotes a
19996 properly allocated memory location. Here is a complete example of use of
19997 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19998 @smallexample @c ada
19999 @iftex
20000 @leftskip=0cm
20001 @end iftex
20002 with Gnat.Io; use Gnat.Io;
20003 with Unchecked_Deallocation;
20004 with Unchecked_Conversion;
20005 with GNAT.Debug_Pools;
20006 with System.Storage_Elements;
20007 with Ada.Exceptions; use Ada.Exceptions;
20008 procedure Debug_Pool_Test is
20009
20010    type T is access Integer;
20011    type U is access all T;
20012
20013    P : GNAT.Debug_Pools.Debug_Pool;
20014    for T'Storage_Pool use P;
20015
20016    procedure Free is new Unchecked_Deallocation (Integer, T);
20017    function UC is new Unchecked_Conversion (U, T);
20018    A, B : aliased T;
20019
20020    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20021
20022 begin
20023    Info (P);
20024    A := new Integer;
20025    B := new Integer;
20026    B := A;
20027    Info (P);
20028    Free (A);
20029    begin
20030       Put_Line (Integer'Image(B.all));
20031    exception
20032       when E : others => Put_Line ("raised: " & Exception_Name (E));
20033    end;
20034    begin
20035       Free (B);
20036    exception
20037       when E : others => Put_Line ("raised: " & Exception_Name (E));
20038    end;
20039    B := UC(A'Access);
20040    begin
20041       Put_Line (Integer'Image(B.all));
20042    exception
20043       when E : others => Put_Line ("raised: " & Exception_Name (E));
20044    end;
20045    begin
20046       Free (B);
20047    exception
20048       when E : others => Put_Line ("raised: " & Exception_Name (E));
20049    end;
20050    Info (P);
20051 end Debug_Pool_Test;
20052 @end smallexample
20053
20054 @noindent
20055 The debug pool mechanism provides the following precise diagnostics on the
20056 execution of this erroneous program:
20057 @smallexample
20058 Debug Pool info:
20059   Total allocated bytes :  0
20060   Total deallocated bytes :  0
20061   Current Water Mark:  0
20062   High Water Mark:  0
20063
20064 Debug Pool info:
20065   Total allocated bytes :  8
20066   Total deallocated bytes :  0
20067   Current Water Mark:  8
20068   High Water Mark:  8
20069
20070 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20071 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20072 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20073 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20074 Debug Pool info:
20075   Total allocated bytes :  8
20076   Total deallocated bytes :  4
20077   Current Water Mark:  4
20078   High Water Mark:  8
20079 @end smallexample
20080
20081 @ifclear vms
20082 @node The gnatmem Tool
20083 @section The @command{gnatmem} Tool
20084 @findex gnatmem
20085
20086 @noindent
20087 The @code{gnatmem} utility monitors dynamic allocation and
20088 deallocation activity in a program, and displays information about
20089 incorrect deallocations and possible sources of memory leaks.
20090 It is designed to work in association with a static runtime library
20091 only and in this context provides three types of information:
20092 @itemize @bullet
20093 @item
20094 General information concerning memory management, such as the total
20095 number of allocations and deallocations, the amount of allocated
20096 memory and the high water mark, i.e.@: the largest amount of allocated
20097 memory in the course of program execution.
20098
20099 @item
20100 Backtraces for all incorrect deallocations, that is to say deallocations
20101 which do not correspond to a valid allocation.
20102
20103 @item
20104 Information on each allocation that is potentially the origin of a memory
20105 leak.
20106 @end itemize
20107
20108 @menu
20109 * Running gnatmem::
20110 * Switches for gnatmem::
20111 * Example of gnatmem Usage::
20112 @end menu
20113
20114 @node Running gnatmem
20115 @subsection Running @code{gnatmem}
20116
20117 @noindent
20118 @code{gnatmem} makes use of the output created by the special version of
20119 allocation and deallocation routines that record call information. This
20120 allows to obtain accurate dynamic memory usage history at a minimal cost to
20121 the execution speed. Note however, that @code{gnatmem} is not supported on
20122 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20123 Solaris and Windows NT/2000/XP (x86).
20124
20125 @noindent
20126 The @code{gnatmem} command has the form
20127
20128 @smallexample
20129    $ gnatmem @ovar{switches} user_program
20130 @end smallexample
20131
20132 @noindent
20133 The program must have been linked with the instrumented version of the
20134 allocation and deallocation routines. This is done by linking with the
20135 @file{libgmem.a} library. For correct symbolic backtrace information,
20136 the user program should be compiled with debugging options
20137 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20138
20139 @smallexample
20140 $ gnatmake -g my_program -largs -lgmem
20141 @end smallexample
20142
20143 @noindent
20144 As library @file{libgmem.a} contains an alternate body for package
20145 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20146 when an executable is linked with library @file{libgmem.a}. It is then not
20147 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20148
20149 @noindent
20150 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20151 This file contains information about all allocations and deallocations
20152 performed by the program. It is produced by the instrumented allocations and
20153 deallocations routines and will be used by @code{gnatmem}.
20154
20155 In order to produce symbolic backtrace information for allocations and
20156 deallocations performed by the GNAT run-time library, you need to use a
20157 version of that library that has been compiled with the @option{-g} switch
20158 (see @ref{Rebuilding the GNAT Run-Time Library}).
20159
20160 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20161 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20162 @option{-i} switch, gnatmem will assume that this file can be found in the
20163 current directory. For example, after you have executed @file{my_program},
20164 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20165
20166 @smallexample
20167 $ gnatmem my_program
20168 @end smallexample
20169
20170 @noindent
20171 This will produce the output with the following format:
20172
20173 *************** debut cc
20174 @smallexample
20175 $ gnatmem my_program
20176
20177 Global information
20178 ------------------
20179    Total number of allocations        :  45
20180    Total number of deallocations      :   6
20181    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20182    High Water Mark                    :  11.40 Kilobytes
20183
20184 .
20185 .
20186 .
20187 Allocation Root # 2
20188 -------------------
20189  Number of non freed allocations    :  11
20190  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20191  High Water Mark                    :   1.27 Kilobytes
20192  Backtrace                          :
20193    my_program.adb:23 my_program.alloc
20194 .
20195 .
20196 .
20197 @end smallexample
20198
20199 The first block of output gives general information. In this case, the
20200 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20201 Unchecked_Deallocation routine occurred.
20202
20203 @noindent
20204 Subsequent paragraphs display  information on all allocation roots.
20205 An allocation root is a specific point in the execution of the program
20206 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20207 construct. This root is represented by an execution backtrace (or subprogram
20208 call stack). By default the backtrace depth for allocations roots is 1, so
20209 that a root corresponds exactly to a source location. The backtrace can
20210 be made deeper, to make the root more specific.
20211
20212 @node Switches for gnatmem
20213 @subsection Switches for @code{gnatmem}
20214
20215 @noindent
20216 @code{gnatmem} recognizes the following switches:
20217
20218 @table @option
20219
20220 @item -q
20221 @cindex @option{-q} (@code{gnatmem})
20222 Quiet. Gives the minimum output needed to identify the origin of the
20223 memory leaks. Omits statistical information.
20224
20225 @item @var{N}
20226 @cindex @var{N} (@code{gnatmem})
20227 N is an integer literal (usually between 1 and 10) which controls the
20228 depth of the backtraces defining allocation root. The default value for
20229 N is 1. The deeper the backtrace, the more precise the localization of
20230 the root. Note that the total number of roots can depend on this
20231 parameter. This parameter must be specified @emph{before} the name of the
20232 executable to be analyzed, to avoid ambiguity.
20233
20234 @item -b n
20235 @cindex @option{-b} (@code{gnatmem})
20236 This switch has the same effect as just depth parameter.
20237
20238 @item -i @var{file}
20239 @cindex @option{-i} (@code{gnatmem})
20240 Do the @code{gnatmem} processing starting from @file{file}, rather than
20241 @file{gmem.out} in the current directory.
20242
20243 @item -m n
20244 @cindex @option{-m} (@code{gnatmem})
20245 This switch causes @code{gnatmem} to mask the allocation roots that have less
20246 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20247 examine even the roots that didn't result in leaks.
20248
20249 @item -s order
20250 @cindex @option{-s} (@code{gnatmem})
20251 This switch causes @code{gnatmem} to sort the allocation roots according to the
20252 specified order of sort criteria, each identified by a single letter. The
20253 currently supported criteria are @code{n, h, w} standing respectively for
20254 number of unfreed allocations, high watermark, and final watermark
20255 corresponding to a specific root. The default order is @code{nwh}.
20256
20257 @end table
20258
20259 @node Example of gnatmem Usage
20260 @subsection Example of @code{gnatmem} Usage
20261
20262 @noindent
20263 The following example shows the use of @code{gnatmem}
20264 on a simple memory-leaking program.
20265 Suppose that we have the following Ada program:
20266
20267 @smallexample @c ada
20268 @group
20269 @cartouche
20270 with Unchecked_Deallocation;
20271 procedure Test_Gm is
20272
20273    type T is array (1..1000) of Integer;
20274    type Ptr is access T;
20275    procedure Free is new Unchecked_Deallocation (T, Ptr);
20276    A : Ptr;
20277
20278    procedure My_Alloc is
20279    begin
20280       A := new T;
20281    end My_Alloc;
20282
20283    procedure My_DeAlloc is
20284       B : Ptr := A;
20285    begin
20286       Free (B);
20287    end My_DeAlloc;
20288
20289 begin
20290    My_Alloc;
20291    for I in 1 .. 5 loop
20292       for J in I .. 5 loop
20293          My_Alloc;
20294       end loop;
20295       My_Dealloc;
20296    end loop;
20297 end;
20298 @end cartouche
20299 @end group
20300 @end smallexample
20301
20302 @noindent
20303 The program needs to be compiled with debugging option and linked with
20304 @code{gmem} library:
20305
20306 @smallexample
20307 $ gnatmake -g test_gm -largs -lgmem
20308 @end smallexample
20309
20310 @noindent
20311 Then we execute the program as usual:
20312
20313 @smallexample
20314 $ test_gm
20315 @end smallexample
20316
20317 @noindent
20318 Then @code{gnatmem} is invoked simply with
20319 @smallexample
20320 $ gnatmem test_gm
20321 @end smallexample
20322
20323 @noindent
20324 which produces the following output (result may vary on different platforms):
20325
20326 @smallexample
20327 Global information
20328 ------------------
20329    Total number of allocations        :  18
20330    Total number of deallocations      :   5
20331    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20332    High Water Mark                    :  56.90 Kilobytes
20333
20334 Allocation Root # 1
20335 -------------------
20336  Number of non freed allocations    :  11
20337  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20338  High Water Mark                    :  46.88 Kilobytes
20339  Backtrace                          :
20340    test_gm.adb:11 test_gm.my_alloc
20341
20342 Allocation Root # 2
20343 -------------------
20344  Number of non freed allocations    :   1
20345  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20346  High Water Mark                    :  10.02 Kilobytes
20347  Backtrace                          :
20348    s-secsta.adb:81 system.secondary_stack.ss_init
20349
20350 Allocation Root # 3
20351 -------------------
20352  Number of non freed allocations    :   1
20353  Final Water Mark (non freed mem)   :  12 Bytes
20354  High Water Mark                    :  12 Bytes
20355  Backtrace                          :
20356    s-secsta.adb:181 system.secondary_stack.ss_init
20357 @end smallexample
20358
20359 @noindent
20360 Note that the GNAT run time contains itself a certain number of
20361 allocations that have no  corresponding deallocation,
20362 as shown here for root #2 and root
20363 #3. This is a normal behavior when the number of non-freed allocations
20364 is one, it allocates dynamic data structures that the run time needs for
20365 the complete lifetime of the program. Note also that there is only one
20366 allocation root in the user program with a single line back trace:
20367 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20368 program shows that 'My_Alloc' is called at 2 different points in the
20369 source (line 21 and line 24). If those two allocation roots need to be
20370 distinguished, the backtrace depth parameter can be used:
20371
20372 @smallexample
20373 $ gnatmem 3 test_gm
20374 @end smallexample
20375
20376 @noindent
20377 which will give the following output:
20378
20379 @smallexample
20380 Global information
20381 ------------------
20382    Total number of allocations        :  18
20383    Total number of deallocations      :   5
20384    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20385    High Water Mark                    :  56.90 Kilobytes
20386
20387 Allocation Root # 1
20388 -------------------
20389  Number of non freed allocations    :  10
20390  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20391  High Water Mark                    :  42.97 Kilobytes
20392  Backtrace                          :
20393    test_gm.adb:11 test_gm.my_alloc
20394    test_gm.adb:24 test_gm
20395    b_test_gm.c:52 main
20396
20397 Allocation Root # 2
20398 -------------------
20399  Number of non freed allocations    :   1
20400  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20401  High Water Mark                    :  10.02 Kilobytes
20402  Backtrace                          :
20403    s-secsta.adb:81  system.secondary_stack.ss_init
20404    s-secsta.adb:283 <system__secondary_stack___elabb>
20405    b_test_gm.c:33   adainit
20406
20407 Allocation Root # 3
20408 -------------------
20409  Number of non freed allocations    :   1
20410  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20411  High Water Mark                    :   3.91 Kilobytes
20412  Backtrace                          :
20413    test_gm.adb:11 test_gm.my_alloc
20414    test_gm.adb:21 test_gm
20415    b_test_gm.c:52 main
20416
20417 Allocation Root # 4
20418 -------------------
20419  Number of non freed allocations    :   1
20420  Final Water Mark (non freed mem)   :  12 Bytes
20421  High Water Mark                    :  12 Bytes
20422  Backtrace                          :
20423    s-secsta.adb:181 system.secondary_stack.ss_init
20424    s-secsta.adb:283 <system__secondary_stack___elabb>
20425    b_test_gm.c:33   adainit
20426 @end smallexample
20427
20428 @noindent
20429 The allocation root #1 of the first example has been split in 2 roots #1
20430 and #3 thanks to the more precise associated backtrace.
20431
20432 @end ifclear
20433
20434 @node Stack Related Facilities
20435 @chapter Stack Related Facilities
20436
20437 @noindent
20438 This chapter describes some useful tools associated with stack
20439 checking and analysis. In
20440 particular, it deals with dynamic and static stack usage measurements.
20441
20442 @menu
20443 * Stack Overflow Checking::
20444 * Static Stack Usage Analysis::
20445 * Dynamic Stack Usage Analysis::
20446 @end menu
20447
20448 @node Stack Overflow Checking
20449 @section Stack Overflow Checking
20450 @cindex Stack Overflow Checking
20451 @cindex -fstack-check
20452
20453 @noindent
20454 For most operating systems, @command{gcc} does not perform stack overflow
20455 checking by default. This means that if the main environment task or
20456 some other task exceeds the available stack space, then unpredictable
20457 behavior will occur. Most native systems offer some level of protection by
20458 adding a guard page at the end of each task stack. This mechanism is usually
20459 not enough for dealing properly with stack overflow situations because
20460 a large local variable could ``jump'' above the guard page.
20461 Furthermore, when the
20462 guard page is hit, there may not be any space left on the stack for executing
20463 the exception propagation code. Enabling stack checking avoids
20464 such situations.
20465
20466 To activate stack checking, compile all units with the gcc option
20467 @option{-fstack-check}. For example:
20468
20469 @smallexample
20470 gcc -c -fstack-check package1.adb
20471 @end smallexample
20472
20473 @noindent
20474 Units compiled with this option will generate extra instructions to check
20475 that any use of the stack (for procedure calls or for declaring local
20476 variables in declare blocks) does not exceed the available stack space.
20477 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20478
20479 For declared tasks, the stack size is controlled by the size
20480 given in an applicable @code{Storage_Size} pragma or by the value specified
20481 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20482 the default size as defined in the GNAT runtime otherwise.
20483
20484 For the environment task, the stack size depends on
20485 system defaults and is unknown to the compiler. Stack checking
20486 may still work correctly if a fixed
20487 size stack is allocated, but this cannot be guaranteed.
20488 @ifclear vms
20489 To ensure that a clean exception is signalled for stack
20490 overflow, set the environment variable
20491 @env{GNAT_STACK_LIMIT} to indicate the maximum
20492 stack area that can be used, as in:
20493 @cindex GNAT_STACK_LIMIT
20494
20495 @smallexample
20496 SET GNAT_STACK_LIMIT 1600
20497 @end smallexample
20498
20499 @noindent
20500 The limit is given in kilobytes, so the above declaration would
20501 set the stack limit of the environment task to 1.6 megabytes.
20502 Note that the only purpose of this usage is to limit the amount
20503 of stack used by the environment task. If it is necessary to
20504 increase the amount of stack for the environment task, then this
20505 is an operating systems issue, and must be addressed with the
20506 appropriate operating systems commands.
20507 @end ifclear
20508 @ifset vms
20509 To have a fixed size stack in the environment task, the stack must be put
20510 in the P0 address space and its size specified.  Use these switches to
20511 create a p0 image:
20512
20513 @smallexample
20514 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20515 @end smallexample
20516
20517 @noindent
20518 The quotes are required to keep case.  The number after @samp{STACK=} is the
20519 size of the environmental task stack in pagelets (512 bytes).  In this example
20520 the stack size is about 2 megabytes.
20521
20522 @noindent
20523 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20524 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20525 more details about the @option{/p0image} qualifier and the @option{stack}
20526 option.
20527 @end ifset
20528
20529 @node Static Stack Usage Analysis
20530 @section Static Stack Usage Analysis
20531 @cindex Static Stack Usage Analysis
20532 @cindex -fstack-usage
20533
20534 @noindent
20535 A unit compiled with @option{-fstack-usage} will generate an extra file
20536 that specifies
20537 the maximum amount of stack used, on a per-function basis.
20538 The file has the same
20539 basename as the target object file with a @file{.su} extension.
20540 Each line of this file is made up of three fields:
20541
20542 @itemize
20543 @item
20544 The name of the function.
20545 @item
20546 A number of bytes.
20547 @item
20548 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20549 @end itemize
20550
20551 The second field corresponds to the size of the known part of the function
20552 frame.
20553
20554 The qualifier @code{static} means that the function frame size
20555 is purely static.
20556 It usually means that all local variables have a static size.
20557 In this case, the second field is a reliable measure of the function stack
20558 utilization.
20559
20560 The qualifier @code{dynamic} means that the function frame size is not static.
20561 It happens mainly when some local variables have a dynamic size. When this
20562 qualifier appears alone, the second field is not a reliable measure
20563 of the function stack analysis. When it is qualified with  @code{bounded}, it
20564 means that the second field is a reliable maximum of the function stack
20565 utilization.
20566
20567 @node Dynamic Stack Usage Analysis
20568 @section Dynamic Stack Usage Analysis
20569
20570 @noindent
20571 It is possible to measure the maximum amount of stack used by a task, by
20572 adding a switch to @command{gnatbind}, as:
20573
20574 @smallexample
20575 $ gnatbind -u0 file
20576 @end smallexample
20577
20578 @noindent
20579 With this option, at each task termination, its stack usage is  output on
20580 @file{stderr}.
20581 It is not always convenient to output the stack usage when the program
20582 is still running. Hence, it is possible to delay this output until program
20583 termination. for a given number of tasks specified as the argument of the
20584 @option{-u} option. For instance:
20585
20586 @smallexample
20587 $ gnatbind -u100 file
20588 @end smallexample
20589
20590 @noindent
20591 will buffer the stack usage information of the first 100 tasks to terminate and
20592 output this info at program termination. Results are displayed in four
20593 columns:
20594
20595 @noindent
20596 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20597
20598 @noindent
20599 where:
20600
20601 @table @emph
20602 @item Index
20603 is a number associated with each task.
20604
20605 @item Task Name
20606 is the name of the task analyzed.
20607
20608 @item Stack Size
20609 is the maximum size for the stack.
20610
20611 @item Stack Usage
20612 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20613 is not entirely analyzed, and it's not possible to know exactly how
20614 much has actually been used. The report thus contains the theoretical stack usage
20615 (Value) and the possible variation (Variation) around this value.
20616
20617 @end table
20618
20619 @noindent
20620 The environment task stack, e.g., the stack that contains the main unit, is
20621 only processed when the environment variable GNAT_STACK_LIMIT is set.
20622
20623
20624 @c *********************************
20625 @c *            GNATCHECK          *
20626 @c *********************************
20627 @node Verifying Properties Using gnatcheck
20628 @chapter Verifying Properties Using @command{gnatcheck}
20629 @findex gnatcheck
20630 @cindex @command{gnatcheck}
20631
20632 @noindent
20633 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20634 of Ada source files according to a given set of semantic rules.
20635 @cindex ASIS
20636
20637 In order to check compliance with a given rule, @command{gnatcheck} has to
20638 semantically analyze the Ada sources.
20639 Therefore, checks can only be performed on
20640 legal Ada units. Moreover, when a unit depends semantically upon units located
20641 outside the current directory, the source search path has to be provided when
20642 calling @command{gnatcheck}, either through a specified project file or
20643 through @command{gnatcheck} switches as described below.
20644
20645 A number of rules are predefined in @command{gnatcheck} and are described
20646 later in this chapter.
20647 You can also add new rules, by modifying the @command{gnatcheck} code and
20648 rebuilding the tool. In order to add a simple rule making some local checks,
20649 a small amount of straightforward ASIS-based programming is usually needed.
20650
20651 Project support for @command{gnatcheck} is provided by the GNAT
20652 driver (see @ref{The GNAT Driver and Project Files}).
20653
20654 Invoking @command{gnatcheck} on the command line has the form:
20655
20656 @smallexample
20657 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20658       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20659       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20660 @end smallexample
20661
20662 @noindent
20663 where
20664 @itemize @bullet
20665 @item
20666 @var{switches} specify the general tool options
20667
20668 @item
20669 Each @var{filename} is the name (including the extension) of a source
20670 file to process. ``Wildcards'' are allowed, and
20671 the file name may contain path information.
20672
20673 @item
20674 Each @var{arg_list_filename} is the name (including the extension) of a text
20675 file containing the names of the source files to process, separated by spaces
20676 or line breaks.
20677
20678 @item
20679 @var{gcc_switches} is a list of switches for
20680 @command{gcc}. They will be passed on to all compiler invocations made by
20681 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20682 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20683 and use the @option{-gnatec} switch to set the configuration file.
20684
20685 @item
20686 @var{rule_options} is a list of options for controlling a set of
20687 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20688 @end itemize
20689
20690 @noindent
20691 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20692
20693 @menu
20694 * Format of the Report File::
20695 * General gnatcheck Switches::
20696 * gnatcheck Rule Options::
20697 * Adding the Results of Compiler Checks to gnatcheck Output::
20698 * Project-Wide Checks::
20699 * Predefined Rules::
20700 @end menu
20701
20702 @node Format of the Report File
20703 @section Format of the Report File
20704 @cindex Report file (for @code{gnatcheck})
20705
20706 @noindent
20707 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20708 rule violations.
20709 It also creates a text file  that
20710 contains the complete report of the last gnatcheck run. By default this file is
20711 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20712 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20713 location of the report file. This report contains:
20714 @itemize @bullet
20715 @item a list of the Ada source files being checked,
20716 @item a list of enabled and disabled rules,
20717 @item a list of the diagnostic messages, ordered in three different ways
20718 and collected in three separate
20719 sections. Section 1 contains the raw list of diagnostic messages. It
20720 corresponds to the output going to @file{stdout}. Section 2 contains
20721 messages ordered by rules.
20722 Section 3 contains messages ordered by source files.
20723 @end itemize
20724
20725 @node General gnatcheck Switches
20726 @section General @command{gnatcheck} Switches
20727
20728 @noindent
20729 The following switches control the general @command{gnatcheck} behavior
20730
20731 @table @option
20732 @c !sort!
20733 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20734 @item ^-a^/ALL^
20735 Process all units including those with read-only ALI files such as
20736 those from GNAT Run-Time library.
20737
20738 @ifclear vms
20739 @ignore
20740 @cindex @option{-d} (@command{gnatcheck})
20741 @item -d
20742 Debug mode
20743 @end ignore
20744
20745 @cindex @option{-dd} (@command{gnatcheck})
20746 @item -dd
20747 Progress indicator mode (for use in GPS)
20748 @end ifclear
20749
20750 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20751 @item ^-h^/HELP^
20752 List the predefined and user-defined rules. For more details see
20753 @ref{Predefined Rules}.
20754
20755 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20756 @item ^-l^/LOCS^
20757 Use full source locations references in the report file. For a construct from
20758 a generic instantiation a full source location is a chain from the location
20759 of this construct in the generic unit to the place where this unit is
20760 instantiated.
20761
20762 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20763 @item ^-log^/LOG^
20764 Duplicate all the output sent to Stderr into a log file. The log file is
20765 named @var{gnatcheck.log} and is located in the current directory.
20766
20767 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20768 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20769 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20770 the default value is 500. Zero means that there is no limitation on
20771 the number of diagnostic messages to be printed into Stdout.
20772
20773 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20774 @item ^-q^/QUIET^
20775 Quiet mode. All the diagnoses about rule violations are placed in the
20776 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20777
20778 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20779 @item ^-s^/SHORT^
20780 Short format of the report file (no version information, no list of applied
20781 rules, no list of checked sources is included)
20782
20783 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20784 @item ^-s1^/COMPILER_STYLE^
20785 Include the compiler-style section in the report file
20786
20787 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20788 @item ^-s2^/BY_RULES^
20789 Include the section containing diagnoses ordered by rules in the report file
20790
20791 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20792 @item ^-s3^/BY_FILES_BY_RULES^
20793 Include the section containing diagnoses ordered by files and then by rules
20794 in the report file
20795
20796 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20797 @item ^-t^/TIME^
20798 Print out execution time.
20799
20800 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20801 @item ^-v^/VERBOSE^
20802 Verbose mode; @command{gnatcheck} generates version information and then
20803 a trace of sources being processed.
20804
20805 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20806 @item ^-o ^/OUTPUT=^@var{report_file}
20807 Set name of report file file to @var{report_file} .
20808
20809 @end table
20810
20811 @noindent
20812 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20813 @option{^-s2^/BY_RULES^} or
20814 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20815 then the  @command{gnatcheck} report file will only contain sections
20816 explicitly denoted by these options.
20817
20818 @node gnatcheck Rule Options
20819 @section @command{gnatcheck} Rule Options
20820
20821 @noindent
20822 The following options control the processing performed by
20823 @command{gnatcheck}.
20824
20825 @table @option
20826 @cindex @option{+ALL} (@command{gnatcheck})
20827 @item +ALL
20828 Turn all the rule checks ON.
20829
20830 @cindex @option{-ALL} (@command{gnatcheck})
20831 @item -ALL
20832 Turn all the rule checks OFF.
20833
20834 @cindex @option{+R} (@command{gnatcheck})
20835 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20836 Turn on the check for a specified rule with the specified parameter, if any.
20837 @var{rule_id} must be the identifier of one of the currently implemented rules
20838 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20839 are not case-sensitive. The @var{param} item must
20840 be a string representing a valid parameter(s) for the specified rule.
20841 If it contains any space characters then this string must be enclosed in
20842 quotation marks.
20843
20844 @cindex @option{-R} (@command{gnatcheck})
20845 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20846 Turn off the check for a specified rule with the specified parameter, if any.
20847
20848 @cindex @option{-from} (@command{gnatcheck})
20849 @item -from=@var{rule_option_filename}
20850 Read the rule options from the text file @var{rule_option_filename}, referred as
20851 ``rule file'' below.
20852
20853 @end table
20854
20855 @noindent
20856 The default behavior is that all the rule checks are disabled.
20857
20858 A rule file is a text file containing a set of rule options.
20859 @cindex Rule file (for @code{gnatcheck})
20860 The file may contain empty lines and Ada-style comments (comment
20861 lines and end-of-line comments). The rule file has free format; that is,
20862 you do not have to start a new rule option on a new line.
20863
20864 A rule file may contain other @option{-from=@var{rule_option_filename}}
20865 options, each such option being replaced with the content of the
20866 corresponding rule file during the rule files processing. In case a
20867 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20868 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20869 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20870 the processing of rule files is interrupted and a part of their content
20871 is ignored.
20872
20873
20874 @node Adding the Results of Compiler Checks to gnatcheck Output
20875 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20876
20877 @noindent
20878 The @command{gnatcheck} tool can include in the generated diagnostic messages
20879 and in
20880 the report file the results of the checks performed by the compiler. Though
20881 disabled by default, this effect may be obtained by using @option{+R} with
20882 the following rule identifiers and parameters:
20883
20884 @table @option
20885 @item Restrictions
20886 To record restrictions violations (that are performed by the compiler if the
20887 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20888 use the rule named
20889 @code{Restrictions} with the same parameters as pragma
20890 @code{Restrictions} or @code{Restriction_Warnings}.
20891
20892 @item Style_Checks
20893 To record compiler style checks(@pxref{Style Checking}), use the rule named
20894 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20895 which enables all the standard style checks that corresponds to @option{-gnatyy}
20896 GNAT style check option, or a string that has exactly the same
20897 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20898 @code{Style_Checks} (for further information about this pragma,
20899 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}). For example,
20900 @code{+RStyle_Checks:O} rule option activates and adds to @command{gnatcheck}
20901 output the compiler style check that corresponds to
20902 @code{-gnatyO} style check option.
20903
20904 @item Warnings
20905 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20906 named @code{Warnings} with a parameter that is a valid
20907 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20908 (for further information about this pragma, @pxref{Pragma Warnings,,,
20909 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20910 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20911 all the specific warnings, but not suppresses the warning mode,
20912 and 'e' parameter, corresponding to @option{-gnatwe} that means
20913 "treat warnings as errors", does not have any effect.
20914
20915 @end table
20916
20917 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20918 option with the corresponding restriction name as a parameter. @code{-R} is
20919 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20920 warnings and style checks, use the corresponding warning and style options.
20921
20922 @node Project-Wide Checks
20923 @section Project-Wide Checks
20924 @cindex Project-wide checks (for @command{gnatcheck})
20925
20926 @noindent
20927 In order to perform checks on all units of a given project, you can use
20928 the GNAT driver along with the @option{-P} option:
20929 @smallexample
20930    gnat check -Pproj -rules -from=my_rules
20931 @end smallexample
20932
20933 @noindent
20934 If the project @code{proj} depends upon other projects, you can perform
20935 checks on the project closure using the @option{-U} option:
20936 @smallexample
20937    gnat check -Pproj -U -rules -from=my_rules
20938 @end smallexample
20939
20940 @noindent
20941 Finally, if not all the units are relevant to a particular main
20942 program in the project closure, you can perform checks for the set
20943 of units needed to create a given main program (unit closure) using
20944 the @option{-U} option followed by the name of the main unit:
20945 @smallexample
20946    gnat check -Pproj -U main -rules -from=my_rules
20947 @end smallexample
20948
20949
20950 @node Predefined Rules
20951 @section Predefined Rules
20952 @cindex Predefined rules (for @command{gnatcheck})
20953
20954 @ignore
20955 @c (Jan 2007) Since the global rules are still under development and are not
20956 @c documented, there is no point in explaining the difference between
20957 @c global and local rules
20958 @noindent
20959 A rule in @command{gnatcheck} is either local or global.
20960 A @emph{local rule} is a rule that applies to a well-defined section
20961 of a program and that can be checked by analyzing only this section.
20962 A @emph{global rule} requires analysis of some global properties of the
20963 whole program (mostly related to the program call graph).
20964 As of @value{NOW}, the implementation of global rules should be
20965 considered to be at a preliminary stage. You can use the
20966 @option{+GLOBAL} option to enable all the global rules, and the
20967 @option{-GLOBAL} rule option to disable all the global rules.
20968
20969 All the global rules in the list below are
20970 so indicated by marking them ``GLOBAL''.
20971 This +GLOBAL and -GLOBAL options are not
20972 included in the list of gnatcheck options above, because at the moment they
20973 are considered as a temporary debug options.
20974
20975 @command{gnatcheck} performs rule checks for generic
20976 instances only for global rules.  This limitation may be relaxed in a later
20977 release.
20978 @end ignore
20979
20980 @noindent
20981 The following subsections document the rules implemented in
20982 @command{gnatcheck}.
20983 The subsection title is the same as the rule identifier, which may be
20984 used as a parameter of the @option{+R} or @option{-R} options.
20985
20986
20987 @menu
20988 * Abstract_Type_Declarations::
20989 * Anonymous_Arrays::
20990 * Anonymous_Subtypes::
20991 * Blocks::
20992 * Boolean_Relational_Operators::
20993 @ignore
20994 * Ceiling_Violations::
20995 @end ignore
20996 * Complex_Inlined_Subprograms::
20997 * Controlled_Type_Declarations::
20998 * Declarations_In_Blocks::
20999 * Deep_Inheritance_Hierarchies::
21000 * Deeply_Nested_Generics::
21001 * Deeply_Nested_Inlining::
21002 @ignore
21003 * Deeply_Nested_Local_Inlining::
21004 @end ignore
21005 * Default_Parameters::
21006 * Direct_Calls_To_Primitives::
21007 * Discriminated_Records::
21008 * Enumeration_Ranges_In_CASE_Statements::
21009 * Exceptions_As_Control_Flow::
21010 * Exits_From_Conditional_Loops::
21011 * EXIT_Statements_With_No_Loop_Name::
21012 * Expanded_Loop_Exit_Names::
21013 * Explicit_Full_Discrete_Ranges::
21014 * Float_Equality_Checks::
21015 * Forbidden_Attributes::
21016 * Forbidden_Pragmas::
21017 * Function_Style_Procedures::
21018 * Generics_In_Subprograms::
21019 * GOTO_Statements::
21020 * Implicit_IN_Mode_Parameters::
21021 * Implicit_SMALL_For_Fixed_Point_Types::
21022 * Improperly_Located_Instantiations::
21023 * Improper_Returns::
21024 * Library_Level_Subprograms::
21025 * Local_Packages::
21026 @ignore
21027 * Improperly_Called_Protected_Entries::
21028 @end ignore
21029 * Metrics::
21030 * Misnamed_Controlling_Parameters::
21031 * Misnamed_Identifiers::
21032 * Multiple_Entries_In_Protected_Definitions::
21033 * Name_Clashes::
21034 * Non_Qualified_Aggregates::
21035 * Non_Short_Circuit_Operators::
21036 * Non_SPARK_Attributes::
21037 * Non_Tagged_Derived_Types::
21038 * Non_Visible_Exceptions::
21039 * Numeric_Literals::
21040 * OTHERS_In_Aggregates::
21041 * OTHERS_In_CASE_Statements::
21042 * OTHERS_In_Exception_Handlers::
21043 * Outer_Loop_Exits::
21044 * Overloaded_Operators::
21045 * Overly_Nested_Control_Structures::
21046 * Parameters_Out_Of_Order::
21047 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21048 * Positional_Actuals_For_Defaulted_Parameters::
21049 * Positional_Components::
21050 * Positional_Generic_Parameters::
21051 * Positional_Parameters::
21052 * Predefined_Numeric_Types::
21053 * Raising_External_Exceptions::
21054 * Raising_Predefined_Exceptions::
21055 * Separate_Numeric_Error_Handlers::
21056 @ignore
21057 * Recursion::
21058 * Side_Effect_Functions::
21059 @end ignore
21060 * Slices::
21061 * Too_Many_Parents::
21062 * Unassigned_OUT_Parameters::
21063 * Uncommented_BEGIN_In_Package_Bodies::
21064 * Unconditional_Exits::
21065 * Unconstrained_Array_Returns::
21066 * Universal_Ranges::
21067 * Unnamed_Blocks_And_Loops::
21068 @ignore
21069 * Unused_Subprograms::
21070 @end ignore
21071 * USE_PACKAGE_Clauses::
21072 * Visible_Components::
21073 * Volatile_Objects_Without_Address_Clauses::
21074 @end menu
21075
21076
21077 @node Abstract_Type_Declarations
21078 @subsection @code{Abstract_Type_Declarations}
21079 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21080
21081 @noindent
21082 Flag all declarations of abstract types. For an abstract private
21083 type, both the private and full type declarations are flagged.
21084
21085 This rule has no parameters.
21086
21087
21088 @node Anonymous_Arrays
21089 @subsection @code{Anonymous_Arrays}
21090 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21091
21092 @noindent
21093 Flag all anonymous array type definitions (by Ada semantics these can only
21094 occur in object declarations).
21095
21096 This rule has no parameters.
21097
21098 @node Anonymous_Subtypes
21099 @subsection @code{Anonymous_Subtypes}
21100 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21101
21102 @noindent
21103 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
21104 any instance of a subtype indication with a constraint, other than one
21105 that occurs immediately within a subtype declaration. Any use of a range
21106 other than as a constraint used immediately within a subtype declaration
21107 is considered as an anonymous subtype.
21108
21109 An effect of this rule is that @code{for} loops such as the following are
21110 flagged (since @code{1..N} is formally a ``range''):
21111
21112 @smallexample @c ada
21113 for I in 1 .. N loop
21114    @dots{}
21115 end loop;
21116 @end smallexample
21117
21118 @noindent
21119 Declaring an explicit subtype solves the problem:
21120
21121 @smallexample @c ada
21122 subtype S is Integer range 1..N;
21123 @dots{}
21124 for I in S loop
21125    @dots{}
21126 end loop;
21127 @end smallexample
21128
21129 @noindent
21130 This rule has no parameters.
21131
21132 @node Blocks
21133 @subsection @code{Blocks}
21134 @cindex @code{Blocks} rule (for @command{gnatcheck})
21135
21136 @noindent
21137 Flag each block statement.
21138
21139 This rule has no parameters.
21140
21141 @node Boolean_Relational_Operators
21142 @subsection @code{Boolean_Relational_Operators}
21143 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21144
21145 @noindent
21146 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21147 ``>='', ``='' and ``/='') for the predefined Boolean type.
21148 (This rule is useful in enforcing the SPARK language restrictions.)
21149
21150 Calls to predefined relational operators of any type derived from
21151 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21152 with these designators, and uses of operators that are renamings
21153 of the predefined relational operators for @code{Standard.Boolean},
21154 are likewise not detected.
21155
21156 This rule has no parameters.
21157
21158 @ignore
21159 @node Ceiling_Violations
21160 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21161 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21162
21163 @noindent
21164 Flag invocations of a protected operation by a task whose priority exceeds
21165 the protected object's ceiling.
21166
21167 As of @value{NOW}, this rule has the following limitations:
21168
21169 @itemize @bullet
21170
21171 @item
21172  We consider only pragmas Priority and Interrupt_Priority as means to define
21173   a task/protected operation priority. We do not consider the effect of using
21174   Ada.Dynamic_Priorities.Set_Priority procedure;
21175
21176 @item
21177  We consider only base task priorities, and no priority inheritance. That is,
21178   we do not make a difference between calls issued during task activation and
21179   execution of the sequence of statements from task body;
21180
21181 @item
21182  Any situation when the priority of protected operation caller is set by a
21183   dynamic expression (that is, the corresponding Priority or
21184   Interrupt_Priority pragma has a non-static expression as an argument) we
21185   treat as a priority inconsistency (and, therefore, detect this situation).
21186 @end itemize
21187
21188 @noindent
21189 At the moment the notion of the main subprogram is not implemented in
21190 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21191 if this subprogram can be a main subprogram of a partition) changes the
21192 priority of an environment task. So if we have more then one such pragma in
21193 the set of processed sources, the pragma that is processed last, defines the
21194 priority of an environment task.
21195
21196 This rule has no parameters.
21197 @end ignore
21198
21199 @node Controlled_Type_Declarations
21200 @subsection @code{Controlled_Type_Declarations}
21201 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21202
21203 @noindent
21204 Flag all declarations of controlled types. A declaration of a private type
21205 is flagged if its full declaration declares a controlled type. A declaration
21206 of a derived type is flagged if its ancestor type is controlled. Subtype
21207 declarations are not checked. A declaration of a type that itself is not a
21208 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21209 component is not checked.
21210
21211 This rule has no parameters.
21212
21213
21214 @node Complex_Inlined_Subprograms
21215 @subsection @code{Complex_Inlined_Subprograms}
21216 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21217
21218 @noindent
21219 Flags a subprogram (or generic subprogram) if
21220 pragma Inline is applied to the subprogram and at least one of the following
21221 conditions is met:
21222
21223 @itemize @bullet
21224 @item
21225 it contains at least one complex declaration such as a subprogram body,
21226 package, task, protected object declaration, or a generic instantiation
21227 (except instantiation of @code{Ada.Unchecked_Conversion});
21228
21229 @item
21230 it contains at least one complex statement such as a loop, a case
21231 or a if statement, or a short circuit control form;
21232
21233 @item
21234 the number of statements exceeds
21235 a value specified by the @option{N} rule parameter;
21236 @end itemize
21237
21238 @noindent
21239 This rule has the following (mandatory) parameter for the @option{+R} option:
21240
21241 @table @emph
21242 @item N
21243 Positive integer specifying the maximum allowed total number of statements
21244 in the subprogram body.
21245 @end table
21246
21247
21248 @node Declarations_In_Blocks
21249 @subsection @code{Declarations_In_Blocks}
21250 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21251
21252 @noindent
21253 Flag all block statements containing local declarations. A @code{declare}
21254 block with an empty @i{declarative_part} or with a @i{declarative part}
21255 containing only pragmas and/or @code{use} clauses is not flagged.
21256
21257 This rule has no parameters.
21258
21259
21260 @node Deep_Inheritance_Hierarchies
21261 @subsection @code{Deep_Inheritance_Hierarchies}
21262 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21263
21264 @noindent
21265 Flags a tagged derived type declaration or an interface type declaration if
21266 its depth (in its inheritance
21267 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21268
21269 The inheritance depth of a tagged type or interface type is defined as 0 for
21270 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21271 depths of the immediate parent and immediate progenitors.
21272
21273 This rule does not flag private extension
21274 declarations. In the case of a private extension, the correspondong full
21275 declaration is checked.
21276
21277 This rule has the following (mandatory) parameter for the @option{+R} option:
21278
21279 @table @emph
21280 @item N
21281 Integer not less then -1 specifying the maximal allowed depth of any inheritance
21282 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21283 of tagged and interface types.
21284 @end table
21285
21286
21287 @node Deeply_Nested_Generics
21288 @subsection @code{Deeply_Nested_Generics}
21289 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21290
21291 @noindent
21292 Flags a generic declaration nested in another generic declaration if
21293 the nesting level of the inner generic exceeds
21294 a value specified by the @option{N} rule parameter.
21295 The nesting level is the number of generic declaratons that enclose the given
21296 (generic) declaration. Formal packages are not flagged by this rule.
21297
21298 This rule has the following (mandatory) parameters for the @option{+R} option:
21299
21300 @table @emph
21301 @item N
21302 Positive integer specifying the maximal allowed nesting level
21303 for a generic declaration.
21304 @end table
21305
21306 @node Deeply_Nested_Inlining
21307 @subsection @code{Deeply_Nested_Inlining}
21308 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21309
21310 @noindent
21311 Flags a subprogram (or generic subprogram) if
21312 pragma Inline has been applied to the subprogram but the subprogram
21313 calls to another inlined subprogram that results in nested inlining
21314 with nesting depth exceeding the value specified by the
21315 @option{N} rule parameter.
21316
21317 This rule requires the global analysis of all the compilation units that
21318 are @command{gnatcheck} arguments; such analysis may affect the tool's
21319 performance.
21320
21321 This rule has the following (mandatory) parameter for the @option{+R} option:
21322
21323 @table @emph
21324 @item N
21325 Positive integer specifying the maximal allowed level of nested inlining.
21326 @end table
21327
21328
21329 @ignore
21330 @node Deeply_Nested_Local_Inlining
21331 @subsection @code{Deeply_Nested_Local_Inlining}
21332 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21333
21334 @noindent
21335 Flags a subprogram body if a pragma @code{Inline} is applied to the
21336 corresponding subprogram (or generic subprogram) and the body contains a call
21337 to another inlined subprogram that results in nested inlining with nesting
21338 depth more then a value specified by the @option{N} rule parameter.
21339 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21340 assumes that calls to subprograms in
21341 with'ed units are not inlided, so all the analysis of the depth of inlining is
21342 limited by the compilation unit where the subprogram body is located and the
21343 units it depends semantically upon. Such analysis may be usefull for the case
21344 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21345 the executable.
21346
21347 This rule has the following (mandatory) parameters for the @option{+R} option:
21348
21349 @table @emph
21350 @item N
21351 Positive integer specifying the maximal allowed level of nested inlining.
21352 @end table
21353
21354 @end ignore
21355
21356 @node Default_Parameters
21357 @subsection @code{Default_Parameters}
21358 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21359
21360 @noindent
21361 Flag all default expressions for subprogram parameters. Parameter
21362 declarations of formal and generic subprograms are also checked.
21363
21364 This rule has no parameters.
21365
21366
21367 @node Direct_Calls_To_Primitives
21368 @subsection @code{Direct_Calls_To_Primitives}
21369 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21370
21371 @noindent
21372 Flags any non-dispatching call to a dispatching primitive operation, except
21373 for the common idiom where a primitive subprogram for a tagged type
21374 directly calls the same primitive subprogram of the type's immediate ancestor.
21375
21376 This rule has no parameters.
21377
21378
21379 @node Discriminated_Records
21380 @subsection @code{Discriminated_Records}
21381 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21382
21383 @noindent
21384 Flag all declarations of record types with discriminants. Only the
21385 declarations of record and record extension types are checked. Incomplete,
21386 formal, private, derived and private extension type declarations are not
21387 checked. Task and protected type declarations also are not checked.
21388
21389 This rule has no parameters.
21390
21391
21392 @node Enumeration_Ranges_In_CASE_Statements
21393 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21394 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21395
21396 @noindent
21397 Flag each use of a range of enumeration literals as a choice in a
21398 @code{case} statement.
21399 All forms for specifying a range (explicit ranges
21400 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21401 An enumeration range is
21402 flagged even if contains exactly one enumeration value or no values at all. A
21403 type derived from an enumeration type is considered as an enumeration type.
21404
21405 This rule helps prevent maintenance problems arising from adding an
21406 enumeration value to a type and having it implicitly handled by an existing
21407 @code{case} statement with an enumeration range that includes the new literal.
21408
21409 This rule has no parameters.
21410
21411
21412 @node Exceptions_As_Control_Flow
21413 @subsection @code{Exceptions_As_Control_Flow}
21414 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21415
21416 @noindent
21417 Flag each place where an exception is explicitly raised and handled in the
21418 same subprogram body. A @code{raise} statement in an exception handler,
21419 package body, task body or entry body is not flagged.
21420
21421 The rule has no parameters.
21422
21423 @node Exits_From_Conditional_Loops
21424 @subsection @code{Exits_From_Conditional_Loops}
21425 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21426
21427 @noindent
21428 Flag any exit statement if it transfers the control out of a @code{for} loop
21429 or a @code{while} loop. This includes cases when the @code{exit} statement
21430 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21431 in some @code{for} or @code{while} loop, but transfers the control from some
21432 outer (inconditional) @code{loop} statement.
21433
21434 The rule has no parameters.
21435
21436
21437 @node EXIT_Statements_With_No_Loop_Name
21438 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21439 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21440
21441 @noindent
21442 Flag each @code{exit} statement that does not specify the name of the loop
21443 being exited.
21444
21445 The rule has no parameters.
21446
21447
21448 @node Expanded_Loop_Exit_Names
21449 @subsection @code{Expanded_Loop_Exit_Names}
21450 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21451
21452 @noindent
21453 Flag all expanded loop names in @code{exit} statements.
21454
21455 This rule has no parameters.
21456
21457 @node Explicit_Full_Discrete_Ranges
21458 @subsection @code{Explicit_Full_Discrete_Ranges}
21459 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21460
21461 @noindent
21462 Flag each discrete range that has the form @code{A'First .. A'Last}.
21463
21464 This rule has no parameters.
21465
21466 @node Float_Equality_Checks
21467 @subsection @code{Float_Equality_Checks}
21468 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21469
21470 @noindent
21471 Flag all calls to the predefined equality operations for floating-point types.
21472 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21473 User-defined equality operations are not flagged, nor are ``@code{=}''
21474 and ``@code{/=}'' operations for fixed-point types.
21475
21476 This rule has no parameters.
21477
21478
21479 @node Forbidden_Attributes
21480 @subsection @code{Forbidden_Attributes}
21481 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21482
21483 @noindent
21484 Flag each use of the specified attributes. The attributes to be detected are
21485 named in the rule's parameters.
21486
21487 This rule has the following parameters:
21488
21489 @itemize @bullet
21490 @item For the @option{+R} option
21491
21492 @table @asis
21493 @item @emph{Attribute_Designator}
21494 Adds the specified attribute to the set of attributes to be detected and sets
21495 the detection checks for all the specified attributes ON.
21496 If @emph{Attribute_Designator}
21497 does not denote any attribute defined in the Ada standard
21498 or in
21499 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21500 Manual}, it is treated as the name of unknown attribute.
21501
21502 @item @code{GNAT}
21503 All the GNAT-specific attributes are detected; this sets
21504 the detection checks for all the specified attributes ON.
21505
21506 @item @code{ALL}
21507 All attributes are detected; this sets the rule ON.
21508 @end table
21509
21510 @item For the @option{-R} option
21511 @table @asis
21512 @item @emph{Attribute_Designator}
21513 Removes the specified attribute from the set of attributes to be
21514 detected without affecting detection checks for
21515 other attributes. If @emph{Attribute_Designator} does not correspond to any
21516 attribute defined in the Ada standard or in
21517 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21518 this option is treated as turning OFF detection of all unknown attributes.
21519
21520 @item GNAT
21521 Turn OFF detection of all GNAT-specific attributes
21522
21523 @item ALL
21524 Clear the list of the attributes to be detected and
21525 turn the rule OFF.
21526 @end table
21527 @end itemize
21528
21529 @noindent
21530 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21531 have the syntax of an Ada identifier and therefore can not be considered as a
21532 (part of an) attribute designator, a diagnostic message is generated and the
21533 corresponding parameter is ignored. (If an attribute allows a static
21534 expression to be a part of the attribute designator, this expression is
21535 ignored by this rule.)
21536
21537 When more then one parameter is given in the same rule option, the parameters
21538 must be separated by commas.
21539
21540 If more then one option for this rule is specified for the gnatcheck call, a
21541 new option overrides the previous one(s).
21542
21543 The @option{+R} option with no parameters turns the rule ON, with the set of
21544 attributes to be detected defined by the previous rule options.
21545 (By default this set is empty, so if the only option specified for the rule is
21546 @option{+RForbidden_Attributes} (with
21547 no parameter), then the rule is enabled, but it does not detect anything).
21548 The @option{-R} option with no parameter turns the rule OFF, but it does not
21549 affect the set of attributes to be detected.
21550
21551
21552 @node Forbidden_Pragmas
21553 @subsection @code{Forbidden_Pragmas}
21554 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21555
21556 @noindent
21557 Flag each use of the specified pragmas.  The pragmas to be detected
21558 are named in the rule's  parameters.
21559
21560 This rule has the following parameters:
21561
21562 @itemize @bullet
21563 @item For the @option{+R} option
21564
21565 @table @asis
21566 @item @emph{Pragma_Name}
21567 Adds the specified pragma to the set of pragmas to be
21568 checked and sets the checks for all the specified pragmas
21569 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21570 does not correspond to any pragma name defined in the Ada
21571 standard or to the name of a GNAT-specific pragma defined
21572 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21573 Manual}, it is treated as the name of unknown pragma.
21574
21575 @item @code{GNAT}
21576 All the GNAT-specific pragmas are detected; this sets
21577 the checks for all the specified pragmas ON.
21578
21579 @item @code{ALL}
21580 All pragmas are detected; this sets the rule ON.
21581 @end table
21582
21583 @item For the @option{-R} option
21584 @table @asis
21585 @item @emph{Pragma_Name}
21586 Removes the specified pragma from the set of pragmas to be
21587 checked without affecting checks for
21588 other pragmas. @emph{Pragma_Name} is treated as a name
21589 of a pragma. If it does not correspond to any pragma
21590 defined in the Ada standard or to any name defined in
21591 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21592 this option is treated as turning OFF detection of all unknown pragmas.
21593
21594 @item GNAT
21595 Turn OFF detection of all GNAT-specific pragmas
21596
21597 @item ALL
21598 Clear the list of the pragmas to be detected and
21599 turn the rule OFF.
21600 @end table
21601 @end itemize
21602
21603 @noindent
21604 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21605 the syntax of an Ada identifier and therefore can not be considered
21606 as a pragma name, a diagnostic message is generated and the corresponding
21607 parameter is ignored.
21608
21609 When more then one parameter is given in the same rule option, the parameters
21610 must be separated by a comma.
21611
21612 If more then one option for this rule is specified for the @command{gnatcheck}
21613 call, a new option overrides the previous one(s).
21614
21615 The @option{+R} option with no parameters turns the rule ON with the set of
21616 pragmas to be detected defined by the previous rule options.
21617 (By default this set is empty, so if the only option specified for the rule is
21618 @option{+RForbidden_Pragmas} (with
21619 no parameter), then the rule is enabled, but it does not detect anything).
21620 The @option{-R} option with no parameter turns the rule OFF, but it does not
21621 affect the set of pragmas to be detected.
21622
21623
21624
21625
21626 @node Function_Style_Procedures
21627 @subsection @code{Function_Style_Procedures}
21628 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21629
21630 @noindent
21631 Flag each procedure that can be rewritten as a function. A procedure can be
21632 converted into a function if it has exactly one parameter of mode @code{out}
21633 and no parameters of mode @code{in out}. Procedure declarations,
21634 formal procedure declarations, and generic procedure declarations are always
21635 checked. Procedure
21636 bodies and body stubs are flagged only if they do not have corresponding
21637 separate declarations. Procedure renamings and procedure instantiations are
21638 not flagged.
21639
21640 If a procedure can be rewritten as a function, but its @code{out} parameter is
21641 of a limited type, it is not flagged.
21642
21643 Protected procedures are not flagged. Null procedures also are not flagged.
21644
21645 This rule has no parameters.
21646
21647
21648 @node Generics_In_Subprograms
21649 @subsection @code{Generics_In_Subprograms}
21650 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21651
21652 @noindent
21653 Flag each declaration of a generic unit in a subprogram. Generic
21654 declarations in the bodies of generic subprograms are also flagged.
21655 A generic unit nested in another generic unit is not flagged.
21656 If a generic unit is
21657 declared in a local package that is declared in a subprogram body, the
21658 generic unit is flagged.
21659
21660 This rule has no parameters.
21661
21662
21663 @node GOTO_Statements
21664 @subsection @code{GOTO_Statements}
21665 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21666
21667 @noindent
21668 Flag each occurrence of a @code{goto} statement.
21669
21670 This rule has no parameters.
21671
21672
21673 @node Implicit_IN_Mode_Parameters
21674 @subsection @code{Implicit_IN_Mode_Parameters}
21675 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21676
21677 @noindent
21678 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21679 Note that @code{access} parameters, although they technically behave
21680 like @code{in} parameters, are not flagged.
21681
21682 This rule has no parameters.
21683
21684
21685 @node Implicit_SMALL_For_Fixed_Point_Types
21686 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21687 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21688
21689 @noindent
21690 Flag each fixed point type declaration that lacks an explicit
21691 representation  clause to define its @code{'Small} value.
21692 Since @code{'Small} can be  defined only for ordinary fixed point types,
21693 decimal fixed point type declarations are not checked.
21694
21695 This rule has no parameters.
21696
21697
21698 @node Improperly_Located_Instantiations
21699 @subsection @code{Improperly_Located_Instantiations}
21700 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21701
21702 @noindent
21703 Flag all generic instantiations in library-level package specs
21704 (including library generic packages) and in all subprogram bodies.
21705
21706 Instantiations in task and entry bodies are not flagged. Instantiations in the
21707 bodies of protected subprograms are flagged.
21708
21709 This rule has no parameters.
21710
21711
21712
21713 @node Improper_Returns
21714 @subsection @code{Improper_Returns}
21715 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21716
21717 @noindent
21718 Flag each explicit @code{return} statement in procedures, and
21719 multiple @code{return} statements in functions.
21720 Diagnostic messages are generated for all @code{return} statements
21721 in a procedure (thus each procedure must be written so that it
21722 returns implicitly at the end of its statement part),
21723 and for all @code{return} statements in a function after the first one.
21724 This rule supports the stylistic convention that each subprogram
21725 should have no more than one point of normal return.
21726
21727 This rule has no parameters.
21728
21729
21730 @node Library_Level_Subprograms
21731 @subsection @code{Library_Level_Subprograms}
21732 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21733
21734 @noindent
21735 Flag all library-level subprograms (including generic subprogram instantiations).
21736
21737 This rule has no parameters.
21738
21739
21740 @node Local_Packages
21741 @subsection @code{Local_Packages}
21742 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21743
21744 @noindent
21745 Flag all local packages declared in package and generic package
21746 specs.
21747 Local packages in bodies are not flagged.
21748
21749 This rule has no parameters.
21750
21751 @ignore
21752 @node Improperly_Called_Protected_Entries
21753 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21754 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21755
21756 @noindent
21757 Flag each protected entry that can be called from more than one task.
21758
21759 This rule has no parameters.
21760 @end ignore
21761
21762 @node Metrics
21763 @subsection @code{Metrics}
21764 @cindex @code{Metrics} rule (for @command{gnatcheck})
21765
21766 @noindent
21767 There is a set of checks based on computing a metric value and comparing the
21768 result with the specified upper (or lower, depending on a specific metric)
21769 value specified for a given metric. A construct is flagged if a given metric
21770 is applicable (can be computed) for it and the computed value is greater
21771 then (lover then) the specified upper (lower) bound.
21772
21773 The name of any metric-based rule consists of the prefix @code{Metrics_}
21774 followed by the name of the corresponding metric (see the table below).
21775 For @option{+R} option, each metric-based rule has a numeric parameter
21776 specifying the bound (integer or real, depending on a metric), @option{-R}
21777 option for metric rules does not have a parameter.
21778
21779 The following table shows the metric names for that the corresponding
21780 metrics-based checks are supported by gnatcheck, including the
21781 constraint that must be satisfied by the bound that is specified for the check
21782 and what bound - upper (U) or lower (L) - should be specified.
21783
21784 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21785 @ifnothtml
21786 @headitem Check Name @tab Description @tab Bounds Value
21787 @end ifnothtml
21788 @ifhtml
21789 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21790 @end ifhtml
21791 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21792 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21793 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21794 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21795 @end multitable
21796
21797 @noindent
21798 The meaning and the computed values for all these metrics are exactly
21799 the same as for the corresponding metrics in @command{gnatmetric}.
21800
21801 @emph{Example:} the rule
21802 @smallexample
21803 +RMetrics_Cyclomatic_Complexity : 7
21804 @end smallexample
21805 @noindent
21806 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21807
21808 To turn OFF the check for cyclomatic complexity metric, use the following option:
21809 @smallexample
21810 -RMetrics_Cyclomatic_Complexity
21811 @end smallexample
21812
21813
21814 @node Misnamed_Controlling_Parameters
21815 @subsection @code{Misnamed_Controlling_Parameters}
21816 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21817
21818 @noindent
21819 Flags a declaration of a dispatching operation, if the first parameter is
21820 not a controlling one and its name is not @code{This} (the check for
21821 parameter name is not case-sensitive). Declarations of dispatching functions
21822 with controlling result and no controlling parameter are never flagged.
21823
21824 A subprogram body declaration, subprogram renaming declaration or subprogram
21825 body stub is flagged only if it is not a completion of a prior subprogram
21826 declaration.
21827
21828 This rule has no parameters.
21829
21830
21831
21832 @node Misnamed_Identifiers
21833 @subsection @code{Misnamed_Identifiers}
21834 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21835
21836 @noindent
21837 Flag the declaration of each identifier that does not have a suffix
21838 corresponding to the kind of entity being declared.
21839 The following declarations are checked:
21840
21841 @itemize @bullet
21842 @item
21843 type declarations
21844
21845 @item
21846 subtype declarations
21847
21848 @item
21849 constant declarations (but not number declarations)
21850
21851 @item
21852 package renaming declarations (but not generic package renaming
21853 declarations)
21854 @end itemize
21855
21856 @noindent
21857 This rule may have parameters. When used without parameters, the rule enforces
21858 the following checks:
21859
21860 @itemize @bullet
21861 @item
21862 type-defining names end with @code{_T}, unless the type is an access type,
21863 in which case the suffix must be @code{_A}
21864 @item
21865 constant names end with @code{_C}
21866 @item
21867 names defining package renamings end with @code{_R}
21868 @end itemize
21869
21870 @noindent
21871 Defining identifiers from incomplete type declarations are never flagged.
21872
21873 For a private type declaration (including private extensions), the defining
21874 identifier from the private type declaration is checked against the type
21875 suffix (even if the corresponding full declaration is an access type
21876 declaration), and the defining identifier from the corresponding full type
21877 declaration is not checked.
21878
21879 @noindent
21880 For a deferred constant, the defining name in the corresponding full constant
21881 declaration is not checked.
21882
21883 Defining names of formal types are not checked.
21884
21885 The rule may have the following parameters:
21886
21887 @itemize @bullet
21888 @item
21889 For the @option{+R} option:
21890 @table @code
21891 @item Default
21892 Sets the default listed above for all the names to be checked.
21893
21894 @item Type_Suffix=@emph{string}
21895 Specifies the suffix for a type name.
21896
21897 @item Access_Suffix=@emph{string}
21898 Specifies the suffix for an access type name. If
21899 this parameter is set, it overrides for access
21900 types the suffix set by the @code{Type_Suffix} parameter.
21901 For access types, @emph{string} may have the following format:
21902 @emph{suffix1(suffix2)}. That means that an access type name
21903 should have the @emph{suffix1} suffix except for the case when
21904 the designated type is also an access type, in this case the
21905 type name should have the @emph{suffix1 & suffix2} suffix.
21906
21907 @item Class_Access_Suffix=@emph{string}
21908 Specifies the suffix for the name of an access type that points to some class-wide
21909 type. If this parameter is set, it overrides for such access
21910 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
21911 parameter.
21912
21913 @item Class_Subtype_Suffix=@emph{string}
21914 Specifies the suffix for the name of a subtype that denotes a class-wide type.
21915
21916 @item Constant_Suffix=@emph{string}
21917 Specifies the suffix for a constant name.
21918
21919 @item Renaming_Suffix=@emph{string}
21920 Specifies the suffix for a package renaming name.
21921 @end table
21922
21923 @item
21924 For the @option{-R} option:
21925 @table @code
21926 @item All_Suffixes
21927 Remove all the suffixes specified for the
21928 identifier suffix checks, whether by default or
21929 as specified by other rule parameters. All the
21930 checks for this rule are disabled as a result.
21931
21932 @item Type_Suffix
21933 Removes the suffix specified for types. This
21934 disables checks for types but does not disable
21935 any other checks for this rule (including the
21936 check for access type names if @code{Access_Suffix} is
21937 set).
21938
21939 @item Access_Suffix
21940 Removes the suffix specified for access types.
21941 This disables checks for access type names but
21942 does not disable any other checks for this rule.
21943 If @code{Type_Suffix} is set, access type names are
21944 checked as ordinary type names.
21945
21946 @item Class_Access_Suffix
21947 Removes the suffix specified for access types pointing to class-wide
21948 type. This disables specific checks for names of access types pointing to
21949 class-wide types but does not disable any other checks for this rule.
21950 If @code{Type_Suffix} is set, access type names are
21951 checked as ordinary type names. If @code{Access_Suffix} is set, these
21952 access types are checked as any other access type name.
21953
21954 @item Class_Subtype_Suffix=@emph{string}
21955 Removes the suffix specified for subtype names.
21956 This disables checks for subtype names but
21957 does not disable any other checks for this rule.
21958
21959 @item Constant_Suffix
21960 Removes the suffix specified for constants. This
21961 disables checks for constant names but does not
21962 disable any other checks for this rule.
21963
21964 @item Renaming_Suffix
21965 Removes the suffix specified for package
21966 renamings. This disables checks for package
21967 renamings but does not disable any other checks
21968 for this rule.
21969 @end table
21970 @end itemize
21971
21972 @noindent
21973 If more than one parameter is used, parameters must be separated by commas.
21974
21975 If more than one  option is specified for the @command{gnatcheck} invocation,
21976 a new option overrides the previous one(s).
21977
21978 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21979 checks for all the
21980 name suffixes specified by previous options used for this rule.
21981
21982 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21983 all the checks but keeps
21984 all the suffixes specified by previous options used for this rule.
21985
21986 The @emph{string} value must be a valid suffix for an Ada identifier (after
21987 trimming all the leading and trailing space characters, if any).
21988 Parameters are not case sensitive, except the @emph{string} part.
21989
21990 If any error is detected in a rule parameter, the parameter is ignored.
21991 In such a case the options that are set for the rule are not
21992 specified.
21993
21994
21995
21996 @node Multiple_Entries_In_Protected_Definitions
21997 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21998 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21999
22000 @noindent
22001 Flag each protected definition (i.e., each protected object/type declaration)
22002 that defines more than one entry.
22003 Diagnostic messages are generated for all the entry declarations
22004 except the first one. An entry family is counted as one entry. Entries from
22005 the private part of the protected definition are also checked.
22006
22007 This rule has no parameters.
22008
22009 @node Name_Clashes
22010 @subsection @code{Name_Clashes}
22011 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22012
22013 @noindent
22014 Check that certain names are not used as defining identifiers. To activate
22015 this rule, you need to supply a reference to the dictionary file(s) as a rule
22016 parameter(s) (more then one dictionary file can be specified). If no
22017 dictionary file is set, this rule will not cause anything to be flagged.
22018 Only defining occurrences, not references, are checked.
22019 The check is not case-sensitive.
22020
22021 This rule is enabled by default, but without setting any corresponding
22022 dictionary file(s); thus the default effect is to do no checks.
22023
22024 A dictionary file is a plain text file. The maximum line length for this file
22025 is 1024 characters.  If the line is longer then this limit, extra characters
22026 are ignored.
22027
22028 Each line can be either an empty line, a comment line, or a line containing
22029 a list of identifiers separated by space or HT characters.
22030 A comment is an Ada-style comment (from @code{--} to end-of-line).
22031 Identifiers must follow the Ada syntax for identifiers.
22032 A line containing one or more identifiers may end with a comment.
22033
22034 @node Non_Qualified_Aggregates
22035 @subsection @code{Non_Qualified_Aggregates}
22036 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22037
22038 @noindent
22039 Flag each non-qualified aggregate.
22040 A non-qualified aggregate is an
22041 aggregate that is not the expression of a qualified expression. A
22042 string literal is not considered an aggregate, but an array
22043 aggregate of a string type is considered as a normal aggregate.
22044 Aggregates of anonymous array types are not flagged.
22045
22046 This rule has no parameters.
22047
22048
22049 @node Non_Short_Circuit_Operators
22050 @subsection @code{Non_Short_Circuit_Operators}
22051 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22052
22053 @noindent
22054 Flag all calls to predefined @code{and} and @code{or} operators for
22055 any boolean type. Calls to
22056 user-defined @code{and} and @code{or} and to operators defined by renaming
22057 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22058 operators for modular types or boolean array types are not flagged.
22059
22060 This rule has no parameters.
22061
22062
22063
22064 @node Non_SPARK_Attributes
22065 @subsection @code{Non_SPARK_Attributes}
22066 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22067
22068 @noindent
22069 The SPARK language defines the following subset of Ada 95 attribute
22070 designators as those that can be used in SPARK programs. The use of
22071 any other attribute is flagged.
22072
22073 @itemize @bullet
22074 @item @code{'Adjacent}
22075 @item @code{'Aft}
22076 @item @code{'Base}
22077 @item @code{'Ceiling}
22078 @item @code{'Component_Size}
22079 @item @code{'Compose}
22080 @item @code{'Copy_Sign}
22081 @item @code{'Delta}
22082 @item @code{'Denorm}
22083 @item @code{'Digits}
22084 @item @code{'Exponent}
22085 @item @code{'First}
22086 @item @code{'Floor}
22087 @item @code{'Fore}
22088 @item @code{'Fraction}
22089 @item @code{'Last}
22090 @item @code{'Leading_Part}
22091 @item @code{'Length}
22092 @item @code{'Machine}
22093 @item @code{'Machine_Emax}
22094 @item @code{'Machine_Emin}
22095 @item @code{'Machine_Mantissa}
22096 @item @code{'Machine_Overflows}
22097 @item @code{'Machine_Radix}
22098 @item @code{'Machine_Rounds}
22099 @item @code{'Max}
22100 @item @code{'Min}
22101 @item @code{'Model}
22102 @item @code{'Model_Emin}
22103 @item @code{'Model_Epsilon}
22104 @item @code{'Model_Mantissa}
22105 @item @code{'Model_Small}
22106 @item @code{'Modulus}
22107 @item @code{'Pos}
22108 @item @code{'Pred}
22109 @item @code{'Range}
22110 @item @code{'Remainder}
22111 @item @code{'Rounding}
22112 @item @code{'Safe_First}
22113 @item @code{'Safe_Last}
22114 @item @code{'Scaling}
22115 @item @code{'Signed_Zeros}
22116 @item @code{'Size}
22117 @item @code{'Small}
22118 @item @code{'Succ}
22119 @item @code{'Truncation}
22120 @item @code{'Unbiased_Rounding}
22121 @item @code{'Val}
22122 @item @code{'Valid}
22123 @end itemize
22124
22125 @noindent
22126 This rule has no parameters.
22127
22128
22129 @node Non_Tagged_Derived_Types
22130 @subsection @code{Non_Tagged_Derived_Types}
22131 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22132
22133 @noindent
22134 Flag all derived type declarations that do not have a record extension part.
22135
22136 This rule has no parameters.
22137
22138
22139
22140 @node Non_Visible_Exceptions
22141 @subsection @code{Non_Visible_Exceptions}
22142 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22143
22144 @noindent
22145 Flag constructs leading to the possibility of propagating an exception
22146 out of the scope in which the exception is declared.
22147 Two cases are detected:
22148
22149 @itemize @bullet
22150 @item
22151 An exception declaration in a subprogram body, task body or block
22152 statement is flagged if the body or statement does not contain a handler for
22153 that exception or a handler with an @code{others} choice.
22154
22155 @item
22156 A @code{raise} statement in an exception handler of a subprogram body,
22157 task body or block statement is flagged if it (re)raises a locally
22158 declared exception.  This may occur under the following circumstances:
22159 @itemize @minus
22160 @item
22161 it explicitly raises a locally declared exception, or
22162 @item
22163 it does not specify an exception name (i.e., it is simply @code{raise;})
22164 and the enclosing handler contains a locally declared exception in its
22165 exception choices.
22166 @end itemize
22167 @end itemize
22168
22169 @noindent
22170 Renamings of local exceptions are not flagged.
22171
22172 This rule has no parameters.
22173
22174
22175 @node Numeric_Literals
22176 @subsection @code{Numeric_Literals}
22177 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22178
22179 @noindent
22180 Flag each use of a numeric literal in an index expression, and in any
22181 circumstance except for the following:
22182
22183 @itemize @bullet
22184 @item
22185 a literal occurring in the initialization expression for a constant
22186 declaration or a named number declaration, or
22187
22188 @item
22189 an integer literal that is less than or equal to a value
22190 specified by the @option{N} rule parameter.
22191 @end itemize
22192
22193 @noindent
22194 This rule may have the following parameters for the @option{+R} option:
22195
22196 @table @asis
22197 @item @emph{N}
22198 @emph{N} is an integer literal used as the maximal value that is not flagged
22199 (i.e., integer literals not exceeding this value are allowed)
22200
22201 @item @code{ALL}
22202 All integer literals are flagged
22203 @end table
22204
22205 @noindent
22206 If no parameters are set, the maximum unflagged value is 1.
22207
22208 The last specified check limit (or the fact that there is no limit at
22209 all) is used when multiple @option{+R} options appear.
22210
22211 The @option{-R} option for this rule has no parameters.
22212 It disables the rule but retains the last specified maximum unflagged value.
22213 If the @option{+R} option subsequently appears, this value is used as the
22214 threshold for the check.
22215
22216
22217 @node OTHERS_In_Aggregates
22218 @subsection @code{OTHERS_In_Aggregates}
22219 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22220
22221 @noindent
22222 Flag each use of an @code{others} choice in extension aggregates.
22223 In record and array aggregates, an @code{others} choice is flagged unless
22224 it is used to refer to all components, or to all but one component.
22225
22226 If, in case of a named array aggregate, there are two associations, one
22227 with an @code{others} choice and another with a discrete range, the
22228 @code{others} choice is flagged even if the discrete range specifies
22229 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22230
22231 This rule has no parameters.
22232
22233 @node OTHERS_In_CASE_Statements
22234 @subsection @code{OTHERS_In_CASE_Statements}
22235 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22236
22237 @noindent
22238 Flag any use of an @code{others} choice in a @code{case} statement.
22239
22240 This rule has no parameters.
22241
22242 @node OTHERS_In_Exception_Handlers
22243 @subsection @code{OTHERS_In_Exception_Handlers}
22244 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22245
22246 @noindent
22247 Flag any use of an @code{others} choice in an exception handler.
22248
22249 This rule has no parameters.
22250
22251
22252 @node Outer_Loop_Exits
22253 @subsection @code{Outer_Loop_Exits}
22254 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22255
22256 @noindent
22257 Flag each @code{exit} statement containing a loop name that is not the name
22258 of the immediately enclosing @code{loop} statement.
22259
22260 This rule has no parameters.
22261
22262
22263 @node Overloaded_Operators
22264 @subsection @code{Overloaded_Operators}
22265 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22266
22267 @noindent
22268 Flag each function declaration that overloads an operator symbol.
22269 A function body is checked only if the body does not have a
22270 separate spec. Formal functions are also checked. For a
22271 renaming declaration, only renaming-as-declaration is checked
22272
22273 This rule has no parameters.
22274
22275
22276 @node Overly_Nested_Control_Structures
22277 @subsection @code{Overly_Nested_Control_Structures}
22278 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22279
22280 @noindent
22281 Flag each control structure whose nesting level exceeds the value provided
22282 in the rule parameter.
22283
22284 The control structures checked are the following:
22285
22286 @itemize @bullet
22287 @item    @code{if} statement
22288 @item    @code{case} statement
22289 @item    @code{loop} statement
22290 @item    Selective accept statement
22291 @item    Timed entry call statement
22292 @item    Conditional entry call
22293 @item    Asynchronous select statement
22294 @end itemize
22295
22296 @noindent
22297 The rule has the following parameter for the @option{+R} option:
22298
22299 @table @emph
22300 @item N
22301 Positive integer specifying the maximal control structure nesting
22302 level that is not flagged
22303 @end table
22304
22305 @noindent
22306 If the parameter for the @option{+R} option is not specified or
22307 if it is not a positive integer, @option{+R} option is ignored.
22308
22309 If more then one  option is specified for the gnatcheck call, the later option and
22310 new parameter override the previous one(s).
22311
22312
22313 @node Parameters_Out_Of_Order
22314 @subsection @code{Parameters_Out_Of_Order}
22315 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22316
22317 @noindent
22318 Flag each subprogram and entry declaration whose formal parameters are not
22319 ordered according to the following scheme:
22320
22321 @itemize @bullet
22322
22323 @item @code{in} and @code{access} parameters first,
22324 then @code{in out} parameters,
22325 and then @code{out} parameters;
22326
22327 @item for @code{in} mode, parameters with default initialization expressions
22328 occur last
22329 @end itemize
22330
22331 @noindent
22332 Only the first violation of the described order is flagged.
22333
22334 The following constructs are checked:
22335
22336 @itemize @bullet
22337 @item   subprogram declarations (including null procedures);
22338 @item   generic subprogram declarations;
22339 @item   formal subprogram declarations;
22340 @item   entry declarations;
22341 @item   subprogram bodies and subprogram body stubs that do not
22342 have separate specifications
22343 @end itemize
22344
22345 @noindent
22346 Subprogram renamings are not checked.
22347
22348 This rule has no parameters.
22349
22350
22351 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22352 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22353 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22354
22355 @noindent
22356 Flag each generic actual parameter corresponding to a generic formal
22357 parameter with a default initialization, if positional notation is used.
22358
22359 This rule has no parameters.
22360
22361 @node Positional_Actuals_For_Defaulted_Parameters
22362 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22363 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22364
22365 @noindent
22366 Flag each actual parameter to a subprogram or entry call where the
22367 corresponding formal parameter has a default expression, if positional
22368 notation is used.
22369
22370 This rule has no parameters.
22371
22372 @node Positional_Components
22373 @subsection @code{Positional_Components}
22374 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22375
22376 @noindent
22377 Flag each array, record and extension aggregate that includes positional
22378 notation.
22379
22380 This rule has no parameters.
22381
22382
22383 @node Positional_Generic_Parameters
22384 @subsection @code{Positional_Generic_Parameters}
22385 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22386
22387 @noindent
22388 Flag each instantiation using positional parameter notation.
22389
22390 This rule has no parameters.
22391
22392
22393 @node Positional_Parameters
22394 @subsection @code{Positional_Parameters}
22395 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22396
22397 @noindent
22398 Flag each subprogram or entry call using positional parameter notation,
22399 except for the following:
22400
22401 @itemize @bullet
22402 @item
22403 Invocations of prefix or infix operators are not flagged
22404 @item
22405 If the called subprogram or entry has only one formal parameter,
22406 the call is not flagged;
22407 @item
22408 If a subprogram call uses the @emph{Object.Operation} notation, then
22409 @itemize @minus
22410 @item
22411 the first parameter (that is, @emph{Object}) is not flagged;
22412 @item
22413 if the called subprogram has only two parameters, the second parameter
22414 of the call is not flagged;
22415 @end itemize
22416 @end itemize
22417
22418 @noindent
22419 This rule has no parameters.
22420
22421
22422
22423
22424 @node Predefined_Numeric_Types
22425 @subsection @code{Predefined_Numeric_Types}
22426 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22427
22428 @noindent
22429 Flag each explicit use of the name of any numeric type or subtype defined
22430 in package @code{Standard}.
22431
22432 The rationale for this rule is to detect when the
22433 program may depend on platform-specific characteristics of the implementation
22434 of the predefined numeric types. Note that this rule is over-pessimistic;
22435 for example, a program that uses @code{String} indexing
22436 likely needs a variable of type @code{Integer}.
22437 Another example is the flagging of predefined numeric types with explicit
22438 constraints:
22439
22440 @smallexample @c ada
22441     subtype My_Integer is Integer range Left .. Right;
22442     Vy_Var : My_Integer;
22443 @end smallexample
22444
22445 @noindent
22446 This rule detects only numeric types and subtypes defined in
22447 @code{Standard}. The use of numeric types and subtypes defined in other
22448 predefined packages (such as @code{System.Any_Priority} or
22449 @code{Ada.Text_IO.Count}) is not flagged
22450
22451 This rule has no parameters.
22452
22453
22454
22455 @node Raising_External_Exceptions
22456 @subsection @code{Raising_External_Exceptions}
22457 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22458
22459 @noindent
22460 Flag any @code{raise} statement, in a program unit declared in a library
22461 package or in a generic library package, for an exception that is
22462 neither a predefined exception nor an exception that is also declared (or
22463 renamed) in the visible part of the package.
22464
22465 This rule has no parameters.
22466
22467
22468
22469 @node Raising_Predefined_Exceptions
22470 @subsection @code{Raising_Predefined_Exceptions}
22471 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22472
22473 @noindent
22474 Flag each @code{raise} statement that raises a predefined exception
22475 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22476 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22477
22478 This rule has no parameters.
22479
22480 @node Separate_Numeric_Error_Handlers
22481 @subsection @code{Separate_Numeric_Error_Handlers}
22482 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22483
22484 @noindent
22485 Flags each exception handler that contains a choice for
22486 the predefined @code{Constraint_Error} exception, but does not contain
22487 the choice for the predefined @code{Numeric_Error} exception, or
22488 that contains the choice for @code{Numeric_Error}, but does not contain the
22489 choice for @code{Constraint_Error}.
22490
22491 This rule has no parameters.
22492
22493 @ignore
22494 @node Recursion
22495 @subsection @code{Recursion} (under construction, GLOBAL)
22496 @cindex @code{Recursion} rule (for @command{gnatcheck})
22497
22498 @noindent
22499 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22500 calls, of recursive subprograms are detected.
22501
22502 This rule has no parameters.
22503 @end ignore
22504
22505 @ignore
22506 @node Side_Effect_Functions
22507 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22508 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22509
22510 @noindent
22511 Flag functions with side effects.
22512
22513 We define a side effect as changing any data object that is not local for the
22514 body of this function.
22515
22516 At the moment, we do NOT consider a side effect any input-output operations
22517 (changing a state or a content of any file).
22518
22519 We do not consider protected functions for this rule (???)
22520
22521 There are the following sources of side effect:
22522
22523 @enumerate
22524 @item Explicit (or direct) side-effect:
22525
22526 @itemize @bullet
22527 @item
22528 direct assignment to a non-local variable;
22529
22530 @item
22531 direct call to an entity that is known to change some data object that is
22532      not local for the body of this function (Note, that if F1 calls F2 and F2
22533      does have a side effect, this does not automatically mean that F1 also
22534      have a side effect, because it may be the case that F2 is declared in
22535      F1's body and it changes some data object that is global for F2, but
22536      local for F1);
22537 @end itemize
22538
22539 @item Indirect side-effect:
22540 @itemize @bullet
22541 @item
22542 Subprogram calls implicitly issued by:
22543 @itemize @bullet
22544 @item
22545 computing initialization expressions from type declarations as a part
22546          of object elaboration or allocator evaluation;
22547 @item
22548 computing implicit parameters of subprogram or entry calls or generic
22549          instantiations;
22550 @end itemize
22551
22552 @item
22553 activation of a task that change some non-local data object (directly or
22554      indirectly);
22555
22556 @item
22557 elaboration code of a package that is a result of a package instantiation;
22558
22559 @item
22560 controlled objects;
22561 @end itemize
22562
22563 @item Situations when we can suspect a side-effect, but the full static check
22564 is either impossible or too hard:
22565 @itemize @bullet
22566 @item
22567 assignment to access variables or to the objects pointed by access
22568      variables;
22569
22570 @item
22571 call to a subprogram pointed by access-to-subprogram value
22572
22573 @item
22574 dispatching calls;
22575 @end itemize
22576 @end enumerate
22577
22578 @noindent
22579 This rule has no parameters.
22580 @end ignore
22581
22582 @node Slices
22583 @subsection @code{Slices}
22584 @cindex @code{Slices} rule (for @command{gnatcheck})
22585
22586 @noindent
22587 Flag all uses of array slicing
22588
22589 This rule has no parameters.
22590
22591
22592 @node Too_Many_Parents
22593 @subsection @code{Too_Many_Parents}
22594 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22595
22596 @noindent
22597 Flags any type declaration, single task declaration or single protected
22598 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22599 of the rule.
22600 A parent here is either a (sub)type denoted by the subtype mark from the
22601 parent_subtype_indication (in case of a derived type declaration), or
22602 any of the progenitors from the interface list, if any.
22603
22604 This rule has the following (mandatory) parameters for the @option{+R} option:
22605
22606 @table @emph
22607 @item N
22608 Positive integer specifying the maximal allowed number of parents.
22609 @end table
22610
22611
22612 @node Unassigned_OUT_Parameters
22613 @subsection @code{Unassigned_OUT_Parameters}
22614 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22615
22616 @noindent
22617 Flags procedures' @code{out} parameters that are not assigned, and
22618 identifies the contexts in which the assignments are missing.
22619
22620 An @code{out} parameter is flagged in the statements in the procedure
22621 body's handled sequence of statements (before the procedure body's
22622 @code{exception} part, if any) if this sequence of statements contains
22623 no assignments to the parameter.
22624
22625 An @code{out} parameter is flagged in an exception handler in the exception
22626 part of the procedure body's handled sequence of statements if the handler
22627 contains no assignment to the parameter.
22628
22629 Bodies of generic procedures are also considered.
22630
22631 The following are treated as assignments to an @code{out} parameter:
22632
22633 @itemize @bullet
22634 @item
22635 an assignment statement, with the parameter or some component as the target;
22636
22637 @item
22638 passing the parameter (or one of its components) as an @code{out} or
22639 @code{in out} parameter.
22640 @end itemize
22641
22642 @noindent
22643 This rule does not have any parameters.
22644
22645
22646
22647 @node Uncommented_BEGIN_In_Package_Bodies
22648 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22649 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22650
22651 @noindent
22652 Flags each package body with declarations and a statement part that does not
22653 include a trailing comment on the line containing the @code{begin} keyword;
22654 this trailing comment needs to specify the package name and nothing else.
22655 The @code{begin} is not flagged if the package body does not
22656 contain any declarations.
22657
22658 If the @code{begin} keyword is placed on the
22659 same line as the last declaration or the first statement, it is flagged
22660 independently of whether the line contains a trailing comment. The
22661 diagnostic message is attached to the line containing the first statement.
22662
22663 This rule has no parameters.
22664
22665 @node Unconditional_Exits
22666 @subsection @code{Unconditional_Exits}
22667 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22668
22669 @noindent
22670 Flag unconditional @code{exit} statements.
22671
22672 This rule has no parameters.
22673
22674 @node Unconstrained_Array_Returns
22675 @subsection @code{Unconstrained_Array_Returns}
22676 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22677
22678 @noindent
22679 Flag each function returning an unconstrained array. Function declarations,
22680 function bodies (and body stubs) having no separate specifications,
22681 and generic function instantiations are checked.
22682 Function calls and function renamings are
22683 not checked.
22684
22685 Generic function declarations, and function declarations in generic
22686 packages are not checked, instead this rule checks the results of
22687 generic instantiations (that is, expanded specification and expanded
22688 body corresponding to an instantiation).
22689
22690 This rule has no parameters.
22691
22692 @node Universal_Ranges
22693 @subsection @code{Universal_Ranges}
22694 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22695
22696 @noindent
22697 Flag discrete ranges that are a part of an index constraint, constrained
22698 array definition, or @code{for}-loop parameter specification, and whose bounds
22699 are both of type @i{universal_integer}. Ranges that have at least one
22700 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22701 or an expression of non-universal type) are not flagged.
22702
22703 This rule has no parameters.
22704
22705
22706 @node Unnamed_Blocks_And_Loops
22707 @subsection @code{Unnamed_Blocks_And_Loops}
22708 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22709
22710 @noindent
22711 Flag each unnamed block statement and loop statement.
22712
22713 The rule has no parameters.
22714
22715
22716
22717 @ignore
22718 @node Unused_Subprograms
22719 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22720 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22721
22722 @noindent
22723 Flag all unused subprograms.
22724
22725 This rule has no parameters.
22726 @end ignore
22727
22728
22729
22730
22731 @node USE_PACKAGE_Clauses
22732 @subsection @code{USE_PACKAGE_Clauses}
22733 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22734
22735 @noindent
22736 Flag all @code{use} clauses for packages; @code{use type} clauses are
22737 not flagged.
22738
22739 This rule has no parameters.
22740
22741
22742 @node Visible_Components
22743 @subsection @code{Visible_Components}
22744 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22745
22746 @noindent
22747 Flags all the type declarations located in the visible part of a library
22748 package or a library generic package that can declare a visible component. A
22749 type is considered as declaring a visible component if it contains a record
22750 definition by its own or as a part of a record extension. Type declaration is
22751 flagged even if it contains a record definition that defines no components.
22752
22753 Declarations located in private parts of local (generic) packages are not
22754 flagged. Declarations in private packages are not flagged.
22755
22756 This rule has no parameters.
22757
22758
22759 @node Volatile_Objects_Without_Address_Clauses
22760 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22761 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22762
22763 @noindent
22764 Flag each volatile object that does not have an address clause.
22765
22766 The following check is made: if the pragma @code{Volatile} is applied to a
22767 data object or to its type, then an address clause must
22768 be supplied for this object.
22769
22770 This rule does not check the components of data objects,
22771 array components that are volatile as a result of the pragma
22772 @code{Volatile_Components}, or objects that are volatile because
22773 they are atomic as a result of pragmas @code{Atomic} or
22774 @code{Atomic_Components}.
22775
22776 Only variable declarations, and not constant declarations, are checked.
22777
22778 This rule has no parameters.
22779
22780
22781 @c *********************************
22782 @node Creating Sample Bodies Using gnatstub
22783 @chapter Creating Sample Bodies Using @command{gnatstub}
22784 @findex gnatstub
22785
22786 @noindent
22787 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22788 for library unit declarations.
22789
22790 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22791 driver (see @ref{The GNAT Driver and Project Files}).
22792
22793 To create a body stub, @command{gnatstub} has to compile the library
22794 unit declaration. Therefore, bodies can be created only for legal
22795 library units. Moreover, if a library unit depends semantically upon
22796 units located outside the current directory, you have to provide
22797 the source search path when calling @command{gnatstub}, see the description
22798 of @command{gnatstub} switches below.
22799
22800 By default, all the program unit body stubs generated by @code{gnatstub}
22801 raise the predefined @code{Program_Error} exception, which will catch
22802 accidental calls of generated stubs. This behavior can be changed with
22803 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22804
22805 @menu
22806 * Running gnatstub::
22807 * Switches for gnatstub::
22808 @end menu
22809
22810 @node Running gnatstub
22811 @section Running @command{gnatstub}
22812
22813 @noindent
22814 @command{gnatstub} has the command-line interface of the form
22815
22816 @smallexample
22817 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22818 @end smallexample
22819
22820 @noindent
22821 where
22822 @table @var
22823 @item filename
22824 is the name of the source file that contains a library unit declaration
22825 for which a body must be created. The file name may contain the path
22826 information.
22827 The file name does not have to follow the GNAT file name conventions. If the
22828 name
22829 does not follow GNAT file naming conventions, the name of the body file must
22830 be provided
22831 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22832 If the file name follows the GNAT file naming
22833 conventions and the name of the body file is not provided,
22834 @command{gnatstub}
22835 creates the name
22836 of the body file from the argument file name by replacing the @file{.ads}
22837 suffix
22838 with the @file{.adb} suffix.
22839
22840 @item directory
22841 indicates the directory in which the body stub is to be placed (the default
22842 is the
22843 current directory)
22844
22845 @item switches
22846 is an optional sequence of switches as described in the next section
22847 @end table
22848
22849 @node Switches for gnatstub
22850 @section Switches for @command{gnatstub}
22851
22852 @table @option
22853 @c !sort!
22854
22855 @item ^-f^/FULL^
22856 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22857 If the destination directory already contains a file with the name of the
22858 body file
22859 for the argument spec file, replace it with the generated body stub.
22860
22861 @item ^-hs^/HEADER=SPEC^
22862 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22863 Put the comment header (i.e., all the comments preceding the
22864 compilation unit) from the source of the library unit declaration
22865 into the body stub.
22866
22867 @item ^-hg^/HEADER=GENERAL^
22868 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22869 Put a sample comment header into the body stub.
22870
22871 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22872 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22873 Use the content of the file as the comment header for a generated body stub.
22874
22875 @ifclear vms
22876 @item -IDIR
22877 @cindex @option{-IDIR} (@command{gnatstub})
22878 @itemx -I-
22879 @cindex @option{-I-} (@command{gnatstub})
22880 @end ifclear
22881 @ifset vms
22882 @item /NOCURRENT_DIRECTORY
22883 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22884 @end ifset
22885 ^These switches have ^This switch has^ the same meaning as in calls to
22886 @command{gcc}.
22887 ^They define ^It defines ^ the source search path in the call to
22888 @command{gcc} issued
22889 by @command{gnatstub} to compile an argument source file.
22890
22891 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22892 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22893 This switch has the same meaning as in calls to @command{gcc}.
22894 It defines the additional configuration file to be passed to the call to
22895 @command{gcc} issued
22896 by @command{gnatstub} to compile an argument source file.
22897
22898 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22899 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22900 (@var{n} is a non-negative integer). Set the maximum line length in the
22901 body stub to @var{n}; the default is 79. The maximum value that can be
22902 specified is 32767. Note that in the special case of configuration
22903 pragma files, the maximum is always 32767 regardless of whether or
22904 not this switch appears.
22905
22906 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22907 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22908 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22909 the generated body sample to @var{n}.
22910 The default indentation is 3.
22911
22912 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22913 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22914 Order local bodies alphabetically. (By default local bodies are ordered
22915 in the same way as the corresponding local specs in the argument spec file.)
22916
22917 @item ^-i^/INDENTATION=^@var{n}
22918 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22919 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22920
22921 @item ^-k^/TREE_FILE=SAVE^
22922 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22923 Do not remove the tree file (i.e., the snapshot of the compiler internal
22924 structures used by @command{gnatstub}) after creating the body stub.
22925
22926 @item ^-l^/LINE_LENGTH=^@var{n}
22927 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22928 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22929
22930 @item ^--no-exception^/NO_EXCEPTION^
22931 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22932 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22933 This is not always possible for function stubs.
22934
22935 @item ^--no-local-header^/NO_LOCAL_HEADER^
22936 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
22937 Do not place local comment header with unit name before body stub for a
22938 unit.
22939
22940 @item ^-o ^/BODY=^@var{body-name}
22941 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22942 Body file name.  This should be set if the argument file name does not
22943 follow
22944 the GNAT file naming
22945 conventions. If this switch is omitted the default name for the body will be
22946 obtained
22947 from the argument file name according to the GNAT file naming conventions.
22948
22949 @item ^-q^/QUIET^
22950 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22951 Quiet mode: do not generate a confirmation when a body is
22952 successfully created, and do not generate a message when a body is not
22953 required for an
22954 argument unit.
22955
22956 @item ^-r^/TREE_FILE=REUSE^
22957 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22958 Reuse the tree file (if it exists) instead of creating it.  Instead of
22959 creating the tree file for the library unit declaration, @command{gnatstub}
22960 tries to find it in the current directory and use it for creating
22961 a body. If the tree file is not found, no body is created. This option
22962 also implies @option{^-k^/SAVE^}, whether or not
22963 the latter is set explicitly.
22964
22965 @item ^-t^/TREE_FILE=OVERWRITE^
22966 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22967 Overwrite the existing tree file.  If the current directory already
22968 contains the file which, according to the GNAT file naming rules should
22969 be considered as a tree file for the argument source file,
22970 @command{gnatstub}
22971 will refuse to create the tree file needed to create a sample body
22972 unless this option is set.
22973
22974 @item ^-v^/VERBOSE^
22975 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22976 Verbose mode: generate version information.
22977
22978 @end table
22979
22980 @c *********************************
22981 @node Generating Ada Bindings for C and C++ headers
22982 @chapter Generating Ada Bindings for C and C++ headers
22983 @findex binding
22984
22985 @noindent
22986 GNAT now comes with a new experimental binding generator for C and C++
22987 headers which is intended to do 95% of the tedious work of generating
22988 Ada specs from C or C++ header files. Note that this still is a work in
22989 progress, not designed to generate 100% correct Ada specs.
22990
22991 The code generated is using the Ada 2005 syntax, which makes it
22992 easier to interface with other languages than previous versions of Ada.
22993
22994 @menu
22995 * Running the binding generator::
22996 * Generating bindings for C++ headers::
22997 * Switches::
22998 @end menu
22999
23000 @node Running the binding generator
23001 @section Running the binding generator
23002
23003 @noindent
23004 The binding generator is part of the @command{gcc} compiler and can be
23005 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23006 spec files for the header files specified on the command line, and all
23007 header files needed by these files transitivitely. For example:
23008
23009 @smallexample
23010 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23011 $ gcc -c -gnat05 *.ads
23012 @end smallexample
23013
23014 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23015 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23016 correspond to the files @file{/usr/include/time.h},
23017 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23018 mode these Ada specs.
23019
23020 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23021 and will attempt to generate corresponding Ada comments.
23022
23023 If you want to generate a single Ada file and not the transitive closure, you
23024 can use instead the @option{-fdump-ada-spec-slim} switch.
23025
23026 Note that we recommend when possible to use the @command{g++} driver to
23027 generate bindings, even for most C headers, since this will in general
23028 generate better Ada specs. For generating bindings for C++ headers, it is
23029 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23030 is equivalent in this case. If @command{g++} cannot work on your C headers
23031 because of incompatibilities between C and C++, then you can fallback to
23032 @command{gcc} instead.
23033
23034 For an example of better bindings generated from the C++ front-end,
23035 the name of the parameters (when available) are actually ignored by the C
23036 front-end. Consider the following C header:
23037
23038 @smallexample
23039 extern void foo (int variable);
23040 @end smallexample
23041
23042 with the C front-end, @code{variable} is ignored, and the above is handled as:
23043
23044 @smallexample
23045 extern void foo (int);
23046 @end smallexample
23047
23048 generating a generic:
23049
23050 @smallexample
23051 procedure foo (param1 : int);
23052 @end smallexample
23053
23054 with the C++ front-end, the name is available, and we generate:
23055
23056 @smallexample
23057 procedure foo (variable : int);
23058 @end smallexample
23059
23060 In some cases, the generated bindings will be more complete or more meaningful
23061 when defining some macros, which you can do via the @option{-D} switch. This
23062 is for example the case with @file{Xlib.h} under GNU/Linux:
23063
23064 @smallexample
23065 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23066 @end smallexample
23067
23068 The above will generate more complete bindings than a straight call without
23069 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23070
23071 In other cases, it is not possible to parse a header file in a stand alone
23072 manner, because other include files need to be included first. In this
23073 case, the solution is to create a small header file including the needed
23074 @code{#include} and possible @code{#define} directives. For example, to
23075 generate Ada bindings for @file{readline/readline.h}, you need to first
23076 include @file{stdio.h}, so you can create a file with the following two
23077 lines in e.g. @file{readline1.h}:
23078
23079 @smallexample
23080 #include <stdio.h>
23081 #include <readline/readline.h>
23082 @end smallexample
23083
23084 and then generate Ada bindings from this file:
23085
23086 @smallexample
23087 $ g++ -c -fdump-ada-spec readline1.h
23088 @end smallexample
23089
23090 @node Generating bindings for C++ headers
23091 @section Generating bindings for C++ headers
23092
23093 @noindent
23094 Generating bindings for C++ headers is done using the same options, always
23095 with the @command{g++} compiler.
23096
23097 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23098 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23099 multiple inheritance of abstract classes will be mapped to Ada interfaces
23100 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23101 information on interfacing to C++).
23102
23103 For example, given the following C++ header file:
23104
23105 @smallexample
23106 @group
23107 @cartouche
23108 class Carnivore @{
23109 public:
23110    virtual int Number_Of_Teeth () = 0;
23111 @};
23112
23113 class Domestic @{
23114 public:
23115    virtual void Set_Owner (char* Name) = 0;
23116 @};
23117
23118 class Animal @{
23119 public:
23120   int Age_Count;
23121   virtual void Set_Age (int New_Age);
23122 @};
23123
23124 class Dog : Animal, Carnivore, Domestic @{
23125  public:
23126   int  Tooth_Count;
23127   char *Owner;
23128
23129   virtual int  Number_Of_Teeth ();
23130   virtual void Set_Owner (char* Name);
23131
23132   Dog();
23133 @};
23134 @end cartouche
23135 @end group
23136 @end smallexample
23137
23138 The corresponding Ada code is generated:
23139
23140 @smallexample @c ada
23141 @group
23142 @cartouche
23143   package Class_Carnivore is
23144     type Carnivore is limited interface;
23145     pragma Import (CPP, Carnivore);
23146
23147     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23148   end;
23149   use Class_Carnivore;
23150
23151   package Class_Domestic is
23152     type Domestic is limited interface;
23153     pragma Import (CPP, Domestic);
23154
23155     procedure Set_Owner
23156       (this : access Domestic;
23157        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23158   end;
23159   use Class_Domestic;
23160
23161   package Class_Animal is
23162     type Animal is tagged limited record
23163       Age_Count : aliased int;
23164     end record;
23165     pragma Import (CPP, Animal);
23166
23167     procedure Set_Age (this : access Animal; New_Age : int);
23168     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23169   end;
23170   use Class_Animal;
23171
23172   package Class_Dog is
23173     type Dog is new Animal and Carnivore and Domestic with record
23174       Tooth_Count : aliased int;
23175       Owner : Interfaces.C.Strings.chars_ptr;
23176     end record;
23177     pragma Import (CPP, Dog);
23178
23179     function Number_Of_Teeth (this : access Dog) return int;
23180     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23181
23182     procedure Set_Owner
23183       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23184     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23185
23186     function New_Dog return Dog;
23187     pragma CPP_Constructor (New_Dog);
23188     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23189   end;
23190   use Class_Dog;
23191 @end cartouche
23192 @end group
23193 @end smallexample
23194
23195 @node Switches
23196 @section Switches
23197
23198 @table @option
23199 @item -fdump-ada-spec
23200 @cindex @option{-fdump-ada-spec} (@command{gcc})
23201 Generate Ada spec files for the given header files transitively (including
23202 all header files that these headers depend upon).
23203
23204 @item -fdump-ada-spec-slim
23205 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23206 Generate Ada spec files for the header files specified on the command line
23207 only.
23208
23209 @item -C
23210 @cindex @option{-C} (@command{gcc})
23211 Extract comments from headers and generate Ada comments in the Ada spec files.
23212 @end table
23213
23214 @node Other Utility Programs
23215 @chapter Other Utility Programs
23216
23217 @noindent
23218 This chapter discusses some other utility programs available in the Ada
23219 environment.
23220
23221 @menu
23222 * Using Other Utility Programs with GNAT::
23223 * The External Symbol Naming Scheme of GNAT::
23224 * Converting Ada Files to html with gnathtml::
23225 * Installing gnathtml::
23226 @ifset vms
23227 * LSE::
23228 * Profiling::
23229 @end ifset
23230 @end menu
23231
23232 @node Using Other Utility Programs with GNAT
23233 @section Using Other Utility Programs with GNAT
23234
23235 @noindent
23236 The object files generated by GNAT are in standard system format and in
23237 particular the debugging information uses this format. This means
23238 programs generated by GNAT can be used with existing utilities that
23239 depend on these formats.
23240
23241 @ifclear vms
23242 In general, any utility program that works with C will also often work with
23243 Ada programs generated by GNAT. This includes software utilities such as
23244 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23245 as Purify.
23246 @end ifclear
23247
23248 @node The External Symbol Naming Scheme of GNAT
23249 @section The External Symbol Naming Scheme of GNAT
23250
23251 @noindent
23252 In order to interpret the output from GNAT, when using tools that are
23253 originally intended for use with other languages, it is useful to
23254 understand the conventions used to generate link names from the Ada
23255 entity names.
23256
23257 All link names are in all lowercase letters. With the exception of library
23258 procedure names, the mechanism used is simply to use the full expanded
23259 Ada name with dots replaced by double underscores. For example, suppose
23260 we have the following package spec:
23261
23262 @smallexample @c ada
23263 @group
23264 @cartouche
23265 package QRS is
23266    MN : Integer;
23267 end QRS;
23268 @end cartouche
23269 @end group
23270 @end smallexample
23271
23272 @noindent
23273 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23274 the corresponding link name is @code{qrs__mn}.
23275 @findex Export
23276 Of course if a @code{pragma Export} is used this may be overridden:
23277
23278 @smallexample @c ada
23279 @group
23280 @cartouche
23281 package Exports is
23282    Var1 : Integer;
23283    pragma Export (Var1, C, External_Name => "var1_name");
23284    Var2 : Integer;
23285    pragma Export (Var2, C, Link_Name => "var2_link_name");
23286 end Exports;
23287 @end cartouche
23288 @end group
23289 @end smallexample
23290
23291 @noindent
23292 In this case, the link name for @var{Var1} is whatever link name the
23293 C compiler would assign for the C function @var{var1_name}. This typically
23294 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23295 system conventions, but other possibilities exist. The link name for
23296 @var{Var2} is @var{var2_link_name}, and this is not operating system
23297 dependent.
23298
23299 @findex _main
23300 One exception occurs for library level procedures. A potential ambiguity
23301 arises between the required name @code{_main} for the C main program,
23302 and the name we would otherwise assign to an Ada library level procedure
23303 called @code{Main} (which might well not be the main program).
23304
23305 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23306 names. So if we have a library level procedure such as
23307
23308 @smallexample @c ada
23309 @group
23310 @cartouche
23311 procedure Hello (S : String);
23312 @end cartouche
23313 @end group
23314 @end smallexample
23315
23316 @noindent
23317 the external name of this procedure will be @var{_ada_hello}.
23318
23319
23320 @node Converting Ada Files to html with gnathtml
23321 @section Converting Ada Files to HTML with @code{gnathtml}
23322
23323 @noindent
23324 This @code{Perl} script allows Ada source files to be browsed using
23325 standard Web browsers. For installation procedure, see the section
23326 @xref{Installing gnathtml}.
23327
23328 Ada reserved keywords are highlighted in a bold font and Ada comments in
23329 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23330 switch to suppress the generation of cross-referencing information, user
23331 defined variables and types will appear in a different color; you will
23332 be able to click on any identifier and go to its declaration.
23333
23334 The command line is as follow:
23335 @smallexample
23336 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23337 @end smallexample
23338
23339 @noindent
23340 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23341 an html file for every ada file, and a global file called @file{index.htm}.
23342 This file is an index of every identifier defined in the files.
23343
23344 The available ^switches^options^ are the following ones:
23345
23346 @table @option
23347 @item -83
23348 @cindex @option{-83} (@code{gnathtml})
23349 Only the Ada 83 subset of keywords will be highlighted.
23350
23351 @item -cc @var{color}
23352 @cindex @option{-cc} (@code{gnathtml})
23353 This option allows you to change the color used for comments. The default
23354 value is green. The color argument can be any name accepted by html.
23355
23356 @item -d
23357 @cindex @option{-d} (@code{gnathtml})
23358 If the Ada files depend on some other files (for instance through
23359 @code{with} clauses, the latter files will also be converted to html.
23360 Only the files in the user project will be converted to html, not the files
23361 in the run-time library itself.
23362
23363 @item -D
23364 @cindex @option{-D} (@code{gnathtml})
23365 This command is the same as @option{-d} above, but @command{gnathtml} will
23366 also look for files in the run-time library, and generate html files for them.
23367
23368 @item -ext @var{extension}
23369 @cindex @option{-ext} (@code{gnathtml})
23370 This option allows you to change the extension of the generated HTML files.
23371 If you do not specify an extension, it will default to @file{htm}.
23372
23373 @item -f
23374 @cindex @option{-f} (@code{gnathtml})
23375 By default, gnathtml will generate html links only for global entities
23376 ('with'ed units, global variables and types,@dots{}).  If you specify
23377 @option{-f} on the command line, then links will be generated for local
23378 entities too.
23379
23380 @item -l @var{number}
23381 @cindex @option{-l} (@code{gnathtml})
23382 If this ^switch^option^ is provided and @var{number} is not 0, then
23383 @code{gnathtml} will number the html files every @var{number} line.
23384
23385 @item -I @var{dir}
23386 @cindex @option{-I} (@code{gnathtml})
23387 Specify a directory to search for library files (@file{.ALI} files) and
23388 source files. You can provide several -I switches on the command line,
23389 and the directories will be parsed in the order of the command line.
23390
23391 @item -o @var{dir}
23392 @cindex @option{-o} (@code{gnathtml})
23393 Specify the output directory for html files. By default, gnathtml will
23394 saved the generated html files in a subdirectory named @file{html/}.
23395
23396 @item -p @var{file}
23397 @cindex @option{-p} (@code{gnathtml})
23398 If you are using Emacs and the most recent Emacs Ada mode, which provides
23399 a full Integrated Development Environment for compiling, checking,
23400 running and debugging applications, you may use @file{.gpr} files
23401 to give the directories where Emacs can find sources and object files.
23402
23403 Using this ^switch^option^, you can tell gnathtml to use these files.
23404 This allows you to get an html version of your application, even if it
23405 is spread over multiple directories.
23406
23407 @item -sc @var{color}
23408 @cindex @option{-sc} (@code{gnathtml})
23409 This ^switch^option^ allows you to change the color used for symbol
23410 definitions.
23411 The default value is red. The color argument can be any name accepted by html.
23412
23413 @item -t @var{file}
23414 @cindex @option{-t} (@code{gnathtml})
23415 This ^switch^option^ provides the name of a file. This file contains a list of
23416 file names to be converted, and the effect is exactly as though they had
23417 appeared explicitly on the command line. This
23418 is the recommended way to work around the command line length limit on some
23419 systems.
23420
23421 @end table
23422
23423 @node Installing gnathtml
23424 @section Installing @code{gnathtml}
23425
23426 @noindent
23427 @code{Perl} needs to be installed on your machine to run this script.
23428 @code{Perl} is freely available for almost every architecture and
23429 Operating System via the Internet.
23430
23431 On Unix systems, you  may want to modify  the  first line of  the script
23432 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23433 is. The syntax of this line is:
23434 @smallexample
23435 #!full_path_name_to_perl
23436 @end smallexample
23437
23438 @noindent
23439 Alternatively, you may run the script using the following command line:
23440
23441 @smallexample
23442 $ perl gnathtml.pl @ovar{switches} @var{files}
23443 @end smallexample
23444
23445 @ifset vms
23446 @node LSE
23447 @section LSE
23448 @findex LSE
23449
23450 @noindent
23451 The GNAT distribution provides an Ada 95 template for the HP Language
23452 Sensitive Editor (LSE), a component of DECset. In order to
23453 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23454
23455 @node Profiling
23456 @section Profiling
23457 @findex PCA
23458
23459 @noindent
23460 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23461 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23462 the collection phase with the /DEBUG qualifier.
23463
23464 @smallexample
23465 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23466 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23467 $ RUN/DEBUG <PROGRAM_NAME>
23468 @end smallexample
23469 @noindent
23470 @end ifset
23471
23472 @ifclear vms
23473 @c ******************************
23474 @node Code Coverage and Profiling
23475 @chapter Code Coverage and Profiling
23476 @cindex Code Coverage
23477 @cindex Profiling
23478
23479 @noindent
23480 This chapter describes how to use @code{gcov} - coverage testing tool - and
23481 @code{gprof} - profiler tool - on your Ada programs.
23482
23483 @menu
23484 * Code Coverage of Ada Programs using gcov::
23485 * Profiling an Ada Program using gprof::
23486 @end menu
23487
23488 @node Code Coverage of Ada Programs using gcov
23489 @section Code Coverage of Ada Programs using gcov
23490 @cindex gcov
23491 @cindex -fprofile-arcs
23492 @cindex -ftest-coverage
23493 @cindex -coverage
23494 @cindex Code Coverage
23495
23496 @noindent
23497 @code{gcov} is a test coverage program: it analyzes the execution of a given
23498 program on selected tests, to help you determine the portions of the program
23499 that are still untested.
23500
23501 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23502 User's Guide. You can refer to this documentation for a more complete
23503 description.
23504
23505 This chapter provides a quick startup guide, and
23506 details some Gnat-specific features.
23507
23508 @menu
23509 * Quick startup guide::
23510 * Gnat specifics::
23511 @end menu
23512
23513 @node Quick startup guide
23514 @subsection Quick startup guide
23515
23516 In order to perform coverage analysis of a program using @code{gcov}, 3
23517 steps are needed:
23518
23519 @itemize @bullet
23520 @item
23521 Code instrumentation during the compilation process
23522 @item
23523 Execution of the instrumented program
23524 @item
23525 Execution of the @code{gcov} tool to generate the result.
23526 @end itemize
23527
23528 The code instrumentation needed by gcov is created at the object level:
23529 The source code is not modified in any way, because the instrumentation code is
23530 inserted by gcc during the compilation process. To compile your code with code
23531 coverage activated, you need to recompile your whole project using the
23532 switches
23533 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23534 @code{-fprofile-arcs}.
23535
23536 @smallexample
23537 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23538    -largs -fprofile-arcs
23539 @end smallexample
23540
23541 This compilation process will create @file{.gcno} files together with
23542 the usual object files.
23543
23544 Once the program is compiled with coverage instrumentation, you can
23545 run it as many times as needed - on portions of a test suite for
23546 example. The first execution will produce @file{.gcda} files at the
23547 same location as the @file{.gcno} files.  The following executions
23548 will update those files, so that a cumulative result of the covered
23549 portions of the program is generated.
23550
23551 Finally, you need to call the @code{gcov} tool. The different options of
23552 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23553
23554 This will create annotated source files with a @file{.gcov} extension:
23555 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23556
23557 @node Gnat specifics
23558 @subsection Gnat specifics
23559
23560 Because Ada semantics, portions of the source code may be shared among
23561 several object files. This is the case for example when generics are
23562 involved, when inlining is active  or when declarations generate  initialisation
23563 calls. In order to take
23564 into account this shared code, you need to call @code{gcov} on all
23565 source files of the tested program at once.
23566
23567 The list of source files might exceed the system's maximum command line
23568 length. In order to bypass this limitation, a new mechanism has been
23569 implemented in @code{gcov}: you can now list all your project's files into a
23570 text file, and provide this file to gcov as a parameter,  preceded by a @@
23571 (e.g. @samp{gcov @@mysrclist.txt}).
23572
23573 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23574 not supported as there can be unresolved symbols during the final link.
23575
23576 @node Profiling an Ada Program using gprof
23577 @section Profiling an Ada Program using gprof
23578 @cindex gprof
23579 @cindex -pg
23580 @cindex Profiling
23581
23582 @noindent
23583 This section is not meant to be an exhaustive documentation of @code{gprof}.
23584 Full documentation for it can be found in the GNU Profiler User's Guide
23585 documentation that is part of this GNAT distribution.
23586
23587 Profiling a program helps determine the parts of a program that are executed
23588 most often, and are therefore the most time-consuming.
23589
23590 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23591 better handle Ada programs and multitasking.
23592 It is currently supported on the following platforms
23593 @itemize @bullet
23594 @item
23595 linux x86/x86_64
23596 @item
23597 solaris sparc/sparc64/x86
23598 @item
23599 windows x86
23600 @end itemize
23601
23602 @noindent
23603 In order to profile a program using @code{gprof}, 3 steps are needed:
23604
23605 @itemize @bullet
23606 @item
23607 Code instrumentation, requiring a full recompilation of the project with the
23608 proper switches.
23609 @item
23610 Execution of the program under the analysis conditions, i.e. with the desired
23611 input.
23612 @item
23613 Analysis of the results using the @code{gprof} tool.
23614 @end itemize
23615
23616 @noindent
23617 The following sections detail the different steps, and indicate how
23618 to interpret the results:
23619 @menu
23620 * Compilation for profiling::
23621 * Program execution::
23622 * Running gprof::
23623 * Interpretation of profiling results::
23624 @end menu
23625
23626 @node Compilation for profiling
23627 @subsection Compilation for profiling
23628 @cindex -pg
23629 @cindex Profiling
23630
23631 In order to profile a program the first step is to tell the compiler
23632 to generate the necessary profiling information. The compiler switch to be used
23633 is @code{-pg}, which must be added to other compilation switches. This
23634 switch needs to be specified both during compilation and link stages, and can
23635 be specified once when using gnatmake:
23636
23637 @smallexample
23638 gnatmake -f -pg -P my_project
23639 @end smallexample
23640
23641 @noindent
23642 Note that only the objects that were compiled with the @samp{-pg} switch will be
23643 profiled; if you need to profile your whole project, use the
23644 @samp{-f} gnatmake switch to force full recompilation.
23645
23646 @node Program execution
23647 @subsection Program execution
23648
23649 @noindent
23650 Once the program has been compiled for profiling, you can run it as usual.
23651
23652 The only constraint imposed by profiling is that the program must terminate
23653 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23654 properly analyzed.
23655
23656 Once the program completes execution, a data file called @file{gmon.out} is
23657 generated in the directory where the program was launched from. If this file
23658 already exists, it will be overwritten.
23659
23660 @node Running gprof
23661 @subsection Running gprof
23662
23663 @noindent
23664 The @code{gprof} tool is called as follow:
23665
23666 @smallexample
23667 gprof my_prog gmon.out
23668 @end smallexample
23669
23670 @noindent
23671 or simpler:
23672
23673 @smallexample
23674 gprof my_prog
23675 @end smallexample
23676
23677 @noindent
23678 The complete form of the gprof command line is the following:
23679
23680 @smallexample
23681 gprof [^switches^options^] [executable [data-file]]
23682 @end smallexample
23683
23684 @noindent
23685 @code{gprof} supports numerous ^switch^options^. The order of these
23686 ^switch^options^ does not matter. The full list of options can be found in
23687 the GNU Profiler User's Guide documentation that comes with this documentation.
23688
23689 The following is the subset of those switches that is most relevant:
23690
23691 @table @option
23692
23693 @item --demangle[=@var{style}]
23694 @itemx --no-demangle
23695 @cindex @option{--demangle} (@code{gprof})
23696 These options control whether symbol names should be demangled when
23697 printing output.  The default is to demangle C++ symbols.  The
23698 @code{--no-demangle} option may be used to turn off demangling. Different
23699 compilers have different mangling styles.  The optional demangling style
23700 argument can be used to choose an appropriate demangling style for your
23701 compiler, in particular Ada symbols generated by GNAT can be demangled using
23702 @code{--demangle=gnat}.
23703
23704 @item -e @var{function_name}
23705 @cindex @option{-e} (@code{gprof})
23706 The @samp{-e @var{function}} option tells @code{gprof} not to print
23707 information about the function @var{function_name} (and its
23708 children@dots{}) in the call graph.  The function will still be listed
23709 as a child of any functions that call it, but its index number will be
23710 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23711 given; only one @var{function_name} may be indicated with each @samp{-e}
23712 option.
23713
23714 @item -E @var{function_name}
23715 @cindex @option{-E} (@code{gprof})
23716 The @code{-E @var{function}} option works like the @code{-e} option, but
23717 execution time spent in the function (and children who were not called from
23718 anywhere else), will not be used to compute the percentages-of-time for
23719 the call graph.  More than one @samp{-E} option may be given; only one
23720 @var{function_name} may be indicated with each @samp{-E} option.
23721
23722 @item -f @var{function_name}
23723 @cindex @option{-f} (@code{gprof})
23724 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23725 call graph to the function @var{function_name} and its children (and
23726 their children@dots{}).  More than one @samp{-f} option may be given;
23727 only one @var{function_name} may be indicated with each @samp{-f}
23728 option.
23729
23730 @item -F @var{function_name}
23731 @cindex @option{-F} (@code{gprof})
23732 The @samp{-F @var{function}} option works like the @code{-f} option, but
23733 only time spent in the function and its children (and their
23734 children@dots{}) will be used to determine total-time and
23735 percentages-of-time for the call graph.  More than one @samp{-F} option
23736 may be given; only one @var{function_name} may be indicated with each
23737 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23738
23739 @end table
23740
23741 @node Interpretation of profiling results
23742 @subsection Interpretation of profiling results
23743
23744 @noindent
23745
23746 The results of the profiling analysis are represented by two arrays: the
23747 'flat profile' and the 'call graph'. Full documentation of those outputs
23748 can be found in the GNU Profiler User's Guide.
23749
23750 The flat profile shows the time spent in each function of the program, and how
23751 many time it has been called. This allows you to locate easily the most
23752 time-consuming functions.
23753
23754 The call graph shows, for each subprogram, the subprograms that call it,
23755 and the subprograms that it calls. It also provides an estimate of the time
23756 spent in each of those callers/called subprograms.
23757 @end ifclear
23758
23759 @c ******************************
23760 @node Running and Debugging Ada Programs
23761 @chapter Running and Debugging Ada Programs
23762 @cindex Debugging
23763
23764 @noindent
23765 This chapter discusses how to debug Ada programs.
23766 @ifset vms
23767 It applies to GNAT on the Alpha OpenVMS platform;
23768 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23769 since HP has implemented Ada support in the OpenVMS debugger on I64.
23770 @end ifset
23771
23772 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23773
23774 @enumerate
23775 @item
23776 The illegality may be a violation of the static semantics of Ada. In
23777 that case GNAT diagnoses the constructs in the program that are illegal.
23778 It is then a straightforward matter for the user to modify those parts of
23779 the program.
23780
23781 @item
23782 The illegality may be a violation of the dynamic semantics of Ada. In
23783 that case the program compiles and executes, but may generate incorrect
23784 results, or may terminate abnormally with some exception.
23785
23786 @item
23787 When presented with a program that contains convoluted errors, GNAT
23788 itself may terminate abnormally without providing full diagnostics on
23789 the incorrect user program.
23790 @end enumerate
23791
23792 @menu
23793 * The GNAT Debugger GDB::
23794 * Running GDB::
23795 * Introduction to GDB Commands::
23796 * Using Ada Expressions::
23797 * Calling User-Defined Subprograms::
23798 * Using the Next Command in a Function::
23799 * Ada Exceptions::
23800 * Ada Tasks::
23801 * Debugging Generic Units::
23802 * GNAT Abnormal Termination or Failure to Terminate::
23803 * Naming Conventions for GNAT Source Files::
23804 * Getting Internal Debugging Information::
23805 * Stack Traceback::
23806 @end menu
23807
23808 @cindex Debugger
23809 @findex gdb
23810
23811 @node The GNAT Debugger GDB
23812 @section The GNAT Debugger GDB
23813
23814 @noindent
23815 @code{GDB} is a general purpose, platform-independent debugger that
23816 can be used to debug mixed-language programs compiled with @command{gcc},
23817 and in particular is capable of debugging Ada programs compiled with
23818 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23819 complex Ada data structures.
23820
23821 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23822 @ifset vms
23823 located in the GNU:[DOCS] directory,
23824 @end ifset
23825 for full details on the usage of @code{GDB}, including a section on
23826 its usage on programs. This manual should be consulted for full
23827 details. The section that follows is a brief introduction to the
23828 philosophy and use of @code{GDB}.
23829
23830 When GNAT programs are compiled, the compiler optionally writes debugging
23831 information into the generated object file, including information on
23832 line numbers, and on declared types and variables. This information is
23833 separate from the generated code. It makes the object files considerably
23834 larger, but it does not add to the size of the actual executable that
23835 will be loaded into memory, and has no impact on run-time performance. The
23836 generation of debug information is triggered by the use of the
23837 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23838 used to carry out the compilations. It is important to emphasize that
23839 the use of these options does not change the generated code.
23840
23841 The debugging information is written in standard system formats that
23842 are used by many tools, including debuggers and profilers. The format
23843 of the information is typically designed to describe C types and
23844 semantics, but GNAT implements a translation scheme which allows full
23845 details about Ada types and variables to be encoded into these
23846 standard C formats. Details of this encoding scheme may be found in
23847 the file exp_dbug.ads in the GNAT source distribution. However, the
23848 details of this encoding are, in general, of no interest to a user,
23849 since @code{GDB} automatically performs the necessary decoding.
23850
23851 When a program is bound and linked, the debugging information is
23852 collected from the object files, and stored in the executable image of
23853 the program. Again, this process significantly increases the size of
23854 the generated executable file, but it does not increase the size of
23855 the executable program itself. Furthermore, if this program is run in
23856 the normal manner, it runs exactly as if the debug information were
23857 not present, and takes no more actual memory.
23858
23859 However, if the program is run under control of @code{GDB}, the
23860 debugger is activated.  The image of the program is loaded, at which
23861 point it is ready to run.  If a run command is given, then the program
23862 will run exactly as it would have if @code{GDB} were not present. This
23863 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23864 entirely non-intrusive until a breakpoint is encountered.  If no
23865 breakpoint is ever hit, the program will run exactly as it would if no
23866 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23867 the debugging information and can respond to user commands to inspect
23868 variables, and more generally to report on the state of execution.
23869
23870 @c **************
23871 @node Running GDB
23872 @section Running GDB
23873
23874 @noindent
23875 This section describes how to initiate the debugger.
23876 @c The above sentence is really just filler, but it was otherwise
23877 @c clumsy to get the first paragraph nonindented given the conditional
23878 @c nature of the description
23879
23880 @ifclear vms
23881 The debugger can be launched from a @code{GPS} menu or
23882 directly from the command line. The description below covers the latter use.
23883 All the commands shown can be used in the @code{GPS} debug console window,
23884 but there are usually more GUI-based ways to achieve the same effect.
23885 @end ifclear
23886
23887 The command to run @code{GDB} is
23888
23889 @smallexample
23890 $ ^gdb program^GDB PROGRAM^
23891 @end smallexample
23892
23893 @noindent
23894 where @code{^program^PROGRAM^} is the name of the executable file. This
23895 activates the debugger and results in a prompt for debugger commands.
23896 The simplest command is simply @code{run}, which causes the program to run
23897 exactly as if the debugger were not present. The following section
23898 describes some of the additional commands that can be given to @code{GDB}.
23899
23900 @c *******************************
23901 @node Introduction to GDB Commands
23902 @section Introduction to GDB Commands
23903
23904 @noindent
23905 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
23906 Debugging with GDB, gdb, Debugging with GDB},
23907 @ifset vms
23908 located in the GNU:[DOCS] directory,
23909 @end ifset
23910 for extensive documentation on the use
23911 of these commands, together with examples of their use. Furthermore,
23912 the command @command{help} invoked from within GDB activates a simple help
23913 facility which summarizes the available commands and their options.
23914 In this section we summarize a few of the most commonly
23915 used commands to give an idea of what @code{GDB} is about. You should create
23916 a simple program with debugging information and experiment with the use of
23917 these @code{GDB} commands on the program as you read through the
23918 following section.
23919
23920 @table @code
23921 @item set args @var{arguments}
23922 The @var{arguments} list above is a list of arguments to be passed to
23923 the program on a subsequent run command, just as though the arguments
23924 had been entered on a normal invocation of the program. The @code{set args}
23925 command is not needed if the program does not require arguments.
23926
23927 @item run
23928 The @code{run} command causes execution of the program to start from
23929 the beginning. If the program is already running, that is to say if
23930 you are currently positioned at a breakpoint, then a prompt will ask
23931 for confirmation that you want to abandon the current execution and
23932 restart.
23933
23934 @item breakpoint @var{location}
23935 The breakpoint command sets a breakpoint, that is to say a point at which
23936 execution will halt and @code{GDB} will await further
23937 commands. @var{location} is
23938 either a line number within a file, given in the format @code{file:linenumber},
23939 or it is the name of a subprogram. If you request that a breakpoint be set on
23940 a subprogram that is overloaded, a prompt will ask you to specify on which of
23941 those subprograms you want to breakpoint. You can also
23942 specify that all of them should be breakpointed. If the program is run
23943 and execution encounters the breakpoint, then the program
23944 stops and @code{GDB} signals that the breakpoint was encountered by
23945 printing the line of code before which the program is halted.
23946
23947 @item breakpoint exception @var{name}
23948 A special form of the breakpoint command which breakpoints whenever
23949 exception @var{name} is raised.
23950 If @var{name} is omitted,
23951 then a breakpoint will occur when any exception is raised.
23952
23953 @item print @var{expression}
23954 This will print the value of the given expression. Most simple
23955 Ada expression formats are properly handled by @code{GDB}, so the expression
23956 can contain function calls, variables, operators, and attribute references.
23957
23958 @item continue
23959 Continues execution following a breakpoint, until the next breakpoint or the
23960 termination of the program.
23961
23962 @item step
23963 Executes a single line after a breakpoint. If the next statement
23964 is a subprogram call, execution continues into (the first statement of)
23965 the called subprogram.
23966
23967 @item next
23968 Executes a single line. If this line is a subprogram call, executes and
23969 returns from the call.
23970
23971 @item list
23972 Lists a few lines around the current source location. In practice, it
23973 is usually more convenient to have a separate edit window open with the
23974 relevant source file displayed. Successive applications of this command
23975 print subsequent lines. The command can be given an argument which is a
23976 line number, in which case it displays a few lines around the specified one.
23977
23978 @item backtrace
23979 Displays a backtrace of the call chain. This command is typically
23980 used after a breakpoint has occurred, to examine the sequence of calls that
23981 leads to the current breakpoint. The display includes one line for each
23982 activation record (frame) corresponding to an active subprogram.
23983
23984 @item up
23985 At a breakpoint, @code{GDB} can display the values of variables local
23986 to the current frame. The command @code{up} can be used to
23987 examine the contents of other active frames, by moving the focus up
23988 the stack, that is to say from callee to caller, one frame at a time.
23989
23990 @item down
23991 Moves the focus of @code{GDB} down from the frame currently being
23992 examined to the frame of its callee (the reverse of the previous command),
23993
23994 @item frame @var{n}
23995 Inspect the frame with the given number. The value 0 denotes the frame
23996 of the current breakpoint, that is to say the top of the call stack.
23997
23998 @end table
23999
24000 @noindent
24001 The above list is a very short introduction to the commands that
24002 @code{GDB} provides. Important additional capabilities, including conditional
24003 breakpoints, the ability to execute command sequences on a breakpoint,
24004 the ability to debug at the machine instruction level and many other
24005 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24006 Debugging with GDB}.  Note that most commands can be abbreviated
24007 (for example, c for continue, bt for backtrace).
24008
24009 @node Using Ada Expressions
24010 @section Using Ada Expressions
24011 @cindex Ada expressions
24012
24013 @noindent
24014 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24015 extensions. The philosophy behind the design of this subset is
24016
24017 @itemize @bullet
24018 @item
24019 That @code{GDB} should provide basic literals and access to operations for
24020 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24021 leaving more sophisticated computations to subprograms written into the
24022 program (which therefore may be called from @code{GDB}).
24023
24024 @item
24025 That type safety and strict adherence to Ada language restrictions
24026 are not particularly important to the @code{GDB} user.
24027
24028 @item
24029 That brevity is important to the @code{GDB} user.
24030 @end itemize
24031
24032 @noindent
24033 Thus, for brevity, the debugger acts as if there were
24034 implicit @code{with} and @code{use} clauses in effect for all user-written
24035 packages, thus making it unnecessary to fully qualify most names with
24036 their packages, regardless of context. Where this causes ambiguity,
24037 @code{GDB} asks the user's intent.
24038
24039 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24040 GDB, gdb, Debugging with GDB}.
24041
24042 @node Calling User-Defined Subprograms
24043 @section Calling User-Defined Subprograms
24044
24045 @noindent
24046 An important capability of @code{GDB} is the ability to call user-defined
24047 subprograms while debugging. This is achieved simply by entering
24048 a subprogram call statement in the form:
24049
24050 @smallexample
24051 call subprogram-name (parameters)
24052 @end smallexample
24053
24054 @noindent
24055 The keyword @code{call} can be omitted in the normal case where the
24056 @code{subprogram-name} does not coincide with any of the predefined
24057 @code{GDB} commands.
24058
24059 The effect is to invoke the given subprogram, passing it the
24060 list of parameters that is supplied. The parameters can be expressions and
24061 can include variables from the program being debugged. The
24062 subprogram must be defined
24063 at the library level within your program, and @code{GDB} will call the
24064 subprogram within the environment of your program execution (which
24065 means that the subprogram is free to access or even modify variables
24066 within your program).
24067
24068 The most important use of this facility is in allowing the inclusion of
24069 debugging routines that are tailored to particular data structures
24070 in your program. Such debugging routines can be written to provide a suitably
24071 high-level description of an abstract type, rather than a low-level dump
24072 of its physical layout. After all, the standard
24073 @code{GDB print} command only knows the physical layout of your
24074 types, not their abstract meaning. Debugging routines can provide information
24075 at the desired semantic level and are thus enormously useful.
24076
24077 For example, when debugging GNAT itself, it is crucial to have access to
24078 the contents of the tree nodes used to represent the program internally.
24079 But tree nodes are represented simply by an integer value (which in turn
24080 is an index into a table of nodes).
24081 Using the @code{print} command on a tree node would simply print this integer
24082 value, which is not very useful. But the PN routine (defined in file
24083 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24084 a useful high level representation of the tree node, which includes the
24085 syntactic category of the node, its position in the source, the integers
24086 that denote descendant nodes and parent node, as well as varied
24087 semantic information. To study this example in more detail, you might want to
24088 look at the body of the PN procedure in the stated file.
24089
24090 @node Using the Next Command in a Function
24091 @section Using the Next Command in a Function
24092
24093 @noindent
24094 When you use the @code{next} command in a function, the current source
24095 location will advance to the next statement as usual. A special case
24096 arises in the case of a @code{return} statement.
24097
24098 Part of the code for a return statement is the ``epilog'' of the function.
24099 This is the code that returns to the caller. There is only one copy of
24100 this epilog code, and it is typically associated with the last return
24101 statement in the function if there is more than one return. In some
24102 implementations, this epilog is associated with the first statement
24103 of the function.
24104
24105 The result is that if you use the @code{next} command from a return
24106 statement that is not the last return statement of the function you
24107 may see a strange apparent jump to the last return statement or to
24108 the start of the function. You should simply ignore this odd jump.
24109 The value returned is always that from the first return statement
24110 that was stepped through.
24111
24112 @node Ada Exceptions
24113 @section Breaking on Ada Exceptions
24114 @cindex Exceptions
24115
24116 @noindent
24117 You can set breakpoints that trip when your program raises
24118 selected exceptions.
24119
24120 @table @code
24121 @item break exception
24122 Set a breakpoint that trips whenever (any task in the) program raises
24123 any exception.
24124
24125 @item break exception @var{name}
24126 Set a breakpoint that trips whenever (any task in the) program raises
24127 the exception @var{name}.
24128
24129 @item break exception unhandled
24130 Set a breakpoint that trips whenever (any task in the) program raises an
24131 exception for which there is no handler.
24132
24133 @item info exceptions
24134 @itemx info exceptions @var{regexp}
24135 The @code{info exceptions} command permits the user to examine all defined
24136 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24137 argument, prints out only those exceptions whose name matches @var{regexp}.
24138 @end table
24139
24140 @node Ada Tasks
24141 @section Ada Tasks
24142 @cindex Tasks
24143
24144 @noindent
24145 @code{GDB} allows the following task-related commands:
24146
24147 @table @code
24148 @item info tasks
24149 This command shows a list of current Ada tasks, as in the following example:
24150
24151 @smallexample
24152 @iftex
24153 @leftskip=0cm
24154 @end iftex
24155 (gdb) info tasks
24156   ID       TID P-ID   Thread Pri State                 Name
24157    1   8088000   0   807e000  15 Child Activation Wait main_task
24158    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24159    3   809a800   1   80a4800  15 Child Activation Wait a
24160 *  4   80ae800   3   80b8000  15 Running               c
24161 @end smallexample
24162
24163 @noindent
24164 In this listing, the asterisk before the first task indicates it to be the
24165 currently running task. The first column lists the task ID that is used
24166 to refer to tasks in the following commands.
24167
24168 @item break @var{linespec} task @var{taskid}
24169 @itemx break @var{linespec} task @var{taskid} if @dots{}
24170 @cindex Breakpoints and tasks
24171 These commands are like the @code{break @dots{} thread @dots{}}.
24172 @var{linespec} specifies source lines.
24173
24174 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24175 to specify that you only want @code{GDB} to stop the program when a
24176 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24177 numeric task identifiers assigned by @code{GDB}, shown in the first
24178 column of the @samp{info tasks} display.
24179
24180 If you do not specify @samp{task @var{taskid}} when you set a
24181 breakpoint, the breakpoint applies to @emph{all} tasks of your
24182 program.
24183
24184 You can use the @code{task} qualifier on conditional breakpoints as
24185 well; in this case, place @samp{task @var{taskid}} before the
24186 breakpoint condition (before the @code{if}).
24187
24188 @item task @var{taskno}
24189 @cindex Task switching
24190
24191 This command allows to switch to the task referred by @var{taskno}. In
24192 particular, This allows to browse the backtrace of the specified
24193 task. It is advised to switch back to the original task before
24194 continuing execution otherwise the scheduling of the program may be
24195 perturbed.
24196 @end table
24197
24198 @noindent
24199 For more detailed information on the tasking support,
24200 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24201
24202 @node Debugging Generic Units
24203 @section Debugging Generic Units
24204 @cindex Debugging Generic Units
24205 @cindex Generics
24206
24207 @noindent
24208 GNAT always uses code expansion for generic instantiation. This means that
24209 each time an instantiation occurs, a complete copy of the original code is
24210 made, with appropriate substitutions of formals by actuals.
24211
24212 It is not possible to refer to the original generic entities in
24213 @code{GDB}, but it is always possible to debug a particular instance of
24214 a generic, by using the appropriate expanded names. For example, if we have
24215
24216 @smallexample @c ada
24217 @group
24218 @cartouche
24219 procedure g is
24220
24221    generic package k is
24222       procedure kp (v1 : in out integer);
24223    end k;
24224
24225    package body k is
24226       procedure kp (v1 : in out integer) is
24227       begin
24228          v1 := v1 + 1;
24229       end kp;
24230    end k;
24231
24232    package k1 is new k;
24233    package k2 is new k;
24234
24235    var : integer := 1;
24236
24237 begin
24238    k1.kp (var);
24239    k2.kp (var);
24240    k1.kp (var);
24241    k2.kp (var);
24242 end;
24243 @end cartouche
24244 @end group
24245 @end smallexample
24246
24247 @noindent
24248 Then to break on a call to procedure kp in the k2 instance, simply
24249 use the command:
24250
24251 @smallexample
24252 (gdb) break g.k2.kp
24253 @end smallexample
24254
24255 @noindent
24256 When the breakpoint occurs, you can step through the code of the
24257 instance in the normal manner and examine the values of local variables, as for
24258 other units.
24259
24260 @node GNAT Abnormal Termination or Failure to Terminate
24261 @section GNAT Abnormal Termination or Failure to Terminate
24262 @cindex GNAT Abnormal Termination or Failure to Terminate
24263
24264 @noindent
24265 When presented with programs that contain serious errors in syntax
24266 or semantics,
24267 GNAT may on rare occasions  experience problems in operation, such
24268 as aborting with a
24269 segmentation fault or illegal memory access, raising an internal
24270 exception, terminating abnormally, or failing to terminate at all.
24271 In such cases, you can activate
24272 various features of GNAT that can help you pinpoint the construct in your
24273 program that is the likely source of the problem.
24274
24275 The following strategies are presented in increasing order of
24276 difficulty, corresponding to your experience in using GNAT and your
24277 familiarity with compiler internals.
24278
24279 @enumerate
24280 @item
24281 Run @command{gcc} with the @option{-gnatf}. This first
24282 switch causes all errors on a given line to be reported. In its absence,
24283 only the first error on a line is displayed.
24284
24285 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24286 are encountered, rather than after compilation is terminated. If GNAT
24287 terminates prematurely or goes into an infinite loop, the last error
24288 message displayed may help to pinpoint the culprit.
24289
24290 @item
24291 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24292 mode, @command{gcc} produces ongoing information about the progress of the
24293 compilation and provides the name of each procedure as code is
24294 generated. This switch allows you to find which Ada procedure was being
24295 compiled when it encountered a code generation problem.
24296
24297 @item
24298 @cindex @option{-gnatdc} switch
24299 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24300 switch that does for the front-end what @option{^-v^VERBOSE^} does
24301 for the back end. The system prints the name of each unit,
24302 either a compilation unit or nested unit, as it is being analyzed.
24303 @item
24304 Finally, you can start
24305 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24306 front-end of GNAT, and can be run independently (normally it is just
24307 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24308 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24309 @code{where} command is the first line of attack; the variable
24310 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24311 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24312 which the execution stopped, and @code{input_file name} indicates the name of
24313 the source file.
24314 @end enumerate
24315
24316 @node Naming Conventions for GNAT Source Files
24317 @section Naming Conventions for GNAT Source Files
24318
24319 @noindent
24320 In order to examine the workings of the GNAT system, the following
24321 brief description of its organization may be helpful:
24322
24323 @itemize @bullet
24324 @item
24325 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24326
24327 @item
24328 All files prefixed with @file{^par^PAR^} are components of the parser. The
24329 numbers correspond to chapters of the Ada Reference Manual. For example,
24330 parsing of select statements can be found in @file{par-ch9.adb}.
24331
24332 @item
24333 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24334 numbers correspond to chapters of the Ada standard. For example, all
24335 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24336 addition, some features of the language require sufficient special processing
24337 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24338 dynamic dispatching, etc.
24339
24340 @item
24341 All files prefixed with @file{^exp^EXP^} perform normalization and
24342 expansion of the intermediate representation (abstract syntax tree, or AST).
24343 these files use the same numbering scheme as the parser and semantics files.
24344 For example, the construction of record initialization procedures is done in
24345 @file{exp_ch3.adb}.
24346
24347 @item
24348 The files prefixed with @file{^bind^BIND^} implement the binder, which
24349 verifies the consistency of the compilation, determines an order of
24350 elaboration, and generates the bind file.
24351
24352 @item
24353 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24354 data structures used by the front-end.
24355
24356 @item
24357 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24358 the abstract syntax tree as produced by the parser.
24359
24360 @item
24361 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24362 all entities, computed during semantic analysis.
24363
24364 @item
24365 Library management issues are dealt with in files with prefix
24366 @file{^lib^LIB^}.
24367
24368 @item
24369 @findex Ada
24370 @cindex Annex A
24371 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24372 defined in Annex A.
24373
24374 @item
24375 @findex Interfaces
24376 @cindex Annex B
24377 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24378 defined in Annex B.
24379
24380 @item
24381 @findex System
24382 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24383 both language-defined children and GNAT run-time routines.
24384
24385 @item
24386 @findex GNAT
24387 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24388 general-purpose packages, fully documented in their specs. All
24389 the other @file{.c} files are modifications of common @command{gcc} files.
24390 @end itemize
24391
24392 @node Getting Internal Debugging Information
24393 @section Getting Internal Debugging Information
24394
24395 @noindent
24396 Most compilers have internal debugging switches and modes. GNAT
24397 does also, except GNAT internal debugging switches and modes are not
24398 secret. A summary and full description of all the compiler and binder
24399 debug flags are in the file @file{debug.adb}. You must obtain the
24400 sources of the compiler to see the full detailed effects of these flags.
24401
24402 The switches that print the source of the program (reconstructed from
24403 the internal tree) are of general interest for user programs, as are the
24404 options to print
24405 the full internal tree, and the entity table (the symbol table
24406 information). The reconstructed source provides a readable version of the
24407 program after the front-end has completed analysis and  expansion,
24408 and is useful when studying the performance of specific constructs.
24409 For example, constraint checks are indicated, complex aggregates
24410 are replaced with loops and assignments, and tasking primitives
24411 are replaced with run-time calls.
24412
24413 @node Stack Traceback
24414 @section Stack Traceback
24415 @cindex traceback
24416 @cindex stack traceback
24417 @cindex stack unwinding
24418
24419 @noindent
24420 Traceback is a mechanism to display the sequence of subprogram calls that
24421 leads to a specified execution point in a program. Often (but not always)
24422 the execution point is an instruction at which an exception has been raised.
24423 This mechanism is also known as @i{stack unwinding} because it obtains
24424 its information by scanning the run-time stack and recovering the activation
24425 records of all active subprograms. Stack unwinding is one of the most
24426 important tools for program debugging.
24427
24428 The first entry stored in traceback corresponds to the deepest calling level,
24429 that is to say the subprogram currently executing the instruction
24430 from which we want to obtain the traceback.
24431
24432 Note that there is no runtime performance penalty when stack traceback
24433 is enabled, and no exception is raised during program execution.
24434
24435 @menu
24436 * Non-Symbolic Traceback::
24437 * Symbolic Traceback::
24438 @end menu
24439
24440 @node Non-Symbolic Traceback
24441 @subsection Non-Symbolic Traceback
24442 @cindex traceback, non-symbolic
24443
24444 @noindent
24445 Note: this feature is not supported on all platforms. See
24446 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24447 platforms.
24448
24449 @menu
24450 * Tracebacks From an Unhandled Exception::
24451 * Tracebacks From Exception Occurrences (non-symbolic)::
24452 * Tracebacks From Anywhere in a Program (non-symbolic)::
24453 @end menu
24454
24455 @node Tracebacks From an Unhandled Exception
24456 @subsubsection Tracebacks From an Unhandled Exception
24457
24458 @noindent
24459 A runtime non-symbolic traceback is a list of addresses of call instructions.
24460 To enable this feature you must use the @option{-E}
24461 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24462 of exception information. You can retrieve this information using the
24463 @code{addr2line} tool.
24464
24465 Here is a simple example:
24466
24467 @smallexample @c ada
24468 @cartouche
24469 procedure STB is
24470
24471    procedure P1 is
24472    begin
24473       raise Constraint_Error;
24474    end P1;
24475
24476    procedure P2 is
24477    begin
24478       P1;
24479    end P2;
24480
24481 begin
24482    P2;
24483 end STB;
24484 @end cartouche
24485 @end smallexample
24486
24487 @smallexample
24488 $ gnatmake stb -bargs -E
24489 $ stb
24490
24491 Execution terminated by unhandled exception
24492 Exception name: CONSTRAINT_ERROR
24493 Message: stb.adb:5
24494 Call stack traceback locations:
24495 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24496 @end smallexample
24497
24498 @noindent
24499 As we see the traceback lists a sequence of addresses for the unhandled
24500 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24501 guess that this exception come from procedure P1. To translate these
24502 addresses into the source lines where the calls appear, the
24503 @code{addr2line} tool, described below, is invaluable. The use of this tool
24504 requires the program to be compiled with debug information.
24505
24506 @smallexample
24507 $ gnatmake -g stb -bargs -E
24508 $ stb
24509
24510 Execution terminated by unhandled exception
24511 Exception name: CONSTRAINT_ERROR
24512 Message: stb.adb:5
24513 Call stack traceback locations:
24514 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24515
24516 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24517    0x4011f1 0x77e892a4
24518
24519 00401373 at d:/stb/stb.adb:5
24520 0040138B at d:/stb/stb.adb:10
24521 0040139C at d:/stb/stb.adb:14
24522 00401335 at d:/stb/b~stb.adb:104
24523 004011C4 at /build/@dots{}/crt1.c:200
24524 004011F1 at /build/@dots{}/crt1.c:222
24525 77E892A4 in ?? at ??:0
24526 @end smallexample
24527
24528 @noindent
24529 The @code{addr2line} tool has several other useful options:
24530
24531 @table @code
24532 @item --functions
24533 to get the function name corresponding to any location
24534
24535 @item --demangle=gnat
24536 to use the gnat decoding mode for the function names. Note that
24537 for binutils version 2.9.x the option is simply @option{--demangle}.
24538 @end table
24539
24540 @smallexample
24541 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24542    0x40139c 0x401335 0x4011c4 0x4011f1
24543
24544 00401373 in stb.p1 at d:/stb/stb.adb:5
24545 0040138B in stb.p2 at d:/stb/stb.adb:10
24546 0040139C in stb at d:/stb/stb.adb:14
24547 00401335 in main at d:/stb/b~stb.adb:104
24548 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24549 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24550 @end smallexample
24551
24552 @noindent
24553 From this traceback we can see that the exception was raised in
24554 @file{stb.adb} at line 5, which was reached from a procedure call in
24555 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24556 which contains the call to the main program.
24557 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24558 and the output will vary from platform to platform.
24559
24560 It is also possible to use @code{GDB} with these traceback addresses to debug
24561 the program. For example, we can break at a given code location, as reported
24562 in the stack traceback:
24563
24564 @smallexample
24565 $ gdb -nw stb
24566 @ifclear vms
24567 @noindent
24568 Furthermore, this feature is not implemented inside Windows DLL. Only
24569 the non-symbolic traceback is reported in this case.
24570 @end ifclear
24571
24572 (gdb) break *0x401373
24573 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24574 @end smallexample
24575
24576 @noindent
24577 It is important to note that the stack traceback addresses
24578 do not change when debug information is included. This is particularly useful
24579 because it makes it possible to release software without debug information (to
24580 minimize object size), get a field report that includes a stack traceback
24581 whenever an internal bug occurs, and then be able to retrieve the sequence
24582 of calls with the same program compiled with debug information.
24583
24584 @node Tracebacks From Exception Occurrences (non-symbolic)
24585 @subsubsection Tracebacks From Exception Occurrences
24586
24587 @noindent
24588 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24589 The stack traceback is attached to the exception information string, and can
24590 be retrieved in an exception handler within the Ada program, by means of the
24591 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24592
24593 @smallexample @c ada
24594 with Ada.Text_IO;
24595 with Ada.Exceptions;
24596
24597 procedure STB is
24598
24599    use Ada;
24600    use Ada.Exceptions;
24601
24602    procedure P1 is
24603       K : Positive := 1;
24604    begin
24605       K := K - 1;
24606    exception
24607       when E : others =>
24608          Text_IO.Put_Line (Exception_Information (E));
24609    end P1;
24610
24611    procedure P2 is
24612    begin
24613       P1;
24614    end P2;
24615
24616 begin
24617    P2;
24618 end STB;
24619 @end smallexample
24620
24621 @noindent
24622 This program will output:
24623
24624 @smallexample
24625 $ stb
24626
24627 Exception name: CONSTRAINT_ERROR
24628 Message: stb.adb:12
24629 Call stack traceback locations:
24630 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24631 @end smallexample
24632
24633 @node Tracebacks From Anywhere in a Program (non-symbolic)
24634 @subsubsection Tracebacks From Anywhere in a Program
24635
24636 @noindent
24637 It is also possible to retrieve a stack traceback from anywhere in a
24638 program. For this you need to
24639 use the @code{GNAT.Traceback} API. This package includes a procedure called
24640 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24641 display procedures described below. It is not necessary to use the
24642 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24643 is invoked explicitly.
24644
24645 @noindent
24646 In the following example we compute a traceback at a specific location in
24647 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24648 convert addresses to strings:
24649
24650 @smallexample @c ada
24651 with Ada.Text_IO;
24652 with GNAT.Traceback;
24653 with GNAT.Debug_Utilities;
24654
24655 procedure STB is
24656
24657    use Ada;
24658    use GNAT;
24659    use GNAT.Traceback;
24660
24661    procedure P1 is
24662       TB  : Tracebacks_Array (1 .. 10);
24663       --  We are asking for a maximum of 10 stack frames.
24664       Len : Natural;
24665       --  Len will receive the actual number of stack frames returned.
24666    begin
24667       Call_Chain (TB, Len);
24668
24669       Text_IO.Put ("In STB.P1 : ");
24670
24671       for K in 1 .. Len loop
24672          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24673          Text_IO.Put (' ');
24674       end loop;
24675
24676       Text_IO.New_Line;
24677    end P1;
24678
24679    procedure P2 is
24680    begin
24681       P1;
24682    end P2;
24683
24684 begin
24685    P2;
24686 end STB;
24687 @end smallexample
24688
24689 @smallexample
24690 $ gnatmake -g stb
24691 $ stb
24692
24693 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24694 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24695 @end smallexample
24696
24697 @noindent
24698 You can then get further information by invoking the @code{addr2line}
24699 tool as described earlier (note that the hexadecimal addresses
24700 need to be specified in C format, with a leading ``0x'').
24701
24702 @node Symbolic Traceback
24703 @subsection Symbolic Traceback
24704 @cindex traceback, symbolic
24705
24706 @noindent
24707 A symbolic traceback is a stack traceback in which procedure names are
24708 associated with each code location.
24709
24710 @noindent
24711 Note that this feature is not supported on all platforms. See
24712 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24713 list of currently supported platforms.
24714
24715 @noindent
24716 Note that the symbolic traceback requires that the program be compiled
24717 with debug information. If it is not compiled with debug information
24718 only the non-symbolic information will be valid.
24719
24720 @menu
24721 * Tracebacks From Exception Occurrences (symbolic)::
24722 * Tracebacks From Anywhere in a Program (symbolic)::
24723 @end menu
24724
24725 @node Tracebacks From Exception Occurrences (symbolic)
24726 @subsubsection Tracebacks From Exception Occurrences
24727
24728 @smallexample @c ada
24729 with Ada.Text_IO;
24730 with GNAT.Traceback.Symbolic;
24731
24732 procedure STB is
24733
24734    procedure P1 is
24735    begin
24736       raise Constraint_Error;
24737    end P1;
24738
24739    procedure P2 is
24740    begin
24741       P1;
24742    end P2;
24743
24744    procedure P3 is
24745    begin
24746       P2;
24747    end P3;
24748
24749 begin
24750    P3;
24751 exception
24752    when E : others =>
24753       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24754 end STB;
24755 @end smallexample
24756
24757 @smallexample
24758 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24759 $ stb
24760
24761 0040149F in stb.p1 at stb.adb:8
24762 004014B7 in stb.p2 at stb.adb:13
24763 004014CF in stb.p3 at stb.adb:18
24764 004015DD in ada.stb at stb.adb:22
24765 00401461 in main at b~stb.adb:168
24766 004011C4 in __mingw_CRTStartup at crt1.c:200
24767 004011F1 in mainCRTStartup at crt1.c:222
24768 77E892A4 in ?? at ??:0
24769 @end smallexample
24770
24771 @noindent
24772 In the above example the ``.\'' syntax in the @command{gnatmake} command
24773 is currently required by @command{addr2line} for files that are in
24774 the current working directory.
24775 Moreover, the exact sequence of linker options may vary from platform
24776 to platform.
24777 The above @option{-largs} section is for Windows platforms. By contrast,
24778 under Unix there is no need for the @option{-largs} section.
24779 Differences across platforms are due to details of linker implementation.
24780
24781 @node Tracebacks From Anywhere in a Program (symbolic)
24782 @subsubsection Tracebacks From Anywhere in a Program
24783
24784 @noindent
24785 It is possible to get a symbolic stack traceback
24786 from anywhere in a program, just as for non-symbolic tracebacks.
24787 The first step is to obtain a non-symbolic
24788 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24789 information. Here is an example:
24790
24791 @smallexample @c ada
24792 with Ada.Text_IO;
24793 with GNAT.Traceback;
24794 with GNAT.Traceback.Symbolic;
24795
24796 procedure STB is
24797
24798    use Ada;
24799    use GNAT.Traceback;
24800    use GNAT.Traceback.Symbolic;
24801
24802    procedure P1 is
24803       TB  : Tracebacks_Array (1 .. 10);
24804       --  We are asking for a maximum of 10 stack frames.
24805       Len : Natural;
24806       --  Len will receive the actual number of stack frames returned.
24807    begin
24808       Call_Chain (TB, Len);
24809       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24810    end P1;
24811
24812    procedure P2 is
24813    begin
24814       P1;
24815    end P2;
24816
24817 begin
24818    P2;
24819 end STB;
24820 @end smallexample
24821
24822 @c ******************************
24823 @ifset vms
24824 @node Compatibility with HP Ada
24825 @chapter Compatibility with HP Ada
24826 @cindex Compatibility
24827
24828 @noindent
24829 @cindex DEC Ada
24830 @cindex HP Ada
24831 @cindex Compatibility between GNAT and HP Ada
24832 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24833 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24834 GNAT is highly compatible
24835 with HP Ada, and it should generally be straightforward to port code
24836 from the HP Ada environment to GNAT. However, there are a few language
24837 and implementation differences of which the user must be aware. These
24838 differences are discussed in this chapter. In
24839 addition, the operating environment and command structure for the
24840 compiler are different, and these differences are also discussed.
24841
24842 For further details on these and other compatibility issues,
24843 see Appendix E of the HP publication
24844 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24845
24846 Except where otherwise indicated, the description of GNAT for OpenVMS
24847 applies to both the Alpha and I64 platforms.
24848
24849 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24850 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24851
24852 The discussion in this chapter addresses specifically the implementation
24853 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24854 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24855 GNAT always follows the Alpha implementation.
24856
24857 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24858 attributes are recognized, although only a subset of them can sensibly
24859 be implemented.  The description of pragmas in
24860 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24861 indicates whether or not they are applicable to non-VMS systems.
24862
24863 @menu
24864 * Ada Language Compatibility::
24865 * Differences in the Definition of Package System::
24866 * Language-Related Features::
24867 * The Package STANDARD::
24868 * The Package SYSTEM::
24869 * Tasking and Task-Related Features::
24870 * Pragmas and Pragma-Related Features::
24871 * Library of Predefined Units::
24872 * Bindings::
24873 * Main Program Definition::
24874 * Implementation-Defined Attributes::
24875 * Compiler and Run-Time Interfacing::
24876 * Program Compilation and Library Management::
24877 * Input-Output::
24878 * Implementation Limits::
24879 * Tools and Utilities::
24880 @end menu
24881
24882 @node Ada Language Compatibility
24883 @section Ada Language Compatibility
24884
24885 @noindent
24886 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24887 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24888 with Ada 83, and therefore Ada 83 programs will compile
24889 and run under GNAT with
24890 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24891 provides details on specific incompatibilities.
24892
24893 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24894 as well as the pragma @code{ADA_83}, to force the compiler to
24895 operate in Ada 83 mode. This mode does not guarantee complete
24896 conformance to Ada 83, but in practice is sufficient to
24897 eliminate most sources of incompatibilities.
24898 In particular, it eliminates the recognition of the
24899 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24900 in Ada 83 programs is legal, and handles the cases of packages
24901 with optional bodies, and generics that instantiate unconstrained
24902 types without the use of @code{(<>)}.
24903
24904 @node Differences in the Definition of Package System
24905 @section Differences in the Definition of Package @code{System}
24906
24907 @noindent
24908 An Ada compiler is allowed to add
24909 implementation-dependent declarations to package @code{System}.
24910 In normal mode,
24911 GNAT does not take advantage of this permission, and the version of
24912 @code{System} provided by GNAT exactly matches that defined in the Ada
24913 Reference Manual.
24914
24915 However, HP Ada adds an extensive set of declarations to package
24916 @code{System},
24917 as fully documented in the HP Ada manuals. To minimize changes required
24918 for programs that make use of these extensions, GNAT provides the pragma
24919 @code{Extend_System} for extending the definition of package System. By using:
24920 @cindex pragma @code{Extend_System}
24921 @cindex @code{Extend_System} pragma
24922
24923 @smallexample @c ada
24924 @group
24925 @cartouche
24926 pragma Extend_System (Aux_DEC);
24927 @end cartouche
24928 @end group
24929 @end smallexample
24930
24931 @noindent
24932 the set of definitions in @code{System} is extended to include those in
24933 package @code{System.Aux_DEC}.
24934 @cindex @code{System.Aux_DEC} package
24935 @cindex @code{Aux_DEC} package (child of @code{System})
24936 These definitions are incorporated directly into package @code{System},
24937 as though they had been declared there. For a
24938 list of the declarations added, see the spec of this package,
24939 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24940 @cindex @file{s-auxdec.ads} file
24941 The pragma @code{Extend_System} is a configuration pragma, which means that
24942 it can be placed in the file @file{gnat.adc}, so that it will automatically
24943 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24944 for further details.
24945
24946 An alternative approach that avoids the use of the non-standard
24947 @code{Extend_System} pragma is to add a context clause to the unit that
24948 references these facilities:
24949
24950 @smallexample @c ada
24951 @cartouche
24952 with System.Aux_DEC;
24953 use  System.Aux_DEC;
24954 @end cartouche
24955 @end smallexample
24956
24957 @noindent
24958 The effect is not quite semantically identical to incorporating
24959 the declarations directly into package @code{System},
24960 but most programs will not notice a difference
24961 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24962 to reference the entities directly in package @code{System}.
24963 For units containing such references,
24964 the prefixes must either be removed, or the pragma @code{Extend_System}
24965 must be used.
24966
24967 @node Language-Related Features
24968 @section Language-Related Features
24969
24970 @noindent
24971 The following sections highlight differences in types,
24972 representations of types, operations, alignment, and
24973 related topics.
24974
24975 @menu
24976 * Integer Types and Representations::
24977 * Floating-Point Types and Representations::
24978 * Pragmas Float_Representation and Long_Float::
24979 * Fixed-Point Types and Representations::
24980 * Record and Array Component Alignment::
24981 * Address Clauses::
24982 * Other Representation Clauses::
24983 @end menu
24984
24985 @node Integer Types and Representations
24986 @subsection Integer Types and Representations
24987
24988 @noindent
24989 The set of predefined integer types is identical in HP Ada and GNAT.
24990 Furthermore the representation of these integer types is also identical,
24991 including the capability of size clauses forcing biased representation.
24992
24993 In addition,
24994 HP Ada for OpenVMS Alpha systems has defined the
24995 following additional integer types in package @code{System}:
24996
24997 @itemize @bullet
24998
24999 @item
25000 @code{INTEGER_8}
25001
25002 @item
25003 @code{INTEGER_16}
25004
25005 @item
25006 @code{INTEGER_32}
25007
25008 @item
25009 @code{INTEGER_64}
25010
25011 @item
25012 @code{LARGEST_INTEGER}
25013 @end itemize
25014
25015 @noindent
25016 In GNAT, the first four of these types may be obtained from the
25017 standard Ada package @code{Interfaces}.
25018 Alternatively, by use of the pragma @code{Extend_System}, identical
25019 declarations can be referenced directly in package @code{System}.
25020 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25021
25022 @node Floating-Point Types and Representations
25023 @subsection Floating-Point Types and Representations
25024 @cindex Floating-Point types
25025
25026 @noindent
25027 The set of predefined floating-point types is identical in HP Ada and GNAT.
25028 Furthermore the representation of these floating-point
25029 types is also identical. One important difference is that the default
25030 representation for HP Ada is @code{VAX_Float}, but the default representation
25031 for GNAT is IEEE.
25032
25033 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25034 pragma @code{Float_Representation} as described in the HP Ada
25035 documentation.
25036 For example, the declarations:
25037
25038 @smallexample @c ada
25039 @cartouche
25040 type F_Float is digits 6;
25041 pragma Float_Representation (VAX_Float, F_Float);
25042 @end cartouche
25043 @end smallexample
25044
25045 @noindent
25046 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25047 format.
25048 This set of declarations actually appears in @code{System.Aux_DEC},
25049 which contains
25050 the full set of additional floating-point declarations provided in
25051 the HP Ada version of package @code{System}.
25052 This and similar declarations may be accessed in a user program
25053 by using pragma @code{Extend_System}. The use of this
25054 pragma, and the related pragma @code{Long_Float} is described in further
25055 detail in the following section.
25056
25057 @node Pragmas Float_Representation and Long_Float
25058 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25059
25060 @noindent
25061 HP Ada provides the pragma @code{Float_Representation}, which
25062 acts as a program library switch to allow control over
25063 the internal representation chosen for the predefined
25064 floating-point types declared in the package @code{Standard}.
25065 The format of this pragma is as follows:
25066
25067 @smallexample @c ada
25068 @cartouche
25069 pragma Float_Representation(VAX_Float | IEEE_Float);
25070 @end cartouche
25071 @end smallexample
25072
25073 @noindent
25074 This pragma controls the representation of floating-point
25075 types as follows:
25076
25077 @itemize @bullet
25078 @item
25079 @code{VAX_Float} specifies that floating-point
25080 types are represented by default with the VAX system hardware types
25081 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25082 Note that the @code{H-floating}
25083 type was available only on VAX systems, and is not available
25084 in either HP Ada or GNAT.
25085
25086 @item
25087 @code{IEEE_Float} specifies that floating-point
25088 types are represented by default with the IEEE single and
25089 double floating-point types.
25090 @end itemize
25091
25092 @noindent
25093 GNAT provides an identical implementation of the pragma
25094 @code{Float_Representation}, except that it functions as a
25095 configuration pragma. Note that the
25096 notion of configuration pragma corresponds closely to the
25097 HP Ada notion of a program library switch.
25098
25099 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25100 which is different
25101 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25102 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25103 advisable to change the format of numbers passed to standard library
25104 routines, and if necessary explicit type conversions may be needed.
25105
25106 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25107 efficient, and (given that it conforms to an international standard)
25108 potentially more portable.
25109 The situation in which @code{VAX_Float} may be useful is in interfacing
25110 to existing code and data that expect the use of @code{VAX_Float}.
25111 In such a situation use the predefined @code{VAX_Float}
25112 types in package @code{System}, as extended by
25113 @code{Extend_System}. For example, use @code{System.F_Float}
25114 to specify the 32-bit @code{F-Float} format.
25115
25116 @noindent
25117 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25118 to allow control over the internal representation chosen
25119 for the predefined type @code{Long_Float} and for floating-point
25120 type declarations with digits specified in the range 7 .. 15.
25121 The format of this pragma is as follows:
25122
25123 @smallexample @c ada
25124 @cartouche
25125 pragma Long_Float (D_FLOAT | G_FLOAT);
25126 @end cartouche
25127 @end smallexample
25128
25129 @node Fixed-Point Types and Representations
25130 @subsection Fixed-Point Types and Representations
25131
25132 @noindent
25133 On HP Ada for OpenVMS Alpha systems, rounding is
25134 away from zero for both positive and negative numbers.
25135 Therefore, @code{+0.5} rounds to @code{1},
25136 and @code{-0.5} rounds to @code{-1}.
25137
25138 On GNAT the results of operations
25139 on fixed-point types are in accordance with the Ada
25140 rules. In particular, results of operations on decimal
25141 fixed-point types are truncated.
25142
25143 @node Record and Array Component Alignment
25144 @subsection Record and Array Component Alignment
25145
25146 @noindent
25147 On HP Ada for OpenVMS Alpha, all non-composite components
25148 are aligned on natural boundaries. For example, 1-byte
25149 components are aligned on byte boundaries, 2-byte
25150 components on 2-byte boundaries, 4-byte components on 4-byte
25151 byte boundaries, and so on. The OpenVMS Alpha hardware
25152 runs more efficiently with naturally aligned data.
25153
25154 On GNAT, alignment rules are compatible
25155 with HP Ada for OpenVMS Alpha.
25156
25157 @node Address Clauses
25158 @subsection Address Clauses
25159
25160 @noindent
25161 In HP Ada and GNAT, address clauses are supported for
25162 objects and imported subprograms.
25163 The predefined type @code{System.Address} is a private type
25164 in both compilers on Alpha OpenVMS, with the same representation
25165 (it is simply a machine pointer). Addition, subtraction, and comparison
25166 operations are available in the standard Ada package
25167 @code{System.Storage_Elements}, or in package @code{System}
25168 if it is extended to include @code{System.Aux_DEC} using a
25169 pragma @code{Extend_System} as previously described.
25170
25171 Note that code that @code{with}'s both this extended package @code{System}
25172 and the package @code{System.Storage_Elements} should not @code{use}
25173 both packages, or ambiguities will result. In general it is better
25174 not to mix these two sets of facilities. The Ada package was
25175 designed specifically to provide the kind of features that HP Ada
25176 adds directly to package @code{System}.
25177
25178 The type @code{System.Address} is a 64-bit integer type in GNAT for
25179 I64 OpenVMS.  For more information,
25180 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25181
25182 GNAT is compatible with HP Ada in its handling of address
25183 clauses, except for some limitations in
25184 the form of address clauses for composite objects with
25185 initialization. Such address clauses are easily replaced
25186 by the use of an explicitly-defined constant as described
25187 in the Ada Reference Manual (13.1(22)). For example, the sequence
25188 of declarations:
25189
25190 @smallexample @c ada
25191 @cartouche
25192 X, Y : Integer := Init_Func;
25193 Q : String (X .. Y) := "abc";
25194 @dots{}
25195 for Q'Address use Compute_Address;
25196 @end cartouche
25197 @end smallexample
25198
25199 @noindent
25200 will be rejected by GNAT, since the address cannot be computed at the time
25201 that @code{Q} is declared. To achieve the intended effect, write instead:
25202
25203 @smallexample @c ada
25204 @group
25205 @cartouche
25206 X, Y : Integer := Init_Func;
25207 Q_Address : constant Address := Compute_Address;
25208 Q : String (X .. Y) := "abc";
25209 @dots{}
25210 for Q'Address use Q_Address;
25211 @end cartouche
25212 @end group
25213 @end smallexample
25214
25215 @noindent
25216 which will be accepted by GNAT (and other Ada compilers), and is also
25217 compatible with Ada 83. A fuller description of the restrictions
25218 on address specifications is found in @ref{Top, GNAT Reference Manual,
25219 About This Guide, gnat_rm, GNAT Reference Manual}.
25220
25221 @node Other Representation Clauses
25222 @subsection Other Representation Clauses
25223
25224 @noindent
25225 GNAT implements in a compatible manner all the representation
25226 clauses supported by HP Ada. In addition, GNAT
25227 implements the representation clause forms that were introduced in Ada 95,
25228 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25229
25230 @node The Package STANDARD
25231 @section The Package @code{STANDARD}
25232
25233 @noindent
25234 The package @code{STANDARD}, as implemented by HP Ada, is fully
25235 described in the @cite{Ada Reference Manual} and in the
25236 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25237 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25238
25239 In addition, HP Ada supports the Latin-1 character set in
25240 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25241 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25242 the type @code{WIDE_CHARACTER}.
25243
25244 The floating-point types supported by GNAT are those
25245 supported by HP Ada, but the defaults are different, and are controlled by
25246 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25247
25248 @node The Package SYSTEM
25249 @section The Package @code{SYSTEM}
25250
25251 @noindent
25252 HP Ada provides a specific version of the package
25253 @code{SYSTEM} for each platform on which the language is implemented.
25254 For the complete spec of the package @code{SYSTEM}, see
25255 Appendix F of the @cite{HP Ada Language Reference Manual}.
25256
25257 On HP Ada, the package @code{SYSTEM} includes the following conversion
25258 functions:
25259 @itemize @bullet
25260 @item @code{TO_ADDRESS(INTEGER)}
25261
25262 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25263
25264 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25265
25266 @item @code{TO_INTEGER(ADDRESS)}
25267
25268 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25269
25270 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25271 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25272 @end itemize
25273
25274 @noindent
25275 By default, GNAT supplies a version of @code{SYSTEM} that matches
25276 the definition given in the @cite{Ada Reference Manual}.
25277 This
25278 is a subset of the HP system definitions, which is as
25279 close as possible to the original definitions. The only difference
25280 is that the definition of @code{SYSTEM_NAME} is different:
25281
25282 @smallexample @c ada
25283 @cartouche
25284 type Name is (SYSTEM_NAME_GNAT);
25285 System_Name : constant Name := SYSTEM_NAME_GNAT;
25286 @end cartouche
25287 @end smallexample
25288
25289 @noindent
25290 Also, GNAT adds the Ada declarations for
25291 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25292
25293 However, the use of the following pragma causes GNAT
25294 to extend the definition of package @code{SYSTEM} so that it
25295 encompasses the full set of HP-specific extensions,
25296 including the functions listed above:
25297
25298 @smallexample @c ada
25299 @cartouche
25300 pragma Extend_System (Aux_DEC);
25301 @end cartouche
25302 @end smallexample
25303
25304 @noindent
25305 The pragma @code{Extend_System} is a configuration pragma that
25306 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25307 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
25308
25309 HP Ada does not allow the recompilation of the package
25310 @code{SYSTEM}. Instead HP Ada provides several pragmas
25311 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25312 to modify values in the package @code{SYSTEM}.
25313 On OpenVMS Alpha systems, the pragma
25314 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25315 its single argument.
25316
25317 GNAT does permit the recompilation of package @code{SYSTEM} using
25318 the special switch @option{-gnatg}, and this switch can be used if
25319 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25320 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25321 or @code{MEMORY_SIZE} by any other means.
25322
25323 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25324 enumeration literal @code{SYSTEM_NAME_GNAT}.
25325
25326 The definitions provided by the use of
25327
25328 @smallexample @c ada
25329 pragma Extend_System (AUX_Dec);
25330 @end smallexample
25331
25332 @noindent
25333 are virtually identical to those provided by the HP Ada 83 package
25334 @code{SYSTEM}. One important difference is that the name of the
25335 @code{TO_ADDRESS}
25336 function for type @code{UNSIGNED_LONGWORD} is changed to
25337 @code{TO_ADDRESS_LONG}.
25338 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
25339 discussion of why this change was necessary.
25340
25341 @noindent
25342 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25343 is in fact
25344 an extension to Ada 83 not strictly compatible with the reference manual.
25345 GNAT, in order to be exactly compatible with the standard,
25346 does not provide this capability. In HP Ada 83, the
25347 point of this definition is to deal with a call like:
25348
25349 @smallexample @c ada
25350 TO_ADDRESS (16#12777#);
25351 @end smallexample
25352
25353 @noindent
25354 Normally, according to Ada 83 semantics, one would expect this to be
25355 ambiguous, since it matches both the @code{INTEGER} and
25356 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25357 However, in HP Ada 83, there is no ambiguity, since the
25358 definition using @i{universal_integer} takes precedence.
25359
25360 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25361 it is
25362 not possible to be 100% compatible. Since there are many programs using
25363 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25364 GNAT was
25365 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25366 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25367
25368 @smallexample @c ada
25369 function To_Address (X : Integer) return Address;
25370 pragma Pure_Function (To_Address);
25371
25372 function To_Address_Long (X : Unsigned_Longword) return Address;
25373 pragma Pure_Function (To_Address_Long);
25374 @end smallexample
25375
25376 @noindent
25377 This means that programs using @code{TO_ADDRESS} for
25378 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25379
25380 @node Tasking and Task-Related Features
25381 @section Tasking and Task-Related Features
25382
25383 @noindent
25384 This section compares the treatment of tasking in GNAT
25385 and in HP Ada for OpenVMS Alpha.
25386 The GNAT description applies to both Alpha and I64 OpenVMS.
25387 For detailed information on tasking in
25388 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25389 relevant run-time reference manual.
25390
25391 @menu
25392 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25393 * Assigning Task IDs::
25394 * Task IDs and Delays::
25395 * Task-Related Pragmas::
25396 * Scheduling and Task Priority::
25397 * The Task Stack::
25398 * External Interrupts::
25399 @end menu
25400
25401 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25402 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25403
25404 @noindent
25405 On OpenVMS Alpha systems, each Ada task (except a passive
25406 task) is implemented as a single stream of execution
25407 that is created and managed by the kernel. On these
25408 systems, HP Ada tasking support is based on DECthreads,
25409 an implementation of the POSIX standard for threads.
25410
25411 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25412 code that calls DECthreads routines can be used together.
25413 The interaction between Ada tasks and DECthreads routines
25414 can have some benefits. For example when on OpenVMS Alpha,
25415 HP Ada can call C code that is already threaded.
25416
25417 GNAT uses the facilities of DECthreads,
25418 and Ada tasks are mapped to threads.
25419
25420 @node Assigning Task IDs
25421 @subsection Assigning Task IDs
25422
25423 @noindent
25424 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25425 the environment task that executes the main program. On
25426 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25427 that have been created but are not yet activated.
25428
25429 On OpenVMS Alpha systems, task IDs are assigned at
25430 activation. On GNAT systems, task IDs are also assigned at
25431 task creation but do not have the same form or values as
25432 task ID values in HP Ada. There is no null task, and the
25433 environment task does not have a specific task ID value.
25434
25435 @node Task IDs and Delays
25436 @subsection Task IDs and Delays
25437
25438 @noindent
25439 On OpenVMS Alpha systems, tasking delays are implemented
25440 using Timer System Services. The Task ID is used for the
25441 identification of the timer request (the @code{REQIDT} parameter).
25442 If Timers are used in the application take care not to use
25443 @code{0} for the identification, because cancelling such a timer
25444 will cancel all timers and may lead to unpredictable results.
25445
25446 @node Task-Related Pragmas
25447 @subsection Task-Related Pragmas
25448
25449 @noindent
25450 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25451 specification of the size of the guard area for a task
25452 stack. (The guard area forms an area of memory that has no
25453 read or write access and thus helps in the detection of
25454 stack overflow.) On OpenVMS Alpha systems, if the pragma
25455 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25456 area is created. In the absence of a pragma @code{TASK_STORAGE},
25457 a default guard area is created.
25458
25459 GNAT supplies the following task-related pragmas:
25460
25461 @itemize @bullet
25462 @item  @code{TASK_INFO}
25463
25464 This pragma appears within a task definition and
25465 applies to the task in which it appears. The argument
25466 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25467
25468 @item  @code{TASK_STORAGE}
25469
25470 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25471 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25472 @code{SUPPRESS}, and @code{VOLATILE}.
25473 @end itemize
25474 @node Scheduling and Task Priority
25475 @subsection Scheduling and Task Priority
25476
25477 @noindent
25478 HP Ada implements the Ada language requirement that
25479 when two tasks are eligible for execution and they have
25480 different priorities, the lower priority task does not
25481 execute while the higher priority task is waiting. The HP
25482 Ada Run-Time Library keeps a task running until either the
25483 task is suspended or a higher priority task becomes ready.
25484
25485 On OpenVMS Alpha systems, the default strategy is round-
25486 robin with preemption. Tasks of equal priority take turns
25487 at the processor. A task is run for a certain period of
25488 time and then placed at the tail of the ready queue for
25489 its priority level.
25490
25491 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25492 which can be used to enable or disable round-robin
25493 scheduling of tasks with the same priority.
25494 See the relevant HP Ada run-time reference manual for
25495 information on using the pragmas to control HP Ada task
25496 scheduling.
25497
25498 GNAT follows the scheduling rules of Annex D (Real-Time
25499 Annex) of the @cite{Ada Reference Manual}. In general, this
25500 scheduling strategy is fully compatible with HP Ada
25501 although it provides some additional constraints (as
25502 fully documented in Annex D).
25503 GNAT implements time slicing control in a manner compatible with
25504 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25505 are identical to the HP Ada 83 pragma of the same name.
25506 Note that it is not possible to mix GNAT tasking and
25507 HP Ada 83 tasking in the same program, since the two run-time
25508 libraries are not compatible.
25509
25510 @node The Task Stack
25511 @subsection The Task Stack
25512
25513 @noindent
25514 In HP Ada, a task stack is allocated each time a
25515 non-passive task is activated. As soon as the task is
25516 terminated, the storage for the task stack is deallocated.
25517 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25518 a default stack size is used. Also, regardless of the size
25519 specified, some additional space is allocated for task
25520 management purposes. On OpenVMS Alpha systems, at least
25521 one page is allocated.
25522
25523 GNAT handles task stacks in a similar manner. In accordance with
25524 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25525 an alternative method for controlling the task stack size.
25526 The specification of the attribute @code{T'STORAGE_SIZE} is also
25527 supported in a manner compatible with HP Ada.
25528
25529 @node External Interrupts
25530 @subsection External Interrupts
25531
25532 @noindent
25533 On HP Ada, external interrupts can be associated with task entries.
25534 GNAT is compatible with HP Ada in its handling of external interrupts.
25535
25536 @node Pragmas and Pragma-Related Features
25537 @section Pragmas and Pragma-Related Features
25538
25539 @noindent
25540 Both HP Ada and GNAT supply all language-defined pragmas
25541 as specified by the Ada 83 standard. GNAT also supplies all
25542 language-defined pragmas introduced by Ada 95 and Ada 2005.
25543 In addition, GNAT implements the implementation-defined pragmas
25544 from HP Ada 83.
25545
25546 @itemize @bullet
25547 @item  @code{AST_ENTRY}
25548
25549 @item  @code{COMMON_OBJECT}
25550
25551 @item  @code{COMPONENT_ALIGNMENT}
25552
25553 @item  @code{EXPORT_EXCEPTION}
25554
25555 @item  @code{EXPORT_FUNCTION}
25556
25557 @item  @code{EXPORT_OBJECT}
25558
25559 @item  @code{EXPORT_PROCEDURE}
25560
25561 @item  @code{EXPORT_VALUED_PROCEDURE}
25562
25563 @item  @code{FLOAT_REPRESENTATION}
25564
25565 @item  @code{IDENT}
25566
25567 @item  @code{IMPORT_EXCEPTION}
25568
25569 @item  @code{IMPORT_FUNCTION}
25570
25571 @item  @code{IMPORT_OBJECT}
25572
25573 @item  @code{IMPORT_PROCEDURE}
25574
25575 @item  @code{IMPORT_VALUED_PROCEDURE}
25576
25577 @item  @code{INLINE_GENERIC}
25578
25579 @item  @code{INTERFACE_NAME}
25580
25581 @item  @code{LONG_FLOAT}
25582
25583 @item  @code{MAIN_STORAGE}
25584
25585 @item  @code{PASSIVE}
25586
25587 @item  @code{PSECT_OBJECT}
25588
25589 @item  @code{SHARE_GENERIC}
25590
25591 @item  @code{SUPPRESS_ALL}
25592
25593 @item  @code{TASK_STORAGE}
25594
25595 @item  @code{TIME_SLICE}
25596
25597 @item  @code{TITLE}
25598 @end itemize
25599
25600 @noindent
25601 These pragmas are all fully implemented, with the exception of @code{TITLE},
25602 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25603 recognized, but which have no
25604 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25605 use of Ada protected objects. In GNAT, all generics are inlined.
25606
25607 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25608 a separate subprogram specification which must appear before the
25609 subprogram body.
25610
25611 GNAT also supplies a number of implementation-defined pragmas as follows:
25612 @itemize @bullet
25613 @item  @code{ABORT_DEFER}
25614
25615 @item  @code{ADA_83}
25616
25617 @item  @code{ADA_95}
25618
25619 @item  @code{ADA_05}
25620
25621 @item  @code{ANNOTATE}
25622
25623 @item  @code{ASSERT}
25624
25625 @item  @code{C_PASS_BY_COPY}
25626
25627 @item  @code{CPP_CLASS}
25628
25629 @item  @code{CPP_CONSTRUCTOR}
25630
25631 @item  @code{CPP_DESTRUCTOR}
25632
25633 @item  @code{DEBUG}
25634
25635 @item  @code{EXTEND_SYSTEM}
25636
25637 @item  @code{LINKER_ALIAS}
25638
25639 @item  @code{LINKER_SECTION}
25640
25641 @item  @code{MACHINE_ATTRIBUTE}
25642
25643 @item  @code{NO_RETURN}
25644
25645 @item  @code{PURE_FUNCTION}
25646
25647 @item  @code{SOURCE_FILE_NAME}
25648
25649 @item  @code{SOURCE_REFERENCE}
25650
25651 @item  @code{TASK_INFO}
25652
25653 @item  @code{UNCHECKED_UNION}
25654
25655 @item  @code{UNIMPLEMENTED_UNIT}
25656
25657 @item  @code{UNIVERSAL_DATA}
25658
25659 @item  @code{UNSUPPRESS}
25660
25661 @item  @code{WARNINGS}
25662
25663 @item  @code{WEAK_EXTERNAL}
25664 @end itemize
25665
25666 @noindent
25667 For full details on these GNAT implementation-defined pragmas,
25668 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25669 Manual}.
25670
25671 @menu
25672 * Restrictions on the Pragma INLINE::
25673 * Restrictions on the Pragma INTERFACE::
25674 * Restrictions on the Pragma SYSTEM_NAME::
25675 @end menu
25676
25677 @node Restrictions on the Pragma INLINE
25678 @subsection Restrictions on Pragma @code{INLINE}
25679
25680 @noindent
25681 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25682 @itemize @bullet
25683 @item  Parameters cannot have a task type.
25684
25685 @item  Function results cannot be task types, unconstrained
25686 array types, or unconstrained types with discriminants.
25687
25688 @item  Bodies cannot declare the following:
25689 @itemize @bullet
25690 @item  Subprogram body or stub (imported subprogram is allowed)
25691
25692 @item  Tasks
25693
25694 @item  Generic declarations
25695
25696 @item  Instantiations
25697
25698 @item  Exceptions
25699
25700 @item  Access types (types derived from access types allowed)
25701
25702 @item  Array or record types
25703
25704 @item  Dependent tasks
25705
25706 @item  Direct recursive calls of subprogram or containing
25707 subprogram, directly or via a renaming
25708
25709 @end itemize
25710 @end itemize
25711
25712 @noindent
25713 In GNAT, the only restriction on pragma @code{INLINE} is that the
25714 body must occur before the call if both are in the same
25715 unit, and the size must be appropriately small. There are
25716 no other specific restrictions which cause subprograms to
25717 be incapable of being inlined.
25718
25719 @node  Restrictions on the Pragma INTERFACE
25720 @subsection  Restrictions on Pragma @code{INTERFACE}
25721
25722 @noindent
25723 The following restrictions on pragma @code{INTERFACE}
25724 are enforced by both HP Ada and GNAT:
25725 @itemize @bullet
25726 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25727 Default is the default on OpenVMS Alpha systems.
25728
25729 @item  Parameter passing: Language specifies default
25730 mechanisms but can be overridden with an @code{EXPORT} pragma.
25731
25732 @itemize @bullet
25733 @item  Ada: Use internal Ada rules.
25734
25735 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25736 record or task type. Result cannot be a string, an
25737 array, or a record.
25738
25739 @item  Fortran: Parameters cannot have a task type. Result cannot
25740 be a string, an array, or a record.
25741 @end itemize
25742 @end itemize
25743
25744 @noindent
25745 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25746 record parameters for all languages.
25747
25748 @node  Restrictions on the Pragma SYSTEM_NAME
25749 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25750
25751 @noindent
25752 For HP Ada for OpenVMS Alpha, the enumeration literal
25753 for the type @code{NAME} is @code{OPENVMS_AXP}.
25754 In GNAT, the enumeration
25755 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25756
25757 @node  Library of Predefined Units
25758 @section  Library of Predefined Units
25759
25760 @noindent
25761 A library of predefined units is provided as part of the
25762 HP Ada and GNAT implementations. HP Ada does not provide
25763 the package @code{MACHINE_CODE} but instead recommends importing
25764 assembler code.
25765
25766 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25767 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25768 version.
25769 The HP Ada Predefined Library units are modified to remove post-Ada 83
25770 incompatibilities and to make them interoperable with GNAT
25771 (@pxref{Changes to DECLIB}, for details).
25772 The units are located in the @file{DECLIB} directory.
25773
25774 The GNAT RTL is contained in
25775 the @file{ADALIB} directory, and
25776 the default search path is set up to find @code{DECLIB} units in preference
25777 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25778 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25779
25780 @menu
25781 * Changes to DECLIB::
25782 @end menu
25783
25784 @node Changes to DECLIB
25785 @subsection Changes to @code{DECLIB}
25786
25787 @noindent
25788 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25789 compatibility are minor and include the following:
25790
25791 @itemize @bullet
25792 @item  Adjusting the location of pragmas and record representation
25793 clauses to obey Ada 95 (and thus Ada 2005) rules
25794
25795 @item  Adding the proper notation to generic formal parameters
25796 that take unconstrained types in instantiation
25797
25798 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25799 that have package bodies not otherwise allowed
25800
25801 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25802 ``@code{PROTECTD}''.
25803 Currently these are found only in the @code{STARLET} package spec.
25804
25805 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25806 where the address size is constrained to 32 bits.
25807 @end itemize
25808
25809 @noindent
25810 None of the above changes is visible to users.
25811
25812 @node Bindings
25813 @section Bindings
25814
25815 @noindent
25816 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25817 @itemize @bullet
25818
25819 @item  Command Language Interpreter (CLI interface)
25820
25821 @item  DECtalk Run-Time Library (DTK interface)
25822
25823 @item  Librarian utility routines (LBR interface)
25824
25825 @item  General Purpose Run-Time Library (LIB interface)
25826
25827 @item  Math Run-Time Library (MTH interface)
25828
25829 @item  National Character Set Run-Time Library (NCS interface)
25830
25831 @item  Compiled Code Support Run-Time Library (OTS interface)
25832
25833 @item  Parallel Processing Run-Time Library (PPL interface)
25834
25835 @item  Screen Management Run-Time Library (SMG interface)
25836
25837 @item  Sort Run-Time Library (SOR interface)
25838
25839 @item  String Run-Time Library (STR interface)
25840
25841 @item STARLET System Library
25842 @findex Starlet
25843
25844 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25845
25846 @item  X Windows Toolkit (XT interface)
25847
25848 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25849 @end itemize
25850
25851 @noindent
25852 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25853 directory, on both the Alpha and I64 OpenVMS platforms.
25854
25855 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25856 in the
25857 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25858 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25859 @code{Xt}, and @code{X_Lib}
25860 causing the default X/Motif sharable image libraries to be linked in. This
25861 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25862 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25863
25864 It may be necessary to edit these options files to update or correct the
25865 library names if, for example, the newer X/Motif bindings from
25866 @file{ADA$EXAMPLES}
25867 had been (previous to installing GNAT) copied and renamed to supersede the
25868 default @file{ADA$PREDEFINED} versions.
25869
25870 @menu
25871 * Shared Libraries and Options Files::
25872 * Interfaces to C::
25873 @end menu
25874
25875 @node Shared Libraries and Options Files
25876 @subsection Shared Libraries and Options Files
25877
25878 @noindent
25879 When using the HP Ada
25880 predefined X and Motif bindings, the linking with their sharable images is
25881 done automatically by @command{GNAT LINK}.
25882 When using other X and Motif bindings, you need
25883 to add the corresponding sharable images to the command line for
25884 @code{GNAT LINK}. When linking with shared libraries, or with
25885 @file{.OPT} files, you must
25886 also add them to the command line for @command{GNAT LINK}.
25887
25888 A shared library to be used with GNAT is built in the same way as other
25889 libraries under VMS. The VMS Link command can be used in standard fashion.
25890
25891 @node Interfaces to C
25892 @subsection Interfaces to C
25893
25894 @noindent
25895 HP Ada
25896 provides the following Ada types and operations:
25897
25898 @itemize @bullet
25899 @item C types package (@code{C_TYPES})
25900
25901 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25902
25903 @item Other_types (@code{SHORT_INT})
25904 @end itemize
25905
25906 @noindent
25907 Interfacing to C with GNAT, you can use the above approach
25908 described for HP Ada or the facilities of Annex B of
25909 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25910 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25911 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25912
25913 The @option{-gnatF} qualifier forces default and explicit
25914 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25915 to be uppercased for compatibility with the default behavior
25916 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25917
25918 @node Main Program Definition
25919 @section Main Program Definition
25920
25921 @noindent
25922 The following section discusses differences in the
25923 definition of main programs on HP Ada and GNAT.
25924 On HP Ada, main programs are defined to meet the
25925 following conditions:
25926 @itemize @bullet
25927 @item  Procedure with no formal parameters (returns @code{0} upon
25928 normal completion)
25929
25930 @item  Procedure with no formal parameters (returns @code{42} when
25931 an unhandled exception is raised)
25932
25933 @item  Function with no formal parameters whose returned value
25934 is of a discrete type
25935
25936 @item  Procedure with one @code{out} formal of a discrete type for
25937 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25938
25939 @end itemize
25940
25941 @noindent
25942 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25943 a main function or main procedure returns a discrete
25944 value whose size is less than 64 bits (32 on VAX systems),
25945 the value is zero- or sign-extended as appropriate.
25946 On GNAT, main programs are defined as follows:
25947 @itemize @bullet
25948 @item  Must be a non-generic, parameterless subprogram that
25949 is either a procedure or function returning an Ada
25950 @code{STANDARD.INTEGER} (the predefined type)
25951
25952 @item  Cannot be a generic subprogram or an instantiation of a
25953 generic subprogram
25954 @end itemize
25955
25956 @node Implementation-Defined Attributes
25957 @section Implementation-Defined Attributes
25958
25959 @noindent
25960 GNAT provides all HP Ada implementation-defined
25961 attributes.
25962
25963 @node Compiler and Run-Time Interfacing
25964 @section Compiler and Run-Time Interfacing
25965
25966 @noindent
25967 HP Ada provides the following qualifiers to pass options to the linker
25968 (ACS LINK):
25969 @itemize @bullet
25970 @item  @option{/WAIT} and @option{/SUBMIT}
25971
25972 @item  @option{/COMMAND}
25973
25974 @item  @option{/@r{[}NO@r{]}MAP}
25975
25976 @item  @option{/OUTPUT=@var{file-spec}}
25977
25978 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25979 @end itemize
25980
25981 @noindent
25982 To pass options to the linker, GNAT provides the following
25983 switches:
25984
25985 @itemize @bullet
25986 @item   @option{/EXECUTABLE=@var{exec-name}}
25987
25988 @item   @option{/VERBOSE}
25989
25990 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25991 @end itemize
25992
25993 @noindent
25994 For more information on these switches, see
25995 @ref{Switches for gnatlink}.
25996 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25997 to control optimization. HP Ada also supplies the
25998 following pragmas:
25999 @itemize @bullet
26000 @item  @code{OPTIMIZE}
26001
26002 @item  @code{INLINE}
26003
26004 @item  @code{INLINE_GENERIC}
26005
26006 @item  @code{SUPPRESS_ALL}
26007
26008 @item  @code{PASSIVE}
26009 @end itemize
26010
26011 @noindent
26012 In GNAT, optimization is controlled strictly by command
26013 line parameters, as described in the corresponding section of this guide.
26014 The HP pragmas for control of optimization are
26015 recognized but ignored.
26016
26017 Note that in GNAT, the default is optimization off, whereas in HP Ada
26018 the default is that optimization is turned on.
26019
26020 @node Program Compilation and Library Management
26021 @section Program Compilation and Library Management
26022
26023 @noindent
26024 HP Ada and GNAT provide a comparable set of commands to
26025 build programs. HP Ada also provides a program library,
26026 which is a concept that does not exist on GNAT. Instead,
26027 GNAT provides directories of sources that are compiled as
26028 needed.
26029
26030 The following table summarizes
26031 the HP Ada commands and provides
26032 equivalent GNAT commands. In this table, some GNAT
26033 equivalents reflect the fact that GNAT does not use the
26034 concept of a program library. Instead, it uses a model
26035 in which collections of source and object files are used
26036 in a manner consistent with other languages like C and
26037 Fortran. Therefore, standard system file commands are used
26038 to manipulate these elements. Those GNAT commands are marked with
26039 an asterisk.
26040 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26041
26042 @need 1500
26043 @multitable @columnfractions .35 .65
26044
26045 @item @emph{HP Ada Command}
26046 @tab @emph{GNAT Equivalent / Description}
26047
26048 @item @command{ADA}
26049 @tab @command{GNAT COMPILE}@*
26050 Invokes the compiler to compile one or more Ada source files.
26051
26052 @item @command{ACS ATTACH}@*
26053 @tab [No equivalent]@*
26054 Switches control of terminal from current process running the program
26055 library manager.
26056
26057 @item @command{ACS CHECK}
26058 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26059 Forms the execution closure of one
26060 or more compiled units and checks completeness and currency.
26061
26062 @item @command{ACS COMPILE}
26063 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26064 Forms the execution closure of one or
26065 more specified units, checks completeness and currency,
26066 identifies units that have revised source files, compiles same,
26067 and recompiles units that are or will become obsolete.
26068 Also completes incomplete generic instantiations.
26069
26070 @item @command{ACS COPY FOREIGN}
26071 @tab Copy (*)@*
26072 Copies a foreign object file into the program library as a
26073 library unit body.
26074
26075 @item @command{ACS COPY UNIT}
26076 @tab Copy (*)@*
26077 Copies a compiled unit from one program library to another.
26078
26079 @item @command{ACS CREATE LIBRARY}
26080 @tab Create /directory (*)@*
26081 Creates a program library.
26082
26083 @item @command{ACS CREATE SUBLIBRARY}
26084 @tab Create /directory (*)@*
26085 Creates a program sublibrary.
26086
26087 @item @command{ACS DELETE LIBRARY}
26088 @tab @*
26089 Deletes a program library and its contents.
26090
26091 @item @command{ACS DELETE SUBLIBRARY}
26092 @tab @*
26093 Deletes a program sublibrary and its contents.
26094
26095 @item @command{ACS DELETE UNIT}
26096 @tab Delete file (*)@*
26097 On OpenVMS systems, deletes one or more compiled units from
26098 the current program library.
26099
26100 @item @command{ACS DIRECTORY}
26101 @tab Directory (*)@*
26102 On OpenVMS systems, lists units contained in the current
26103 program library.
26104
26105 @item @command{ACS ENTER FOREIGN}
26106 @tab Copy (*)@*
26107 Allows the import of a foreign body as an Ada library
26108 spec and enters a reference to a pointer.
26109
26110 @item @command{ACS ENTER UNIT}
26111 @tab Copy (*)@*
26112 Enters a reference (pointer) from the current program library to
26113 a unit compiled into another program library.
26114
26115 @item @command{ACS EXIT}
26116 @tab [No equivalent]@*
26117 Exits from the program library manager.
26118
26119 @item @command{ACS EXPORT}
26120 @tab Copy (*)@*
26121 Creates an object file that contains system-specific object code
26122 for one or more units. With GNAT, object files can simply be copied
26123 into the desired directory.
26124
26125 @item @command{ACS EXTRACT SOURCE}
26126 @tab Copy (*)@*
26127 Allows access to the copied source file for each Ada compilation unit
26128
26129 @item @command{ACS HELP}
26130 @tab @command{HELP GNAT}@*
26131 Provides online help.
26132
26133 @item @command{ACS LINK}
26134 @tab @command{GNAT LINK}@*
26135 Links an object file containing Ada units into an executable file.
26136
26137 @item @command{ACS LOAD}
26138 @tab Copy (*)@*
26139 Loads (partially compiles) Ada units into the program library.
26140 Allows loading a program from a collection of files into a library
26141 without knowing the relationship among units.
26142
26143 @item @command{ACS MERGE}
26144 @tab Copy (*)@*
26145 Merges into the current program library, one or more units from
26146 another library where they were modified.
26147
26148 @item @command{ACS RECOMPILE}
26149 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26150 Recompiles from   external or copied source files any obsolete
26151 unit in the closure. Also, completes any incomplete generic
26152 instantiations.
26153
26154 @item @command{ACS REENTER}
26155 @tab @command{GNAT MAKE}@*
26156 Reenters current references to units compiled after last entered
26157 with the @command{ACS ENTER UNIT} command.
26158
26159 @item @command{ACS SET LIBRARY}
26160 @tab Set default (*)@*
26161 Defines a program library to be the compilation context as well
26162 as the target library for compiler output and commands in general.
26163
26164 @item @command{ACS SET PRAGMA}
26165 @tab Edit @file{gnat.adc} (*)@*
26166 Redefines specified  values of the library characteristics
26167 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26168 and @code{Float_Representation}.
26169
26170 @item @command{ACS SET SOURCE}
26171 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26172 Defines the source file search list for the @command{ACS COMPILE} command.
26173
26174 @item @command{ACS SHOW LIBRARY}
26175 @tab Directory (*)@*
26176 Lists information about one or more program libraries.
26177
26178 @item @command{ACS SHOW PROGRAM}
26179 @tab [No equivalent]@*
26180 Lists information about the execution closure of one or
26181 more units in the program library.
26182
26183 @item @command{ACS SHOW SOURCE}
26184 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26185 Shows the source file search used when compiling units.
26186
26187 @item @command{ACS SHOW VERSION}
26188 @tab Compile with @option{VERBOSE} option
26189 Displays the version number of the compiler and program library
26190 manager used.
26191
26192 @item @command{ACS SPAWN}
26193 @tab [No equivalent]@*
26194 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26195 command).
26196
26197 @item @command{ACS VERIFY}
26198 @tab [No equivalent]@*
26199 Performs a series of consistency checks on a program library to
26200 determine whether the library structure and library files are in
26201 valid form.
26202 @end multitable
26203
26204 @noindent
26205
26206 @node Input-Output
26207 @section Input-Output
26208
26209 @noindent
26210 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26211 Management Services (RMS) to perform operations on
26212 external files.
26213
26214 @noindent
26215 HP Ada and GNAT predefine an identical set of input-
26216 output packages. To make the use of the
26217 generic @code{TEXT_IO} operations more convenient, HP Ada
26218 provides predefined library packages that instantiate the
26219 integer and floating-point operations for the predefined
26220 integer and floating-point types as shown in the following table.
26221
26222 @multitable @columnfractions .45 .55
26223 @item @emph{Package Name} @tab Instantiation
26224
26225 @item @code{INTEGER_TEXT_IO}
26226 @tab @code{INTEGER_IO(INTEGER)}
26227
26228 @item @code{SHORT_INTEGER_TEXT_IO}
26229 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26230
26231 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26232 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26233
26234 @item @code{FLOAT_TEXT_IO}
26235 @tab @code{FLOAT_IO(FLOAT)}
26236
26237 @item @code{LONG_FLOAT_TEXT_IO}
26238 @tab @code{FLOAT_IO(LONG_FLOAT)}
26239 @end multitable
26240
26241 @noindent
26242 The HP Ada predefined packages and their operations
26243 are implemented using OpenVMS Alpha files and input-output
26244 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26245 Familiarity with the following is recommended:
26246 @itemize @bullet
26247 @item  RMS file organizations and access methods
26248
26249 @item  OpenVMS file specifications and directories
26250
26251 @item  OpenVMS File Definition Language (FDL)
26252 @end itemize
26253
26254 @noindent
26255 GNAT provides I/O facilities that are completely
26256 compatible with HP Ada. The distribution includes the
26257 standard HP Ada versions of all I/O packages, operating
26258 in a manner compatible with HP Ada. In particular, the
26259 following packages are by default the HP Ada (Ada 83)
26260 versions of these packages rather than the renamings
26261 suggested in Annex J of the Ada Reference Manual:
26262 @itemize @bullet
26263 @item  @code{TEXT_IO}
26264
26265 @item  @code{SEQUENTIAL_IO}
26266
26267 @item  @code{DIRECT_IO}
26268 @end itemize
26269
26270 @noindent
26271 The use of the standard child package syntax (for
26272 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26273 packages.
26274 GNAT provides HP-compatible predefined instantiations
26275 of the @code{TEXT_IO} packages, and also
26276 provides the standard predefined instantiations required
26277 by the @cite{Ada Reference Manual}.
26278
26279 For further information on how GNAT interfaces to the file
26280 system or how I/O is implemented in programs written in
26281 mixed languages, see @ref{Implementation of the Standard I/O,,,
26282 gnat_rm, GNAT Reference Manual}.
26283 This chapter covers the following:
26284 @itemize @bullet
26285 @item  Standard I/O packages
26286
26287 @item  @code{FORM} strings
26288
26289 @item  @code{ADA.DIRECT_IO}
26290
26291 @item  @code{ADA.SEQUENTIAL_IO}
26292
26293 @item  @code{ADA.TEXT_IO}
26294
26295 @item  Stream pointer positioning
26296
26297 @item  Reading and writing non-regular files
26298
26299 @item  @code{GET_IMMEDIATE}
26300
26301 @item  Treating @code{TEXT_IO} files as streams
26302
26303 @item  Shared files
26304
26305 @item  Open modes
26306 @end itemize
26307
26308 @node Implementation Limits
26309 @section Implementation Limits
26310
26311 @noindent
26312 The following table lists implementation limits for HP Ada
26313 and GNAT systems.
26314 @multitable @columnfractions .60 .20 .20
26315 @sp 1
26316 @item  @emph{Compilation Parameter}
26317 @tab   @emph{HP Ada}
26318 @tab   @emph{GNAT}
26319 @sp 1
26320
26321 @item  In a subprogram or entry  declaration, maximum number of
26322 formal parameters that are of an unconstrained record type
26323 @tab   32
26324 @tab   No set limit
26325 @sp 1
26326
26327 @item  Maximum identifier length (number of characters)
26328 @tab   255
26329 @tab   32766
26330 @sp 1
26331
26332 @item  Maximum number of characters in a source line
26333 @tab   255
26334 @tab   32766
26335 @sp 1
26336
26337 @item  Maximum collection size   (number of bytes)
26338 @tab   2**31-1
26339 @tab   2**31-1
26340 @sp 1
26341
26342 @item  Maximum number of discriminants for a record type
26343 @tab   245
26344 @tab   No set limit
26345 @sp 1
26346
26347 @item  Maximum number of formal parameters in an entry or
26348 subprogram declaration
26349 @tab   246
26350 @tab    No set limit
26351 @sp 1
26352
26353 @item  Maximum number of dimensions in an array type
26354 @tab   255
26355 @tab   No set limit
26356 @sp 1
26357
26358 @item  Maximum number of library  units and subunits in a compilation.
26359 @tab   4095
26360 @tab   No set limit
26361 @sp 1
26362
26363 @item  Maximum number of library units and subunits in an execution.
26364 @tab   16383
26365 @tab   No set limit
26366 @sp 1
26367
26368 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26369 or @code{PSECT_OBJECT}
26370 @tab   32757
26371 @tab   No set limit
26372 @sp 1
26373
26374 @item  Maximum number of enumeration literals in an enumeration type
26375 definition
26376 @tab   65535
26377 @tab   No set limit
26378 @sp 1
26379
26380 @item  Maximum number of lines in a source file
26381 @tab   65534
26382 @tab   No set limit
26383 @sp 1
26384
26385 @item  Maximum number of bits in any object
26386 @tab   2**31-1
26387 @tab   2**31-1
26388 @sp 1
26389
26390 @item  Maximum size of the static portion of a stack frame (approximate)
26391 @tab   2**31-1
26392 @tab   2**31-1
26393 @end multitable
26394
26395 @node Tools and Utilities
26396 @section Tools and Utilities
26397
26398 @noindent
26399 The following table lists some of the OpenVMS development tools
26400 available for HP Ada, and the corresponding tools for
26401 use with @value{EDITION} on Alpha and I64 platforms.
26402 Aside from the debugger, all the OpenVMS tools identified are part
26403 of the DECset package.
26404
26405 @iftex
26406 @c Specify table in TeX since Texinfo does a poor job
26407 @tex
26408 \smallskip
26409 \smallskip
26410 \settabs\+Language-Sensitive Editor\quad
26411    &Product with HP Ada\quad
26412    &\cr
26413 \+\it Tool
26414    &\it Product with HP Ada
26415    & \it Product with GNAT Pro\cr
26416 \smallskip
26417 \+Code Management System
26418    &HP CMS
26419    & HP CMS\cr
26420 \smallskip
26421 \+Language-Sensitive Editor
26422    &HP LSE
26423    & emacs or HP LSE (Alpha)\cr
26424 \+
26425    &
26426    & HP LSE (I64)\cr
26427 \smallskip
26428 \+Debugger
26429    &OpenVMS Debug
26430    & gdb (Alpha),\cr
26431 \+
26432    &
26433    & OpenVMS Debug (I64)\cr
26434 \smallskip
26435 \+Source Code Analyzer /
26436    &HP SCA
26437    & GNAT XREF\cr
26438 \+Cross Referencer
26439    &
26440    &\cr
26441 \smallskip
26442 \+Test Manager
26443    &HP Digital Test
26444    & HP DTM\cr
26445 \+
26446    &Manager (DTM)
26447    &\cr
26448 \smallskip
26449 \+Performance and
26450    & HP PCA
26451    & HP PCA\cr
26452 \+Coverage Analyzer
26453    &
26454    &\cr
26455 \smallskip
26456 \+Module Management
26457    & HP MMS
26458    & Not applicable\cr
26459 \+ System
26460    &
26461    &\cr
26462 \smallskip
26463 \smallskip
26464 @end tex
26465 @end iftex
26466
26467 @ifnottex
26468 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26469 @c the TeX version above for the printed version
26470 @flushleft
26471 @c @multitable @columnfractions .3 .4 .4
26472 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26473 @item @i{Tool}
26474 @tab @i{Tool with HP Ada}
26475 @tab @i{Tool with @value{EDITION}}
26476 @item Code Management@*System
26477 @tab HP CMS
26478 @tab HP CMS
26479 @item Language-Sensitive@*Editor
26480 @tab HP LSE
26481 @tab emacs or HP LSE (Alpha)
26482 @item
26483 @tab
26484 @tab HP LSE (I64)
26485 @item Debugger
26486 @tab OpenVMS Debug
26487 @tab gdb (Alpha),
26488 @item
26489 @tab
26490 @tab OpenVMS Debug (I64)
26491 @item Source Code Analyzer /@*Cross Referencer
26492 @tab HP SCA
26493 @tab GNAT XREF
26494 @item Test Manager
26495 @tab HP Digital Test@*Manager (DTM)
26496 @tab HP DTM
26497 @item Performance and@*Coverage Analyzer
26498 @tab HP PCA
26499 @tab HP PCA
26500 @item Module Management@*System
26501 @tab HP MMS
26502 @tab Not applicable
26503 @end multitable
26504 @end flushleft
26505 @end ifnottex
26506
26507 @end ifset
26508
26509 @c **************************************
26510 @node Platform-Specific Information for the Run-Time Libraries
26511 @appendix Platform-Specific Information for the Run-Time Libraries
26512 @cindex Tasking and threads libraries
26513 @cindex Threads libraries and tasking
26514 @cindex Run-time libraries (platform-specific information)
26515
26516 @noindent
26517 The GNAT run-time implementation may vary with respect to both the
26518 underlying threads library and the exception handling scheme.
26519 For threads support, one or more of the following are supplied:
26520 @itemize @bullet
26521 @item @b{native threads library}, a binding to the thread package from
26522 the underlying operating system
26523
26524 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26525 POSIX thread package
26526 @end itemize
26527
26528 @noindent
26529 For exception handling, either or both of two models are supplied:
26530 @itemize @bullet
26531 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26532 Most programs should experience a substantial speed improvement by
26533 being compiled with a ZCX run-time.
26534 This is especially true for
26535 tasking applications or applications with many exception handlers.}
26536 @cindex Zero-Cost Exceptions
26537 @cindex ZCX (Zero-Cost Exceptions)
26538 which uses binder-generated tables that
26539 are interrogated at run time to locate a handler
26540
26541 @item @b{setjmp / longjmp} (``SJLJ''),
26542 @cindex setjmp/longjmp Exception Model
26543 @cindex SJLJ (setjmp/longjmp Exception Model)
26544 which uses dynamically-set data to establish
26545 the set of handlers
26546 @end itemize
26547
26548 @noindent
26549 This appendix summarizes which combinations of threads and exception support
26550 are supplied on various GNAT platforms.
26551 It then shows how to select a particular library either
26552 permanently or temporarily,
26553 explains the properties of (and tradeoffs among) the various threads
26554 libraries, and provides some additional
26555 information about several specific platforms.
26556
26557 @menu
26558 * Summary of Run-Time Configurations::
26559 * Specifying a Run-Time Library::
26560 * Choosing the Scheduling Policy::
26561 * Solaris-Specific Considerations::
26562 * Linux-Specific Considerations::
26563 * AIX-Specific Considerations::
26564 * Irix-Specific Considerations::
26565 * RTX-Specific Considerations::
26566 @end menu
26567
26568 @node Summary of Run-Time Configurations
26569 @section Summary of Run-Time Configurations
26570
26571 @multitable @columnfractions .30 .70
26572 @item @b{alpha-openvms}
26573 @item @code{@ @ }@i{rts-native (default)}
26574 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26575 @item @code{@ @ @ @ }Exceptions @tab ZCX
26576 @*
26577 @item @b{alpha-tru64}
26578 @item @code{@ @ }@i{rts-native (default)}
26579 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26580 @item @code{@ @ @ @ }Exceptions @tab ZCX
26581 @*
26582 @item @code{@ @ }@i{rts-sjlj}
26583 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26584 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26585 @*
26586 @item @b{ia64-hp_linux}
26587 @item @code{@ @ }@i{rts-native (default)}
26588 @item @code{@ @ @ @ }Tasking    @tab pthread library
26589 @item @code{@ @ @ @ }Exceptions @tab ZCX
26590 @*
26591 @item @b{ia64-hpux}
26592 @item @code{@ @ }@i{rts-native (default)}
26593 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26594 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26595 @*
26596 @item @b{ia64-openvms}
26597 @item @code{@ @ }@i{rts-native (default)}
26598 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26599 @item @code{@ @ @ @ }Exceptions @tab ZCX
26600 @*
26601 @item @b{ia64-sgi_linux}
26602 @item @code{@ @ }@i{rts-native (default)}
26603 @item @code{@ @ @ @ }Tasking    @tab pthread library
26604 @item @code{@ @ @ @ }Exceptions @tab ZCX
26605 @*
26606 @item @b{mips-irix}
26607 @item @code{@ @ }@i{rts-native (default)}
26608 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26609 @item @code{@ @ @ @ }Exceptions @tab ZCX
26610 @*
26611 @item @b{pa-hpux}
26612 @item @code{@ @ }@i{rts-native (default)}
26613 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26614 @item @code{@ @ @ @ }Exceptions @tab ZCX
26615 @*
26616 @item @code{@ @ }@i{rts-sjlj}
26617 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26618 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26619 @*
26620 @item @b{ppc-aix}
26621 @item @code{@ @ }@i{rts-native (default)}
26622 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26623 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26624 @*
26625 @item @b{ppc-darwin}
26626 @item @code{@ @ }@i{rts-native (default)}
26627 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26628 @item @code{@ @ @ @ }Exceptions @tab ZCX
26629 @*
26630 @item @b{sparc-solaris}  @tab
26631 @item @code{@ @ }@i{rts-native (default)}
26632 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26633 @item @code{@ @ @ @ }Exceptions @tab ZCX
26634 @*
26635 @item @code{@ @ }@i{rts-pthread}
26636 @item @code{@ @ @ @ }Tasking    @tab pthread library
26637 @item @code{@ @ @ @ }Exceptions @tab ZCX
26638 @*
26639 @item @code{@ @ }@i{rts-sjlj}
26640 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26641 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26642 @*
26643 @item @b{sparc64-solaris}  @tab
26644 @item @code{@ @ }@i{rts-native (default)}
26645 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26646 @item @code{@ @ @ @ }Exceptions @tab ZCX
26647 @*
26648 @item @b{x86-linux}
26649 @item @code{@ @ }@i{rts-native (default)}
26650 @item @code{@ @ @ @ }Tasking    @tab pthread library
26651 @item @code{@ @ @ @ }Exceptions @tab ZCX
26652 @*
26653 @item @code{@ @ }@i{rts-sjlj}
26654 @item @code{@ @ @ @ }Tasking    @tab pthread library
26655 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26656 @*
26657 @item @b{x86-lynx}
26658 @item @code{@ @ }@i{rts-native (default)}
26659 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26660 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26661 @*
26662 @item @b{x86-solaris}
26663 @item @code{@ @ }@i{rts-native (default)}
26664 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26665 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26666 @*
26667 @item @b{x86-windows}
26668 @item @code{@ @ }@i{rts-native (default)}
26669 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26670 @item @code{@ @ @ @ }Exceptions @tab ZCX
26671 @*
26672 @item @code{@ @ }@i{rts-sjlj (default)}
26673 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26674 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26675 @*
26676 @item @b{x86-windows-rtx}
26677 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26678 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26679 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26680 @*
26681 @item @code{@ @ }@i{rts-rtx-w32}
26682 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26683 @item @code{@ @ @ @ }Exceptions @tab ZCX
26684 @*
26685 @item @b{x86_64-linux}
26686 @item @code{@ @ }@i{rts-native (default)}
26687 @item @code{@ @ @ @ }Tasking    @tab pthread library
26688 @item @code{@ @ @ @ }Exceptions @tab ZCX
26689 @*
26690 @item @code{@ @ }@i{rts-sjlj}
26691 @item @code{@ @ @ @ }Tasking    @tab pthread library
26692 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26693 @*
26694 @end multitable
26695
26696 @node Specifying a Run-Time Library
26697 @section Specifying a Run-Time Library
26698
26699 @noindent
26700 The @file{adainclude} subdirectory containing the sources of the GNAT
26701 run-time library, and the @file{adalib} subdirectory containing the
26702 @file{ALI} files and the static and/or shared GNAT library, are located
26703 in the gcc target-dependent area:
26704
26705 @smallexample
26706 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26707 @end smallexample
26708
26709 @noindent
26710 As indicated above, on some platforms several run-time libraries are supplied.
26711 These libraries are installed in the target dependent area and
26712 contain a complete source and binary subdirectory. The detailed description
26713 below explains the differences between the different libraries in terms of
26714 their thread support.
26715
26716 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26717 This default run time is selected by the means of soft links.
26718 For example on x86-linux:
26719
26720 @smallexample
26721 @group
26722  $(target-dir)
26723      |
26724      +--- adainclude----------+
26725      |                        |
26726      +--- adalib-----------+  |
26727      |                     |  |
26728      +--- rts-native       |  |
26729      |    |                |  |
26730      |    +--- adainclude <---+
26731      |    |                |
26732      |    +--- adalib <----+
26733      |
26734      +--- rts-sjlj
26735           |
26736           +--- adainclude
26737           |
26738           +--- adalib
26739 @end group
26740 @end smallexample
26741
26742 @noindent
26743 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26744 these soft links can be modified with the following commands:
26745
26746 @smallexample
26747 $ cd $target
26748 $ rm -f adainclude adalib
26749 $ ln -s rts-sjlj/adainclude adainclude
26750 $ ln -s rts-sjlj/adalib adalib
26751 @end smallexample
26752
26753 @noindent
26754 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26755 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26756 @file{$target/ada_object_path}.
26757
26758 Selecting another run-time library temporarily can be
26759 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26760 @cindex @option{--RTS} option
26761
26762 @node Choosing the Scheduling Policy
26763 @section Choosing the Scheduling Policy
26764
26765 @noindent
26766 When using a POSIX threads implementation, you have a choice of several
26767 scheduling policies: @code{SCHED_FIFO},
26768 @cindex @code{SCHED_FIFO} scheduling policy
26769 @code{SCHED_RR}
26770 @cindex @code{SCHED_RR} scheduling policy
26771 and @code{SCHED_OTHER}.
26772 @cindex @code{SCHED_OTHER} scheduling policy
26773 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26774 or @code{SCHED_RR} requires special (e.g., root) privileges.
26775
26776 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26777 @code{SCHED_FIFO},
26778 @cindex @code{SCHED_FIFO} scheduling policy
26779 you can use one of the following:
26780
26781 @itemize @bullet
26782 @item
26783 @code{pragma Time_Slice (0.0)}
26784 @cindex pragma Time_Slice
26785 @item
26786 the corresponding binder option @option{-T0}
26787 @cindex @option{-T0} option
26788 @item
26789 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26790 @cindex pragma Task_Dispatching_Policy
26791 @end itemize
26792
26793 @noindent
26794 To specify @code{SCHED_RR},
26795 @cindex @code{SCHED_RR} scheduling policy
26796 you should use @code{pragma Time_Slice} with a
26797 value greater than @code{0.0}, or else use the corresponding @option{-T}
26798 binder option.
26799
26800 @node Solaris-Specific Considerations
26801 @section Solaris-Specific Considerations
26802 @cindex Solaris Sparc threads libraries
26803
26804 @noindent
26805 This section addresses some topics related to the various threads libraries
26806 on Sparc Solaris.
26807
26808 @menu
26809 * Solaris Threads Issues::
26810 @end menu
26811
26812 @node Solaris Threads Issues
26813 @subsection Solaris Threads Issues
26814
26815 @noindent
26816 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26817 library based on POSIX threads --- @emph{rts-pthread}.
26818 @cindex rts-pthread threads library
26819 This run-time library has the advantage of being mostly shared across all
26820 POSIX-compliant thread implementations, and it also provides under
26821 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26822 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26823 and @code{PTHREAD_PRIO_PROTECT}
26824 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26825 semantics that can be selected using the predefined pragma
26826 @code{Locking_Policy}
26827 @cindex pragma Locking_Policy (under rts-pthread)
26828 with respectively
26829 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26830 @cindex @code{Inheritance_Locking} (under rts-pthread)
26831 @cindex @code{Ceiling_Locking} (under rts-pthread)
26832
26833 As explained above, the native run-time library is based on the Solaris thread
26834 library (@code{libthread}) and is the default library.
26835
26836 When the Solaris threads library is used (this is the default), programs
26837 compiled with GNAT can automatically take advantage of
26838 and can thus execute on multiple processors.
26839 The user can alternatively specify a processor on which the program should run
26840 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26841 is made by
26842 setting the environment variable @env{GNAT_PROCESSOR}
26843 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26844 to one of the following:
26845
26846 @table @code
26847 @item -2
26848 Use the default configuration (run the program on all
26849 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26850 unset
26851
26852 @item -1
26853 Let the run-time implementation choose one processor and run the program on
26854 that processor
26855
26856 @item 0 .. Last_Proc
26857 Run the program on the specified processor.
26858 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26859 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26860 @end table
26861
26862 @node Linux-Specific Considerations
26863 @section Linux-Specific Considerations
26864 @cindex Linux threads libraries
26865
26866 @noindent
26867 On GNU/Linux without NPTL support (usually system with GNU C Library
26868 older than 2.3), the signal model is not POSIX compliant, which means
26869 that to send a signal to the process, you need to send the signal to all
26870 threads, e.g.@: by using @code{killpg()}.
26871
26872 @node AIX-Specific Considerations
26873 @section AIX-Specific Considerations
26874 @cindex AIX resolver library
26875
26876 @noindent
26877 On AIX, the resolver library initializes some internal structure on
26878 the first call to @code{get*by*} functions, which are used to implement
26879 @code{GNAT.Sockets.Get_Host_By_Name} and
26880 @code{GNAT.Sockets.Get_Host_By_Address}.
26881 If such initialization occurs within an Ada task, and the stack size for
26882 the task is the default size, a stack overflow may occur.
26883
26884 To avoid this overflow, the user should either ensure that the first call
26885 to @code{GNAT.Sockets.Get_Host_By_Name} or
26886 @code{GNAT.Sockets.Get_Host_By_Addrss}
26887 occurs in the environment task, or use @code{pragma Storage_Size} to
26888 specify a sufficiently large size for the stack of the task that contains
26889 this call.
26890
26891 @node Irix-Specific Considerations
26892 @section Irix-Specific Considerations
26893 @cindex Irix libraries
26894
26895 @noindent
26896 The GCC support libraries coming with the Irix compiler have moved to
26897 their canonical place with respect to the general Irix ABI related
26898 conventions. Running applications built with the default shared GNAT
26899 run-time now requires the LD_LIBRARY_PATH environment variable to
26900 include this location. A possible way to achieve this is to issue the
26901 following command line on a bash prompt:
26902
26903 @smallexample
26904 @group
26905 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26906 @end group
26907 @end smallexample
26908
26909 @node RTX-Specific Considerations
26910 @section RTX-Specific Considerations
26911 @cindex RTX libraries
26912
26913 @noindent
26914 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26915 API. Applications can be built to work in two different modes:
26916
26917 @itemize @bullet
26918 @item
26919 Windows executables that run in Ring 3 to utilize memory protection
26920 (@emph{rts-rtx-w32}).
26921
26922 @item
26923 Real-time subsystem (RTSS) executables that run in Ring 0, where
26924 performance can be optimized with RTSS applications taking precedent
26925 over all Windows applications (@emph{rts-rtx-rtss}).
26926
26927 @end itemize
26928
26929 @c *******************************
26930 @node Example of Binder Output File
26931 @appendix Example of Binder Output File
26932
26933 @noindent
26934 This Appendix displays the source code for @command{gnatbind}'s output
26935 file generated for a simple ``Hello World'' program.
26936 Comments have been added for clarification purposes.
26937
26938 @smallexample @c adanocomment
26939 @iftex
26940 @leftskip=0cm
26941 @end iftex
26942 --  The package is called Ada_Main unless this name is actually used
26943 --  as a unit name in the partition, in which case some other unique
26944 --  name is used.
26945
26946 with System;
26947 package ada_main is
26948
26949    Elab_Final_Code : Integer;
26950    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26951
26952    --  The main program saves the parameters (argument count,
26953    --  argument values, environment pointer) in global variables
26954    --  for later access by other units including
26955    --  Ada.Command_Line.
26956
26957    gnat_argc : Integer;
26958    gnat_argv : System.Address;
26959    gnat_envp : System.Address;
26960
26961    --  The actual variables are stored in a library routine. This
26962    --  is useful for some shared library situations, where there
26963    --  are problems if variables are not in the library.
26964
26965    pragma Import (C, gnat_argc);
26966    pragma Import (C, gnat_argv);
26967    pragma Import (C, gnat_envp);
26968
26969    --  The exit status is similarly an external location
26970
26971    gnat_exit_status : Integer;
26972    pragma Import (C, gnat_exit_status);
26973
26974    GNAT_Version : constant String :=
26975                     "GNAT Version: 6.0.0w (20061115)";
26976    pragma Export (C, GNAT_Version, "__gnat_version");
26977
26978    --  This is the generated adafinal routine that performs
26979    --  finalization at the end of execution. In the case where
26980    --  Ada is the main program, this main program makes a call
26981    --  to adafinal at program termination.
26982
26983    procedure adafinal;
26984    pragma Export (C, adafinal, "adafinal");
26985
26986    --  This is the generated adainit routine that performs
26987    --  initialization at the start of execution. In the case
26988    --  where Ada is the main program, this main program makes
26989    --  a call to adainit at program startup.
26990
26991    procedure adainit;
26992    pragma Export (C, adainit, "adainit");
26993
26994    --  This routine is called at the start of execution. It is
26995    --  a dummy routine that is used by the debugger to breakpoint
26996    --  at the start of execution.
26997
26998    procedure Break_Start;
26999    pragma Import (C, Break_Start, "__gnat_break_start");
27000
27001    --  This is the actual generated main program (it would be
27002    --  suppressed if the no main program switch were used). As
27003    --  required by standard system conventions, this program has
27004    --  the external name main.
27005
27006    function main
27007      (argc : Integer;
27008       argv : System.Address;
27009       envp : System.Address)
27010       return Integer;
27011    pragma Export (C, main, "main");
27012
27013    --  The following set of constants give the version
27014    --  identification values for every unit in the bound
27015    --  partition. This identification is computed from all
27016    --  dependent semantic units, and corresponds to the
27017    --  string that would be returned by use of the
27018    --  Body_Version or Version attributes.
27019
27020    type Version_32 is mod 2 ** 32;
27021    u00001 : constant Version_32 := 16#7880BEB3#;
27022    u00002 : constant Version_32 := 16#0D24CBD0#;
27023    u00003 : constant Version_32 := 16#3283DBEB#;
27024    u00004 : constant Version_32 := 16#2359F9ED#;
27025    u00005 : constant Version_32 := 16#664FB847#;
27026    u00006 : constant Version_32 := 16#68E803DF#;
27027    u00007 : constant Version_32 := 16#5572E604#;
27028    u00008 : constant Version_32 := 16#46B173D8#;
27029    u00009 : constant Version_32 := 16#156A40CF#;
27030    u00010 : constant Version_32 := 16#033DABE0#;
27031    u00011 : constant Version_32 := 16#6AB38FEA#;
27032    u00012 : constant Version_32 := 16#22B6217D#;
27033    u00013 : constant Version_32 := 16#68A22947#;
27034    u00014 : constant Version_32 := 16#18CC4A56#;
27035    u00015 : constant Version_32 := 16#08258E1B#;
27036    u00016 : constant Version_32 := 16#367D5222#;
27037    u00017 : constant Version_32 := 16#20C9ECA4#;
27038    u00018 : constant Version_32 := 16#50D32CB6#;
27039    u00019 : constant Version_32 := 16#39A8BB77#;
27040    u00020 : constant Version_32 := 16#5CF8FA2B#;
27041    u00021 : constant Version_32 := 16#2F1EB794#;
27042    u00022 : constant Version_32 := 16#31AB6444#;
27043    u00023 : constant Version_32 := 16#1574B6E9#;
27044    u00024 : constant Version_32 := 16#5109C189#;
27045    u00025 : constant Version_32 := 16#56D770CD#;
27046    u00026 : constant Version_32 := 16#02F9DE3D#;
27047    u00027 : constant Version_32 := 16#08AB6B2C#;
27048    u00028 : constant Version_32 := 16#3FA37670#;
27049    u00029 : constant Version_32 := 16#476457A0#;
27050    u00030 : constant Version_32 := 16#731E1B6E#;
27051    u00031 : constant Version_32 := 16#23C2E789#;
27052    u00032 : constant Version_32 := 16#0F1BD6A1#;
27053    u00033 : constant Version_32 := 16#7C25DE96#;
27054    u00034 : constant Version_32 := 16#39ADFFA2#;
27055    u00035 : constant Version_32 := 16#571DE3E7#;
27056    u00036 : constant Version_32 := 16#5EB646AB#;
27057    u00037 : constant Version_32 := 16#4249379B#;
27058    u00038 : constant Version_32 := 16#0357E00A#;
27059    u00039 : constant Version_32 := 16#3784FB72#;
27060    u00040 : constant Version_32 := 16#2E723019#;
27061    u00041 : constant Version_32 := 16#623358EA#;
27062    u00042 : constant Version_32 := 16#107F9465#;
27063    u00043 : constant Version_32 := 16#6843F68A#;
27064    u00044 : constant Version_32 := 16#63305874#;
27065    u00045 : constant Version_32 := 16#31E56CE1#;
27066    u00046 : constant Version_32 := 16#02917970#;
27067    u00047 : constant Version_32 := 16#6CCBA70E#;
27068    u00048 : constant Version_32 := 16#41CD4204#;
27069    u00049 : constant Version_32 := 16#572E3F58#;
27070    u00050 : constant Version_32 := 16#20729FF5#;
27071    u00051 : constant Version_32 := 16#1D4F93E8#;
27072    u00052 : constant Version_32 := 16#30B2EC3D#;
27073    u00053 : constant Version_32 := 16#34054F96#;
27074    u00054 : constant Version_32 := 16#5A199860#;
27075    u00055 : constant Version_32 := 16#0E7F912B#;
27076    u00056 : constant Version_32 := 16#5760634A#;
27077    u00057 : constant Version_32 := 16#5D851835#;
27078
27079    --  The following Export pragmas export the version numbers
27080    --  with symbolic names ending in B (for body) or S
27081    --  (for spec) so that they can be located in a link. The
27082    --  information provided here is sufficient to track down
27083    --  the exact versions of units used in a given build.
27084
27085    pragma Export (C, u00001, "helloB");
27086    pragma Export (C, u00002, "system__standard_libraryB");
27087    pragma Export (C, u00003, "system__standard_libraryS");
27088    pragma Export (C, u00004, "adaS");
27089    pragma Export (C, u00005, "ada__text_ioB");
27090    pragma Export (C, u00006, "ada__text_ioS");
27091    pragma Export (C, u00007, "ada__exceptionsB");
27092    pragma Export (C, u00008, "ada__exceptionsS");
27093    pragma Export (C, u00009, "gnatS");
27094    pragma Export (C, u00010, "gnat__heap_sort_aB");
27095    pragma Export (C, u00011, "gnat__heap_sort_aS");
27096    pragma Export (C, u00012, "systemS");
27097    pragma Export (C, u00013, "system__exception_tableB");
27098    pragma Export (C, u00014, "system__exception_tableS");
27099    pragma Export (C, u00015, "gnat__htableB");
27100    pragma Export (C, u00016, "gnat__htableS");
27101    pragma Export (C, u00017, "system__exceptionsS");
27102    pragma Export (C, u00018, "system__machine_state_operationsB");
27103    pragma Export (C, u00019, "system__machine_state_operationsS");
27104    pragma Export (C, u00020, "system__machine_codeS");
27105    pragma Export (C, u00021, "system__storage_elementsB");
27106    pragma Export (C, u00022, "system__storage_elementsS");
27107    pragma Export (C, u00023, "system__secondary_stackB");
27108    pragma Export (C, u00024, "system__secondary_stackS");
27109    pragma Export (C, u00025, "system__parametersB");
27110    pragma Export (C, u00026, "system__parametersS");
27111    pragma Export (C, u00027, "system__soft_linksB");
27112    pragma Export (C, u00028, "system__soft_linksS");
27113    pragma Export (C, u00029, "system__stack_checkingB");
27114    pragma Export (C, u00030, "system__stack_checkingS");
27115    pragma Export (C, u00031, "system__tracebackB");
27116    pragma Export (C, u00032, "system__tracebackS");
27117    pragma Export (C, u00033, "ada__streamsS");
27118    pragma Export (C, u00034, "ada__tagsB");
27119    pragma Export (C, u00035, "ada__tagsS");
27120    pragma Export (C, u00036, "system__string_opsB");
27121    pragma Export (C, u00037, "system__string_opsS");
27122    pragma Export (C, u00038, "interfacesS");
27123    pragma Export (C, u00039, "interfaces__c_streamsB");
27124    pragma Export (C, u00040, "interfaces__c_streamsS");
27125    pragma Export (C, u00041, "system__file_ioB");
27126    pragma Export (C, u00042, "system__file_ioS");
27127    pragma Export (C, u00043, "ada__finalizationB");
27128    pragma Export (C, u00044, "ada__finalizationS");
27129    pragma Export (C, u00045, "system__finalization_rootB");
27130    pragma Export (C, u00046, "system__finalization_rootS");
27131    pragma Export (C, u00047, "system__finalization_implementationB");
27132    pragma Export (C, u00048, "system__finalization_implementationS");
27133    pragma Export (C, u00049, "system__string_ops_concat_3B");
27134    pragma Export (C, u00050, "system__string_ops_concat_3S");
27135    pragma Export (C, u00051, "system__stream_attributesB");
27136    pragma Export (C, u00052, "system__stream_attributesS");
27137    pragma Export (C, u00053, "ada__io_exceptionsS");
27138    pragma Export (C, u00054, "system__unsigned_typesS");
27139    pragma Export (C, u00055, "system__file_control_blockS");
27140    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27141    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27142
27143    -- BEGIN ELABORATION ORDER
27144    -- ada (spec)
27145    -- gnat (spec)
27146    -- gnat.heap_sort_a (spec)
27147    -- gnat.heap_sort_a (body)
27148    -- gnat.htable (spec)
27149    -- gnat.htable (body)
27150    -- interfaces (spec)
27151    -- system (spec)
27152    -- system.machine_code (spec)
27153    -- system.parameters (spec)
27154    -- system.parameters (body)
27155    -- interfaces.c_streams (spec)
27156    -- interfaces.c_streams (body)
27157    -- system.standard_library (spec)
27158    -- ada.exceptions (spec)
27159    -- system.exception_table (spec)
27160    -- system.exception_table (body)
27161    -- ada.io_exceptions (spec)
27162    -- system.exceptions (spec)
27163    -- system.storage_elements (spec)
27164    -- system.storage_elements (body)
27165    -- system.machine_state_operations (spec)
27166    -- system.machine_state_operations (body)
27167    -- system.secondary_stack (spec)
27168    -- system.stack_checking (spec)
27169    -- system.soft_links (spec)
27170    -- system.soft_links (body)
27171    -- system.stack_checking (body)
27172    -- system.secondary_stack (body)
27173    -- system.standard_library (body)
27174    -- system.string_ops (spec)
27175    -- system.string_ops (body)
27176    -- ada.tags (spec)
27177    -- ada.tags (body)
27178    -- ada.streams (spec)
27179    -- system.finalization_root (spec)
27180    -- system.finalization_root (body)
27181    -- system.string_ops_concat_3 (spec)
27182    -- system.string_ops_concat_3 (body)
27183    -- system.traceback (spec)
27184    -- system.traceback (body)
27185    -- ada.exceptions (body)
27186    -- system.unsigned_types (spec)
27187    -- system.stream_attributes (spec)
27188    -- system.stream_attributes (body)
27189    -- system.finalization_implementation (spec)
27190    -- system.finalization_implementation (body)
27191    -- ada.finalization (spec)
27192    -- ada.finalization (body)
27193    -- ada.finalization.list_controller (spec)
27194    -- ada.finalization.list_controller (body)
27195    -- system.file_control_block (spec)
27196    -- system.file_io (spec)
27197    -- system.file_io (body)
27198    -- ada.text_io (spec)
27199    -- ada.text_io (body)
27200    -- hello (body)
27201    -- END ELABORATION ORDER
27202
27203 end ada_main;
27204
27205 --  The following source file name pragmas allow the generated file
27206 --  names to be unique for different main programs. They are needed
27207 --  since the package name will always be Ada_Main.
27208
27209 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27210 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27211
27212 --  Generated package body for Ada_Main starts here
27213
27214 package body ada_main is
27215
27216    --  The actual finalization is performed by calling the
27217    --  library routine in System.Standard_Library.Adafinal
27218
27219    procedure Do_Finalize;
27220    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27221
27222    -------------
27223    -- adainit --
27224    -------------
27225
27226 @findex adainit
27227    procedure adainit is
27228
27229       --  These booleans are set to True once the associated unit has
27230       --  been elaborated. It is also used to avoid elaborating the
27231       --  same unit twice.
27232
27233       E040 : Boolean;
27234       pragma Import (Ada, E040, "interfaces__c_streams_E");
27235
27236       E008 : Boolean;
27237       pragma Import (Ada, E008, "ada__exceptions_E");
27238
27239       E014 : Boolean;
27240       pragma Import (Ada, E014, "system__exception_table_E");
27241
27242       E053 : Boolean;
27243       pragma Import (Ada, E053, "ada__io_exceptions_E");
27244
27245       E017 : Boolean;
27246       pragma Import (Ada, E017, "system__exceptions_E");
27247
27248       E024 : Boolean;
27249       pragma Import (Ada, E024, "system__secondary_stack_E");
27250
27251       E030 : Boolean;
27252       pragma Import (Ada, E030, "system__stack_checking_E");
27253
27254       E028 : Boolean;
27255       pragma Import (Ada, E028, "system__soft_links_E");
27256
27257       E035 : Boolean;
27258       pragma Import (Ada, E035, "ada__tags_E");
27259
27260       E033 : Boolean;
27261       pragma Import (Ada, E033, "ada__streams_E");
27262
27263       E046 : Boolean;
27264       pragma Import (Ada, E046, "system__finalization_root_E");
27265
27266       E048 : Boolean;
27267       pragma Import (Ada, E048, "system__finalization_implementation_E");
27268
27269       E044 : Boolean;
27270       pragma Import (Ada, E044, "ada__finalization_E");
27271
27272       E057 : Boolean;
27273       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27274
27275       E055 : Boolean;
27276       pragma Import (Ada, E055, "system__file_control_block_E");
27277
27278       E042 : Boolean;
27279       pragma Import (Ada, E042, "system__file_io_E");
27280
27281       E006 : Boolean;
27282       pragma Import (Ada, E006, "ada__text_io_E");
27283
27284       --  Set_Globals is a library routine that stores away the
27285       --  value of the indicated set of global values in global
27286       --  variables within the library.
27287
27288       procedure Set_Globals
27289         (Main_Priority            : Integer;
27290          Time_Slice_Value         : Integer;
27291          WC_Encoding              : Character;
27292          Locking_Policy           : Character;
27293          Queuing_Policy           : Character;
27294          Task_Dispatching_Policy  : Character;
27295          Adafinal                 : System.Address;
27296          Unreserve_All_Interrupts : Integer;
27297          Exception_Tracebacks     : Integer);
27298 @findex __gnat_set_globals
27299       pragma Import (C, Set_Globals, "__gnat_set_globals");
27300
27301       --  SDP_Table_Build is a library routine used to build the
27302       --  exception tables. See unit Ada.Exceptions in files
27303       --  a-except.ads/adb for full details of how zero cost
27304       --  exception handling works. This procedure, the call to
27305       --  it, and the two following tables are all omitted if the
27306       --  build is in longjmp/setjmp exception mode.
27307
27308 @findex SDP_Table_Build
27309 @findex Zero Cost Exceptions
27310       procedure SDP_Table_Build
27311         (SDP_Addresses   : System.Address;
27312          SDP_Count       : Natural;
27313          Elab_Addresses  : System.Address;
27314          Elab_Addr_Count : Natural);
27315       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27316
27317       --  Table of Unit_Exception_Table addresses. Used for zero
27318       --  cost exception handling to build the top level table.
27319
27320       ST : aliased constant array (1 .. 23) of System.Address := (
27321         Hello'UET_Address,
27322         Ada.Text_Io'UET_Address,
27323         Ada.Exceptions'UET_Address,
27324         Gnat.Heap_Sort_A'UET_Address,
27325         System.Exception_Table'UET_Address,
27326         System.Machine_State_Operations'UET_Address,
27327         System.Secondary_Stack'UET_Address,
27328         System.Parameters'UET_Address,
27329         System.Soft_Links'UET_Address,
27330         System.Stack_Checking'UET_Address,
27331         System.Traceback'UET_Address,
27332         Ada.Streams'UET_Address,
27333         Ada.Tags'UET_Address,
27334         System.String_Ops'UET_Address,
27335         Interfaces.C_Streams'UET_Address,
27336         System.File_Io'UET_Address,
27337         Ada.Finalization'UET_Address,
27338         System.Finalization_Root'UET_Address,
27339         System.Finalization_Implementation'UET_Address,
27340         System.String_Ops_Concat_3'UET_Address,
27341         System.Stream_Attributes'UET_Address,
27342         System.File_Control_Block'UET_Address,
27343         Ada.Finalization.List_Controller'UET_Address);
27344
27345       --  Table of addresses of elaboration routines. Used for
27346       --  zero cost exception handling to make sure these
27347       --  addresses are included in the top level procedure
27348       --  address table.
27349
27350       EA : aliased constant array (1 .. 23) of System.Address := (
27351         adainit'Code_Address,
27352         Do_Finalize'Code_Address,
27353         Ada.Exceptions'Elab_Spec'Address,
27354         System.Exceptions'Elab_Spec'Address,
27355         Interfaces.C_Streams'Elab_Spec'Address,
27356         System.Exception_Table'Elab_Body'Address,
27357         Ada.Io_Exceptions'Elab_Spec'Address,
27358         System.Stack_Checking'Elab_Spec'Address,
27359         System.Soft_Links'Elab_Body'Address,
27360         System.Secondary_Stack'Elab_Body'Address,
27361         Ada.Tags'Elab_Spec'Address,
27362         Ada.Tags'Elab_Body'Address,
27363         Ada.Streams'Elab_Spec'Address,
27364         System.Finalization_Root'Elab_Spec'Address,
27365         Ada.Exceptions'Elab_Body'Address,
27366         System.Finalization_Implementation'Elab_Spec'Address,
27367         System.Finalization_Implementation'Elab_Body'Address,
27368         Ada.Finalization'Elab_Spec'Address,
27369         Ada.Finalization.List_Controller'Elab_Spec'Address,
27370         System.File_Control_Block'Elab_Spec'Address,
27371         System.File_Io'Elab_Body'Address,
27372         Ada.Text_Io'Elab_Spec'Address,
27373         Ada.Text_Io'Elab_Body'Address);
27374
27375    --  Start of processing for adainit
27376
27377    begin
27378
27379       --  Call SDP_Table_Build to build the top level procedure
27380       --  table for zero cost exception handling (omitted in
27381       --  longjmp/setjmp mode).
27382
27383       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27384
27385       --  Call Set_Globals to record various information for
27386       --  this partition.  The values are derived by the binder
27387       --  from information stored in the ali files by the compiler.
27388
27389 @findex __gnat_set_globals
27390       Set_Globals
27391         (Main_Priority            => -1,
27392          --  Priority of main program, -1 if no pragma Priority used
27393
27394          Time_Slice_Value         => -1,
27395          --  Time slice from Time_Slice pragma, -1 if none used
27396
27397          WC_Encoding              => 'b',
27398          --  Wide_Character encoding used, default is brackets
27399
27400          Locking_Policy           => ' ',
27401          --  Locking_Policy used, default of space means not
27402          --  specified, otherwise it is the first character of
27403          --  the policy name.
27404
27405          Queuing_Policy           => ' ',
27406          --  Queuing_Policy used, default of space means not
27407          --  specified, otherwise it is the first character of
27408          --  the policy name.
27409
27410          Task_Dispatching_Policy  => ' ',
27411          --  Task_Dispatching_Policy used, default of space means
27412          --  not specified, otherwise first character of the
27413          --  policy name.
27414
27415          Adafinal                 => System.Null_Address,
27416          --  Address of Adafinal routine, not used anymore
27417
27418          Unreserve_All_Interrupts => 0,
27419          --  Set true if pragma Unreserve_All_Interrupts was used
27420
27421          Exception_Tracebacks     => 0);
27422          --  Indicates if exception tracebacks are enabled
27423
27424       Elab_Final_Code := 1;
27425
27426       --  Now we have the elaboration calls for all units in the partition.
27427       --  The Elab_Spec and Elab_Body attributes generate references to the
27428       --  implicit elaboration procedures generated by the compiler for
27429       --  each unit that requires elaboration.
27430
27431       if not E040 then
27432          Interfaces.C_Streams'Elab_Spec;
27433       end if;
27434       E040 := True;
27435       if not E008 then
27436          Ada.Exceptions'Elab_Spec;
27437       end if;
27438       if not E014 then
27439          System.Exception_Table'Elab_Body;
27440          E014 := True;
27441       end if;
27442       if not E053 then
27443          Ada.Io_Exceptions'Elab_Spec;
27444          E053 := True;
27445       end if;
27446       if not E017 then
27447          System.Exceptions'Elab_Spec;
27448          E017 := True;
27449       end if;
27450       if not E030 then
27451          System.Stack_Checking'Elab_Spec;
27452       end if;
27453       if not E028 then
27454          System.Soft_Links'Elab_Body;
27455          E028 := True;
27456       end if;
27457       E030 := True;
27458       if not E024 then
27459          System.Secondary_Stack'Elab_Body;
27460          E024 := True;
27461       end if;
27462       if not E035 then
27463          Ada.Tags'Elab_Spec;
27464       end if;
27465       if not E035 then
27466          Ada.Tags'Elab_Body;
27467          E035 := True;
27468       end if;
27469       if not E033 then
27470          Ada.Streams'Elab_Spec;
27471          E033 := True;
27472       end if;
27473       if not E046 then
27474          System.Finalization_Root'Elab_Spec;
27475       end if;
27476       E046 := True;
27477       if not E008 then
27478          Ada.Exceptions'Elab_Body;
27479          E008 := True;
27480       end if;
27481       if not E048 then
27482          System.Finalization_Implementation'Elab_Spec;
27483       end if;
27484       if not E048 then
27485          System.Finalization_Implementation'Elab_Body;
27486          E048 := True;
27487       end if;
27488       if not E044 then
27489          Ada.Finalization'Elab_Spec;
27490       end if;
27491       E044 := True;
27492       if not E057 then
27493          Ada.Finalization.List_Controller'Elab_Spec;
27494       end if;
27495       E057 := True;
27496       if not E055 then
27497          System.File_Control_Block'Elab_Spec;
27498          E055 := True;
27499       end if;
27500       if not E042 then
27501          System.File_Io'Elab_Body;
27502          E042 := True;
27503       end if;
27504       if not E006 then
27505          Ada.Text_Io'Elab_Spec;
27506       end if;
27507       if not E006 then
27508          Ada.Text_Io'Elab_Body;
27509          E006 := True;
27510       end if;
27511
27512       Elab_Final_Code := 0;
27513    end adainit;
27514
27515    --------------
27516    -- adafinal --
27517    --------------
27518
27519 @findex adafinal
27520    procedure adafinal is
27521    begin
27522       Do_Finalize;
27523    end adafinal;
27524
27525    ----------
27526    -- main --
27527    ----------
27528
27529    --  main is actually a function, as in the ANSI C standard,
27530    --  defined to return the exit status. The three parameters
27531    --  are the argument count, argument values and environment
27532    --  pointer.
27533
27534 @findex Main Program
27535    function main
27536      (argc : Integer;
27537       argv : System.Address;
27538       envp : System.Address)
27539       return Integer
27540    is
27541       --  The initialize routine performs low level system
27542       --  initialization using a standard library routine which
27543       --  sets up signal handling and performs any other
27544       --  required setup. The routine can be found in file
27545       --  a-init.c.
27546
27547 @findex __gnat_initialize
27548       procedure initialize;
27549       pragma Import (C, initialize, "__gnat_initialize");
27550
27551       --  The finalize routine performs low level system
27552       --  finalization using a standard library routine. The
27553       --  routine is found in file a-final.c and in the standard
27554       --  distribution is a dummy routine that does nothing, so
27555       --  really this is a hook for special user finalization.
27556
27557 @findex __gnat_finalize
27558       procedure finalize;
27559       pragma Import (C, finalize, "__gnat_finalize");
27560
27561       --  We get to the main program of the partition by using
27562       --  pragma Import because if we try to with the unit and
27563       --  call it Ada style, then not only do we waste time
27564       --  recompiling it, but also, we don't really know the right
27565       --  switches (e.g.@: identifier character set) to be used
27566       --  to compile it.
27567
27568       procedure Ada_Main_Program;
27569       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27570
27571    --  Start of processing for main
27572
27573    begin
27574       --  Save global variables
27575
27576       gnat_argc := argc;
27577       gnat_argv := argv;
27578       gnat_envp := envp;
27579
27580       --  Call low level system initialization
27581
27582       Initialize;
27583
27584       --  Call our generated Ada initialization routine
27585
27586       adainit;
27587
27588       --  This is the point at which we want the debugger to get
27589       --  control
27590
27591       Break_Start;
27592
27593       --  Now we call the main program of the partition
27594
27595       Ada_Main_Program;
27596
27597       --  Perform Ada finalization
27598
27599       adafinal;
27600
27601       --  Perform low level system finalization
27602
27603       Finalize;
27604
27605       --  Return the proper exit status
27606       return (gnat_exit_status);
27607    end;
27608
27609 --  This section is entirely comments, so it has no effect on the
27610 --  compilation of the Ada_Main package. It provides the list of
27611 --  object files and linker options, as well as some standard
27612 --  libraries needed for the link. The gnatlink utility parses
27613 --  this b~hello.adb file to read these comment lines to generate
27614 --  the appropriate command line arguments for the call to the
27615 --  system linker. The BEGIN/END lines are used for sentinels for
27616 --  this parsing operation.
27617
27618 --  The exact file names will of course depend on the environment,
27619 --  host/target and location of files on the host system.
27620
27621 @findex Object file list
27622 -- BEGIN Object file/option list
27623    --   ./hello.o
27624    --   -L./
27625    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27626    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27627 -- END Object file/option list
27628
27629 end ada_main;
27630 @end smallexample
27631
27632 @noindent
27633 The Ada code in the above example is exactly what is generated by the
27634 binder. We have added comments to more clearly indicate the function
27635 of each part of the generated @code{Ada_Main} package.
27636
27637 The code is standard Ada in all respects, and can be processed by any
27638 tools that handle Ada. In particular, it is possible to use the debugger
27639 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27640 suppose that for reasons that you do not understand, your program is crashing
27641 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27642 you can place a breakpoint on the call:
27643
27644 @smallexample @c ada
27645 Ada.Text_Io'Elab_Body;
27646 @end smallexample
27647
27648 @noindent
27649 and trace the elaboration routine for this package to find out where
27650 the problem might be (more usually of course you would be debugging
27651 elaboration code in your own application).
27652
27653 @node Elaboration Order Handling in GNAT
27654 @appendix Elaboration Order Handling in GNAT
27655 @cindex Order of elaboration
27656 @cindex Elaboration control
27657
27658 @menu
27659 * Elaboration Code::
27660 * Checking the Elaboration Order::
27661 * Controlling the Elaboration Order::
27662 * Controlling Elaboration in GNAT - Internal Calls::
27663 * Controlling Elaboration in GNAT - External Calls::
27664 * Default Behavior in GNAT - Ensuring Safety::
27665 * Treatment of Pragma Elaborate::
27666 * Elaboration Issues for Library Tasks::
27667 * Mixing Elaboration Models::
27668 * What to Do If the Default Elaboration Behavior Fails::
27669 * Elaboration for Access-to-Subprogram Values::
27670 * Summary of Procedures for Elaboration Control::
27671 * Other Elaboration Order Considerations::
27672 @end menu
27673
27674 @noindent
27675 This chapter describes the handling of elaboration code in Ada and
27676 in GNAT, and discusses how the order of elaboration of program units can
27677 be controlled in GNAT, either automatically or with explicit programming
27678 features.
27679
27680 @node Elaboration Code
27681 @section Elaboration Code
27682
27683 @noindent
27684 Ada provides rather general mechanisms for executing code at elaboration
27685 time, that is to say before the main program starts executing. Such code arises
27686 in three contexts:
27687
27688 @table @asis
27689 @item Initializers for variables.
27690 Variables declared at the library level, in package specs or bodies, can
27691 require initialization that is performed at elaboration time, as in:
27692 @smallexample @c ada
27693 @cartouche
27694 Sqrt_Half : Float := Sqrt (0.5);
27695 @end cartouche
27696 @end smallexample
27697
27698 @item Package initialization code
27699 Code in a @code{BEGIN-END} section at the outer level of a package body is
27700 executed as part of the package body elaboration code.
27701
27702 @item Library level task allocators
27703 Tasks that are declared using task allocators at the library level
27704 start executing immediately and hence can execute at elaboration time.
27705 @end table
27706
27707 @noindent
27708 Subprogram calls are possible in any of these contexts, which means that
27709 any arbitrary part of the program may be executed as part of the elaboration
27710 code. It is even possible to write a program which does all its work at
27711 elaboration time, with a null main program, although stylistically this
27712 would usually be considered an inappropriate way to structure
27713 a program.
27714
27715 An important concern arises in the context of elaboration code:
27716 we have to be sure that it is executed in an appropriate order. What we
27717 have is a series of elaboration code sections, potentially one section
27718 for each unit in the program. It is important that these execute
27719 in the correct order. Correctness here means that, taking the above
27720 example of the declaration of @code{Sqrt_Half},
27721 if some other piece of
27722 elaboration code references @code{Sqrt_Half},
27723 then it must run after the
27724 section of elaboration code that contains the declaration of
27725 @code{Sqrt_Half}.
27726
27727 There would never be any order of elaboration problem if we made a rule
27728 that whenever you @code{with} a unit, you must elaborate both the spec and body
27729 of that unit before elaborating the unit doing the @code{with}'ing:
27730
27731 @smallexample @c ada
27732 @group
27733 @cartouche
27734 with Unit_1;
27735 package Unit_2 is @dots{}
27736 @end cartouche
27737 @end group
27738 @end smallexample
27739
27740 @noindent
27741 would require that both the body and spec of @code{Unit_1} be elaborated
27742 before the spec of @code{Unit_2}. However, a rule like that would be far too
27743 restrictive. In particular, it would make it impossible to have routines
27744 in separate packages that were mutually recursive.
27745
27746 You might think that a clever enough compiler could look at the actual
27747 elaboration code and determine an appropriate correct order of elaboration,
27748 but in the general case, this is not possible. Consider the following
27749 example.
27750
27751 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27752 that references
27753 the variable @code{Sqrt_1}, which is declared in the elaboration code
27754 of the body of @code{Unit_1}:
27755
27756 @smallexample @c ada
27757 @cartouche
27758 Sqrt_1 : Float := Sqrt (0.1);
27759 @end cartouche
27760 @end smallexample
27761
27762 @noindent
27763 The elaboration code of the body of @code{Unit_1} also contains:
27764
27765 @smallexample @c ada
27766 @group
27767 @cartouche
27768 if expression_1 = 1 then
27769    Q := Unit_2.Func_2;
27770 end if;
27771 @end cartouche
27772 @end group
27773 @end smallexample
27774
27775 @noindent
27776 @code{Unit_2} is exactly parallel,
27777 it has a procedure @code{Func_2} that references
27778 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27779 the body @code{Unit_2}:
27780
27781 @smallexample @c ada
27782 @cartouche
27783 Sqrt_2 : Float := Sqrt (0.1);
27784 @end cartouche
27785 @end smallexample
27786
27787 @noindent
27788 The elaboration code of the body of @code{Unit_2} also contains:
27789
27790 @smallexample @c ada
27791 @group
27792 @cartouche
27793 if expression_2 = 2 then
27794    Q := Unit_1.Func_1;
27795 end if;
27796 @end cartouche
27797 @end group
27798 @end smallexample
27799
27800 @noindent
27801 Now the question is, which of the following orders of elaboration is
27802 acceptable:
27803
27804 @smallexample
27805 @group
27806 Spec of Unit_1
27807 Spec of Unit_2
27808 Body of Unit_1
27809 Body of Unit_2
27810 @end group
27811 @end smallexample
27812
27813 @noindent
27814 or
27815
27816 @smallexample
27817 @group
27818 Spec of Unit_2
27819 Spec of Unit_1
27820 Body of Unit_2
27821 Body of Unit_1
27822 @end group
27823 @end smallexample
27824
27825 @noindent
27826 If you carefully analyze the flow here, you will see that you cannot tell
27827 at compile time the answer to this question.
27828 If @code{expression_1} is not equal to 1,
27829 and @code{expression_2} is not equal to 2,
27830 then either order is acceptable, because neither of the function calls is
27831 executed. If both tests evaluate to true, then neither order is acceptable
27832 and in fact there is no correct order.
27833
27834 If one of the two expressions is true, and the other is false, then one
27835 of the above orders is correct, and the other is incorrect. For example,
27836 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27837 then the call to @code{Func_1}
27838 will occur, but not the call to @code{Func_2.}
27839 This means that it is essential
27840 to elaborate the body of @code{Unit_1} before
27841 the body of @code{Unit_2}, so the first
27842 order of elaboration is correct and the second is wrong.
27843
27844 By making @code{expression_1} and @code{expression_2}
27845 depend on input data, or perhaps
27846 the time of day, we can make it impossible for the compiler or binder
27847 to figure out which of these expressions will be true, and hence it
27848 is impossible to guarantee a safe order of elaboration at run time.
27849
27850 @node Checking the Elaboration Order
27851 @section Checking the Elaboration Order
27852
27853 @noindent
27854 In some languages that involve the same kind of elaboration problems,
27855 e.g.@: Java and C++, the programmer is expected to worry about these
27856 ordering problems himself, and it is common to
27857 write a program in which an incorrect elaboration order  gives
27858 surprising results, because it references variables before they
27859 are initialized.
27860 Ada is designed to be a safe language, and a programmer-beware approach is
27861 clearly not sufficient. Consequently, the language provides three lines
27862 of defense:
27863
27864 @table @asis
27865 @item Standard rules
27866 Some standard rules restrict the possible choice of elaboration
27867 order. In particular, if you @code{with} a unit, then its spec is always
27868 elaborated before the unit doing the @code{with}. Similarly, a parent
27869 spec is always elaborated before the child spec, and finally
27870 a spec is always elaborated before its corresponding body.
27871
27872 @item Dynamic elaboration checks
27873 @cindex Elaboration checks
27874 @cindex Checks, elaboration
27875 Dynamic checks are made at run time, so that if some entity is accessed
27876 before it is elaborated (typically  by means of a subprogram call)
27877 then the exception (@code{Program_Error}) is raised.
27878
27879 @item Elaboration control
27880 Facilities are provided for the programmer to specify the desired order
27881 of elaboration.
27882 @end table
27883
27884 Let's look at these facilities in more detail. First, the rules for
27885 dynamic checking. One possible rule would be simply to say that the
27886 exception is raised if you access a variable which has not yet been
27887 elaborated. The trouble with this approach is that it could require
27888 expensive checks on every variable reference. Instead Ada has two
27889 rules which are a little more restrictive, but easier to check, and
27890 easier to state:
27891
27892 @table @asis
27893 @item Restrictions on calls
27894 A subprogram can only be called at elaboration time if its body
27895 has been elaborated. The rules for elaboration given above guarantee
27896 that the spec of the subprogram has been elaborated before the
27897 call, but not the body. If this rule is violated, then the
27898 exception @code{Program_Error} is raised.
27899
27900 @item Restrictions on instantiations
27901 A generic unit can only be instantiated if the body of the generic
27902 unit has been elaborated. Again, the rules for elaboration given above
27903 guarantee that the spec of the generic unit has been elaborated
27904 before the instantiation, but not the body. If this rule is
27905 violated, then the exception @code{Program_Error} is raised.
27906 @end table
27907
27908 @noindent
27909 The idea is that if the body has been elaborated, then any variables
27910 it references must have been elaborated; by checking for the body being
27911 elaborated we guarantee that none of its references causes any
27912 trouble. As we noted above, this is a little too restrictive, because a
27913 subprogram that has no non-local references in its body may in fact be safe
27914 to call. However, it really would be unsafe to rely on this, because
27915 it would mean that the caller was aware of details of the implementation
27916 in the body. This goes against the basic tenets of Ada.
27917
27918 A plausible implementation can be described as follows.
27919 A Boolean variable is associated with each subprogram
27920 and each generic unit. This variable is initialized to False, and is set to
27921 True at the point body is elaborated. Every call or instantiation checks the
27922 variable, and raises @code{Program_Error} if the variable is False.
27923
27924 Note that one might think that it would be good enough to have one Boolean
27925 variable for each package, but that would not deal with cases of trying
27926 to call a body in the same package as the call
27927 that has not been elaborated yet.
27928 Of course a compiler may be able to do enough analysis to optimize away
27929 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27930 does such optimizations, but still the easiest conceptual model is to
27931 think of there being one variable per subprogram.
27932
27933 @node Controlling the Elaboration Order
27934 @section Controlling the Elaboration Order
27935
27936 @noindent
27937 In the previous section we discussed the rules in Ada which ensure
27938 that @code{Program_Error} is raised if an incorrect elaboration order is
27939 chosen. This prevents erroneous executions, but we need mechanisms to
27940 specify a correct execution and avoid the exception altogether.
27941 To achieve this, Ada provides a number of features for controlling
27942 the order of elaboration. We discuss these features in this section.
27943
27944 First, there are several ways of indicating to the compiler that a given
27945 unit has no elaboration problems:
27946
27947 @table @asis
27948 @item packages that do not require a body
27949 A library package that does not require a body does not permit
27950 a body (this rule was introduced in Ada 95).
27951 Thus if we have a such a package, as in:
27952
27953 @smallexample @c ada
27954 @group
27955 @cartouche
27956 package Definitions is
27957    generic
27958       type m is new integer;
27959    package Subp is
27960       type a is array (1 .. 10) of m;
27961       type b is array (1 .. 20) of m;
27962    end Subp;
27963 end Definitions;
27964 @end cartouche
27965 @end group
27966 @end smallexample
27967
27968 @noindent
27969 A package that @code{with}'s @code{Definitions} may safely instantiate
27970 @code{Definitions.Subp} because the compiler can determine that there
27971 definitely is no package body to worry about in this case
27972
27973 @item pragma Pure
27974 @cindex pragma Pure
27975 @findex Pure
27976 Places sufficient restrictions on a unit to guarantee that
27977 no call to any subprogram in the unit can result in an
27978 elaboration problem. This means that the compiler does not need
27979 to worry about the point of elaboration of such units, and in
27980 particular, does not need to check any calls to any subprograms
27981 in this unit.
27982
27983 @item pragma Preelaborate
27984 @findex Preelaborate
27985 @cindex pragma Preelaborate
27986 This pragma places slightly less stringent restrictions on a unit than
27987 does pragma Pure,
27988 but these restrictions are still sufficient to ensure that there
27989 are no elaboration problems with any calls to the unit.
27990
27991 @item pragma Elaborate_Body
27992 @findex Elaborate_Body
27993 @cindex pragma Elaborate_Body
27994 This pragma requires that the body of a unit be elaborated immediately
27995 after its spec. Suppose a unit @code{A} has such a pragma,
27996 and unit @code{B} does
27997 a @code{with} of unit @code{A}. Recall that the standard rules require
27998 the spec of unit @code{A}
27999 to be elaborated before the @code{with}'ing unit; given the pragma in
28000 @code{A}, we also know that the body of @code{A}
28001 will be elaborated before @code{B}, so
28002 that calls to @code{A} are safe and do not need a check.
28003 @end table
28004
28005 @noindent
28006 Note that,
28007 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28008 the use of
28009 @code{Elaborate_Body} does not guarantee that the program is
28010 free of elaboration problems, because it may not be possible
28011 to satisfy the requested elaboration order.
28012 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28013 If a programmer
28014 marks @code{Unit_1} as @code{Elaborate_Body},
28015 and not @code{Unit_2,} then the order of
28016 elaboration will be:
28017
28018 @smallexample
28019 @group
28020 Spec of Unit_2
28021 Spec of Unit_1
28022 Body of Unit_1
28023 Body of Unit_2
28024 @end group
28025 @end smallexample
28026
28027 @noindent
28028 Now that means that the call to @code{Func_1} in @code{Unit_2}
28029 need not be checked,
28030 it must be safe. But the call to @code{Func_2} in
28031 @code{Unit_1} may still fail if
28032 @code{Expression_1} is equal to 1,
28033 and the programmer must still take
28034 responsibility for this not being the case.
28035
28036 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28037 eliminated, except for calls entirely within a body, which are
28038 in any case fully under programmer control. However, using the pragma
28039 everywhere is not always possible.
28040 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28041 we marked both of them as having pragma @code{Elaborate_Body}, then
28042 clearly there would be no possible elaboration order.
28043
28044 The above pragmas allow a server to guarantee safe use by clients, and
28045 clearly this is the preferable approach. Consequently a good rule
28046 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28047 and if this is not possible,
28048 mark them as @code{Elaborate_Body} if possible.
28049 As we have seen, there are situations where neither of these
28050 three pragmas can be used.
28051 So we also provide methods for clients to control the
28052 order of elaboration of the servers on which they depend:
28053
28054 @table @asis
28055 @item pragma Elaborate (unit)
28056 @findex Elaborate
28057 @cindex pragma Elaborate
28058 This pragma is placed in the context clause, after a @code{with} clause,
28059 and it requires that the body of the named unit be elaborated before
28060 the unit in which the pragma occurs. The idea is to use this pragma
28061 if the current unit calls at elaboration time, directly or indirectly,
28062 some subprogram in the named unit.
28063
28064 @item pragma Elaborate_All (unit)
28065 @findex Elaborate_All
28066 @cindex pragma Elaborate_All
28067 This is a stronger version of the Elaborate pragma. Consider the
28068 following example:
28069
28070 @smallexample
28071 Unit A @code{with}'s unit B and calls B.Func in elab code
28072 Unit B @code{with}'s unit C, and B.Func calls C.Func
28073 @end smallexample
28074
28075 @noindent
28076 Now if we put a pragma @code{Elaborate (B)}
28077 in unit @code{A}, this ensures that the
28078 body of @code{B} is elaborated before the call, but not the
28079 body of @code{C}, so
28080 the call to @code{C.Func} could still cause @code{Program_Error} to
28081 be raised.
28082
28083 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28084 not only that the body of the named unit be elaborated before the
28085 unit doing the @code{with}, but also the bodies of all units that the
28086 named unit uses, following @code{with} links transitively. For example,
28087 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28088 then it requires
28089 not only that the body of @code{B} be elaborated before @code{A},
28090 but also the
28091 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28092 @end table
28093
28094 @noindent
28095 We are now in a position to give a usage rule in Ada for avoiding
28096 elaboration problems, at least if dynamic dispatching and access to
28097 subprogram values are not used. We will handle these cases separately
28098 later.
28099
28100 The rule is simple. If a unit has elaboration code that can directly or
28101 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28102 a generic package in a @code{with}'ed unit,
28103 then if the @code{with}'ed unit does not have
28104 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28105 a pragma @code{Elaborate_All}
28106 for the @code{with}'ed unit. By following this rule a client is
28107 assured that calls can be made without risk of an exception.
28108
28109 For generic subprogram instantiations, the rule can be relaxed to
28110 require only a pragma @code{Elaborate} since elaborating the body
28111 of a subprogram cannot cause any transitive elaboration (we are
28112 not calling the subprogram in this case, just elaborating its
28113 declaration).
28114
28115 If this rule is not followed, then a program may be in one of four
28116 states:
28117
28118 @table @asis
28119 @item No order exists
28120 No order of elaboration exists which follows the rules, taking into
28121 account any @code{Elaborate}, @code{Elaborate_All},
28122 or @code{Elaborate_Body} pragmas. In
28123 this case, an Ada compiler must diagnose the situation at bind
28124 time, and refuse to build an executable program.
28125
28126 @item One or more orders exist, all incorrect
28127 One or more acceptable elaboration orders exist, and all of them
28128 generate an elaboration order problem. In this case, the binder
28129 can build an executable program, but @code{Program_Error} will be raised
28130 when the program is run.
28131
28132 @item Several orders exist, some right, some incorrect
28133 One or more acceptable elaboration orders exists, and some of them
28134 work, and some do not. The programmer has not controlled
28135 the order of elaboration, so the binder may or may not pick one of
28136 the correct orders, and the program may or may not raise an
28137 exception when it is run. This is the worst case, because it means
28138 that the program may fail when moved to another compiler, or even
28139 another version of the same compiler.
28140
28141 @item One or more orders exists, all correct
28142 One ore more acceptable elaboration orders exist, and all of them
28143 work. In this case the program runs successfully. This state of
28144 affairs can be guaranteed by following the rule we gave above, but
28145 may be true even if the rule is not followed.
28146 @end table
28147
28148 @noindent
28149 Note that one additional advantage of following our rules on the use
28150 of @code{Elaborate} and @code{Elaborate_All}
28151 is that the program continues to stay in the ideal (all orders OK) state
28152 even if maintenance
28153 changes some bodies of some units. Conversely, if a program that does
28154 not follow this rule happens to be safe at some point, this state of affairs
28155 may deteriorate silently as a result of maintenance changes.
28156
28157 You may have noticed that the above discussion did not mention
28158 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28159 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28160 code in the body makes calls to some other unit, so it is still necessary
28161 to use @code{Elaborate_All} on such units.
28162
28163 @node Controlling Elaboration in GNAT - Internal Calls
28164 @section Controlling Elaboration in GNAT - Internal Calls
28165
28166 @noindent
28167 In the case of internal calls, i.e., calls within a single package, the
28168 programmer has full control over the order of elaboration, and it is up
28169 to the programmer to elaborate declarations in an appropriate order. For
28170 example writing:
28171
28172 @smallexample @c ada
28173 @group
28174 @cartouche
28175 function One return Float;
28176
28177 Q : Float := One;
28178
28179 function One return Float is
28180 begin
28181      return 1.0;
28182 end One;
28183 @end cartouche
28184 @end group
28185 @end smallexample
28186
28187 @noindent
28188 will obviously raise @code{Program_Error} at run time, because function
28189 One will be called before its body is elaborated. In this case GNAT will
28190 generate a warning that the call will raise @code{Program_Error}:
28191
28192 @smallexample
28193 @group
28194 @cartouche
28195  1. procedure y is
28196  2.    function One return Float;
28197  3.
28198  4.    Q : Float := One;
28199                     |
28200     >>> warning: cannot call "One" before body is elaborated
28201     >>> warning: Program_Error will be raised at run time
28202
28203  5.
28204  6.    function One return Float is
28205  7.    begin
28206  8.         return 1.0;
28207  9.    end One;
28208 10.
28209 11. begin
28210 12.    null;
28211 13. end;
28212 @end cartouche
28213 @end group
28214 @end smallexample
28215
28216 @noindent
28217 Note that in this particular case, it is likely that the call is safe, because
28218 the function @code{One} does not access any global variables.
28219 Nevertheless in Ada, we do not want the validity of the check to depend on
28220 the contents of the body (think about the separate compilation case), so this
28221 is still wrong, as we discussed in the previous sections.
28222
28223 The error is easily corrected by rearranging the declarations so that the
28224 body of @code{One} appears before the declaration containing the call
28225 (note that in Ada 95 and Ada 2005,
28226 declarations can appear in any order, so there is no restriction that
28227 would prevent this reordering, and if we write:
28228
28229 @smallexample @c ada
28230 @group
28231 @cartouche
28232 function One return Float;
28233
28234 function One return Float is
28235 begin
28236      return 1.0;
28237 end One;
28238
28239 Q : Float := One;
28240 @end cartouche
28241 @end group
28242 @end smallexample
28243
28244 @noindent
28245 then all is well, no warning is generated, and no
28246 @code{Program_Error} exception
28247 will be raised.
28248 Things are more complicated when a chain of subprograms is executed:
28249
28250 @smallexample @c ada
28251 @group
28252 @cartouche
28253 function A return Integer;
28254 function B return Integer;
28255 function C return Integer;
28256
28257 function B return Integer is begin return A; end;
28258 function C return Integer is begin return B; end;
28259
28260 X : Integer := C;
28261
28262 function A return Integer is begin return 1; end;
28263 @end cartouche
28264 @end group
28265 @end smallexample
28266
28267 @noindent
28268 Now the call to @code{C}
28269 at elaboration time in the declaration of @code{X} is correct, because
28270 the body of @code{C} is already elaborated,
28271 and the call to @code{B} within the body of
28272 @code{C} is correct, but the call
28273 to @code{A} within the body of @code{B} is incorrect, because the body
28274 of @code{A} has not been elaborated, so @code{Program_Error}
28275 will be raised on the call to @code{A}.
28276 In this case GNAT will generate a
28277 warning that @code{Program_Error} may be
28278 raised at the point of the call. Let's look at the warning:
28279
28280 @smallexample
28281 @group
28282 @cartouche
28283  1. procedure x is
28284  2.    function A return Integer;
28285  3.    function B return Integer;
28286  4.    function C return Integer;
28287  5.
28288  6.    function B return Integer is begin return A; end;
28289                                                     |
28290     >>> warning: call to "A" before body is elaborated may
28291                  raise Program_Error
28292     >>> warning: "B" called at line 7
28293     >>> warning: "C" called at line 9
28294
28295  7.    function C return Integer is begin return B; end;
28296  8.
28297  9.    X : Integer := C;
28298 10.
28299 11.    function A return Integer is begin return 1; end;
28300 12.
28301 13. begin
28302 14.    null;
28303 15. end;
28304 @end cartouche
28305 @end group
28306 @end smallexample
28307
28308 @noindent
28309 Note that the message here says ``may raise'', instead of the direct case,
28310 where the message says ``will be raised''. That's because whether
28311 @code{A} is
28312 actually called depends in general on run-time flow of control.
28313 For example, if the body of @code{B} said
28314
28315 @smallexample @c ada
28316 @group
28317 @cartouche
28318 function B return Integer is
28319 begin
28320    if some-condition-depending-on-input-data then
28321       return A;
28322    else
28323       return 1;
28324    end if;
28325 end B;
28326 @end cartouche
28327 @end group
28328 @end smallexample
28329
28330 @noindent
28331 then we could not know until run time whether the incorrect call to A would
28332 actually occur, so @code{Program_Error} might
28333 or might not be raised. It is possible for a compiler to
28334 do a better job of analyzing bodies, to
28335 determine whether or not @code{Program_Error}
28336 might be raised, but it certainly
28337 couldn't do a perfect job (that would require solving the halting problem
28338 and is provably impossible), and because this is a warning anyway, it does
28339 not seem worth the effort to do the analysis. Cases in which it
28340 would be relevant are rare.
28341
28342 In practice, warnings of either of the forms given
28343 above will usually correspond to
28344 real errors, and should be examined carefully and eliminated.
28345 In the rare case where a warning is bogus, it can be suppressed by any of
28346 the following methods:
28347
28348 @itemize @bullet
28349 @item
28350 Compile with the @option{-gnatws} switch set
28351
28352 @item
28353 Suppress @code{Elaboration_Check} for the called subprogram
28354
28355 @item
28356 Use pragma @code{Warnings_Off} to turn warnings off for the call
28357 @end itemize
28358
28359 @noindent
28360 For the internal elaboration check case,
28361 GNAT by default generates the
28362 necessary run-time checks to ensure
28363 that @code{Program_Error} is raised if any
28364 call fails an elaboration check. Of course this can only happen if a
28365 warning has been issued as described above. The use of pragma
28366 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28367 some of these checks, meaning that it may be possible (but is not
28368 guaranteed) for a program to be able to call a subprogram whose body
28369 is not yet elaborated, without raising a @code{Program_Error} exception.
28370
28371 @node Controlling Elaboration in GNAT - External Calls
28372 @section Controlling Elaboration in GNAT - External Calls
28373
28374 @noindent
28375 The previous section discussed the case in which the execution of a
28376 particular thread of elaboration code occurred entirely within a
28377 single unit. This is the easy case to handle, because a programmer
28378 has direct and total control over the order of elaboration, and
28379 furthermore, checks need only be generated in cases which are rare
28380 and which the compiler can easily detect.
28381 The situation is more complex when separate compilation is taken into account.
28382 Consider the following:
28383
28384 @smallexample @c ada
28385 @cartouche
28386 @group
28387 package Math is
28388    function Sqrt (Arg : Float) return Float;
28389 end Math;
28390
28391 package body Math is
28392    function Sqrt (Arg : Float) return Float is
28393    begin
28394          @dots{}
28395    end Sqrt;
28396 end Math;
28397 @end group
28398 @group
28399 with Math;
28400 package Stuff is
28401    X : Float := Math.Sqrt (0.5);
28402 end Stuff;
28403
28404 with Stuff;
28405 procedure Main is
28406 begin
28407    @dots{}
28408 end Main;
28409 @end group
28410 @end cartouche
28411 @end smallexample
28412
28413 @noindent
28414 where @code{Main} is the main program. When this program is executed, the
28415 elaboration code must first be executed, and one of the jobs of the
28416 binder is to determine the order in which the units of a program are
28417 to be elaborated. In this case we have four units: the spec and body
28418 of @code{Math},
28419 the spec of @code{Stuff} and the body of @code{Main}).
28420 In what order should the four separate sections of elaboration code
28421 be executed?
28422
28423 There are some restrictions in the order of elaboration that the binder
28424 can choose. In particular, if unit U has a @code{with}
28425 for a package @code{X}, then you
28426 are assured that the spec of @code{X}
28427 is elaborated before U , but you are
28428 not assured that the body of @code{X}
28429 is elaborated before U.
28430 This means that in the above case, the binder is allowed to choose the
28431 order:
28432
28433 @smallexample
28434 spec of Math
28435 spec of Stuff
28436 body of Math
28437 body of Main
28438 @end smallexample
28439
28440 @noindent
28441 but that's not good, because now the call to @code{Math.Sqrt}
28442 that happens during
28443 the elaboration of the @code{Stuff}
28444 spec happens before the body of @code{Math.Sqrt} is
28445 elaborated, and hence causes @code{Program_Error} exception to be raised.
28446 At first glance, one might say that the binder is misbehaving, because
28447 obviously you want to elaborate the body of something you @code{with}
28448 first, but
28449 that is not a general rule that can be followed in all cases. Consider
28450
28451 @smallexample @c ada
28452 @group
28453 @cartouche
28454 package X is @dots{}
28455
28456 package Y is @dots{}
28457
28458 with X;
28459 package body Y is @dots{}
28460
28461 with Y;
28462 package body X is @dots{}
28463 @end cartouche
28464 @end group
28465 @end smallexample
28466
28467 @noindent
28468 This is a common arrangement, and, apart from the order of elaboration
28469 problems that might arise in connection with elaboration code, this works fine.
28470 A rule that says that you must first elaborate the body of anything you
28471 @code{with} cannot work in this case:
28472 the body of @code{X} @code{with}'s @code{Y},
28473 which means you would have to
28474 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28475 which means
28476 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28477 loop that cannot be broken.
28478
28479 It is true that the binder can in many cases guess an order of elaboration
28480 that is unlikely to cause a @code{Program_Error}
28481 exception to be raised, and it tries to do so (in the
28482 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28483 by default
28484 elaborate the body of @code{Math} right after its spec, so all will be well).
28485
28486 However, a program that blindly relies on the binder to be helpful can
28487 get into trouble, as we discussed in the previous sections, so
28488 GNAT
28489 provides a number of facilities for assisting the programmer in
28490 developing programs that are robust with respect to elaboration order.
28491
28492 @node Default Behavior in GNAT - Ensuring Safety
28493 @section Default Behavior in GNAT - Ensuring Safety
28494
28495 @noindent
28496 The default behavior in GNAT ensures elaboration safety. In its
28497 default mode GNAT implements the
28498 rule we previously described as the right approach. Let's restate it:
28499
28500 @itemize
28501 @item
28502 @emph{If a unit has elaboration code that can directly or indirectly make a
28503 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28504 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28505 does not have pragma @code{Pure} or
28506 @code{Preelaborate}, then the client should have an
28507 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28508
28509 @emph{In the case of instantiating a generic subprogram, it is always
28510 sufficient to have only an @code{Elaborate} pragma for the
28511 @code{with}'ed unit.}
28512 @end itemize
28513
28514 @noindent
28515 By following this rule a client is assured that calls and instantiations
28516 can be made without risk of an exception.
28517
28518 In this mode GNAT traces all calls that are potentially made from
28519 elaboration code, and puts in any missing implicit @code{Elaborate}
28520 and @code{Elaborate_All} pragmas.
28521 The advantage of this approach is that no elaboration problems
28522 are possible if the binder can find an elaboration order that is
28523 consistent with these implicit @code{Elaborate} and
28524 @code{Elaborate_All} pragmas. The
28525 disadvantage of this approach is that no such order may exist.
28526
28527 If the binder does not generate any diagnostics, then it means that it has
28528 found an elaboration order that is guaranteed to be safe. However, the binder
28529 may still be relying on implicitly generated @code{Elaborate} and
28530 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28531 guaranteed.
28532
28533 If it is important to guarantee portability, then the compilations should
28534 use the
28535 @option{-gnatwl}
28536 (warn on elaboration problems) switch. This will cause warning messages
28537 to be generated indicating the missing @code{Elaborate} and
28538 @code{Elaborate_All} pragmas.
28539 Consider the following source program:
28540
28541 @smallexample @c ada
28542 @group
28543 @cartouche
28544 with k;
28545 package j is
28546   m : integer := k.r;
28547 end;
28548 @end cartouche
28549 @end group
28550 @end smallexample
28551
28552 @noindent
28553 where it is clear that there
28554 should be a pragma @code{Elaborate_All}
28555 for unit @code{k}. An implicit pragma will be generated, and it is
28556 likely that the binder will be able to honor it. However, if you want
28557 to port this program to some other Ada compiler than GNAT.
28558 it is safer to include the pragma explicitly in the source. If this
28559 unit is compiled with the
28560 @option{-gnatwl}
28561 switch, then the compiler outputs a warning:
28562
28563 @smallexample
28564 @group
28565 @cartouche
28566 1. with k;
28567 2. package j is
28568 3.   m : integer := k.r;
28569                      |
28570    >>> warning: call to "r" may raise Program_Error
28571    >>> warning: missing pragma Elaborate_All for "k"
28572
28573 4. end;
28574 @end cartouche
28575 @end group
28576 @end smallexample
28577
28578 @noindent
28579 and these warnings can be used as a guide for supplying manually
28580 the missing pragmas. It is usually a bad idea to use this warning
28581 option during development. That's because it will warn you when
28582 you need to put in a pragma, but cannot warn you when it is time
28583 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28584 unnecessary dependencies and even false circularities.
28585
28586 This default mode is more restrictive than the Ada Reference
28587 Manual, and it is possible to construct programs which will compile
28588 using the dynamic model described there, but will run into a
28589 circularity using the safer static model we have described.
28590
28591 Of course any Ada compiler must be able to operate in a mode
28592 consistent with the requirements of the Ada Reference Manual,
28593 and in particular must have the capability of implementing the
28594 standard dynamic model of elaboration with run-time checks.
28595
28596 In GNAT, this standard mode can be achieved either by the use of
28597 the @option{-gnatE} switch on the compiler (@command{gcc} or
28598 @command{gnatmake}) command, or by the use of the configuration pragma:
28599
28600 @smallexample @c ada
28601 pragma Elaboration_Checks (DYNAMIC);
28602 @end smallexample
28603
28604 @noindent
28605 Either approach will cause the unit affected to be compiled using the
28606 standard dynamic run-time elaboration checks described in the Ada
28607 Reference Manual. The static model is generally preferable, since it
28608 is clearly safer to rely on compile and link time checks rather than
28609 run-time checks. However, in the case of legacy code, it may be
28610 difficult to meet the requirements of the static model. This
28611 issue is further discussed in
28612 @ref{What to Do If the Default Elaboration Behavior Fails}.
28613
28614 Note that the static model provides a strict subset of the allowed
28615 behavior and programs of the Ada Reference Manual, so if you do
28616 adhere to the static model and no circularities exist,
28617 then you are assured that your program will
28618 work using the dynamic model, providing that you remove any
28619 pragma Elaborate statements from the source.
28620
28621 @node Treatment of Pragma Elaborate
28622 @section Treatment of Pragma Elaborate
28623 @cindex Pragma Elaborate
28624
28625 @noindent
28626 The use of @code{pragma Elaborate}
28627 should generally be avoided in Ada 95 and Ada 2005 programs,
28628 since there is no guarantee that transitive calls
28629 will be properly handled. Indeed at one point, this pragma was placed
28630 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28631
28632 Now that's a bit restrictive. In practice, the case in which
28633 @code{pragma Elaborate} is useful is when the caller knows that there
28634 are no transitive calls, or that the called unit contains all necessary
28635 transitive @code{pragma Elaborate} statements, and legacy code often
28636 contains such uses.
28637
28638 Strictly speaking the static mode in GNAT should ignore such pragmas,
28639 since there is no assurance at compile time that the necessary safety
28640 conditions are met. In practice, this would cause GNAT to be incompatible
28641 with correctly written Ada 83 code that had all necessary
28642 @code{pragma Elaborate} statements in place. Consequently, we made the
28643 decision that GNAT in its default mode will believe that if it encounters
28644 a @code{pragma Elaborate} then the programmer knows what they are doing,
28645 and it will trust that no elaboration errors can occur.
28646
28647 The result of this decision is two-fold. First to be safe using the
28648 static mode, you should remove all @code{pragma Elaborate} statements.
28649 Second, when fixing circularities in existing code, you can selectively
28650 use @code{pragma Elaborate} statements to convince the static mode of
28651 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28652 statement.
28653
28654 When using the static mode with @option{-gnatwl}, any use of
28655 @code{pragma Elaborate} will generate a warning about possible
28656 problems.
28657
28658 @node Elaboration Issues for Library Tasks
28659 @section Elaboration Issues for Library Tasks
28660 @cindex Library tasks, elaboration issues
28661 @cindex Elaboration of library tasks
28662
28663 @noindent
28664 In this section we examine special elaboration issues that arise for
28665 programs that declare library level tasks.
28666
28667 Generally the model of execution of an Ada program is that all units are
28668 elaborated, and then execution of the program starts. However, the
28669 declaration of library tasks definitely does not fit this model. The
28670 reason for this is that library tasks start as soon as they are declared
28671 (more precisely, as soon as the statement part of the enclosing package
28672 body is reached), that is to say before elaboration
28673 of the program is complete. This means that if such a task calls a
28674 subprogram, or an entry in another task, the callee may or may not be
28675 elaborated yet, and in the standard
28676 Reference Manual model of dynamic elaboration checks, you can even
28677 get timing dependent Program_Error exceptions, since there can be
28678 a race between the elaboration code and the task code.
28679
28680 The static model of elaboration in GNAT seeks to avoid all such
28681 dynamic behavior, by being conservative, and the conservative
28682 approach in this particular case is to assume that all the code
28683 in a task body is potentially executed at elaboration time if
28684 a task is declared at the library level.
28685
28686 This can definitely result in unexpected circularities. Consider
28687 the following example
28688
28689 @smallexample @c ada
28690 package Decls is
28691   task Lib_Task is
28692      entry Start;
28693   end Lib_Task;
28694
28695   type My_Int is new Integer;
28696
28697   function Ident (M : My_Int) return My_Int;
28698 end Decls;
28699
28700 with Utils;
28701 package body Decls is
28702   task body Lib_Task is
28703   begin
28704      accept Start;
28705      Utils.Put_Val (2);
28706   end Lib_Task;
28707
28708   function Ident (M : My_Int) return My_Int is
28709   begin
28710      return M;
28711   end Ident;
28712 end Decls;
28713
28714 with Decls;
28715 package Utils is
28716   procedure Put_Val (Arg : Decls.My_Int);
28717 end Utils;
28718
28719 with Text_IO;
28720 package body Utils is
28721   procedure Put_Val (Arg : Decls.My_Int) is
28722   begin
28723      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28724   end Put_Val;
28725 end Utils;
28726
28727 with Decls;
28728 procedure Main is
28729 begin
28730    Decls.Lib_Task.Start;
28731 end;
28732 @end smallexample
28733
28734 @noindent
28735 If the above example is compiled in the default static elaboration
28736 mode, then a circularity occurs. The circularity comes from the call
28737 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28738 this call occurs in elaboration code, we need an implicit pragma
28739 @code{Elaborate_All} for @code{Utils}. This means that not only must
28740 the spec and body of @code{Utils} be elaborated before the body
28741 of @code{Decls}, but also the spec and body of any unit that is
28742 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28743 the body of @code{Decls}. This is the transitive implication of
28744 pragma @code{Elaborate_All} and it makes sense, because in general
28745 the body of @code{Put_Val} might have a call to something in a
28746 @code{with'ed} unit.
28747
28748 In this case, the body of Utils (actually its spec) @code{with's}
28749 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28750 must be elaborated before itself, in case there is a call from the
28751 body of @code{Utils}.
28752
28753 Here is the exact chain of events we are worrying about:
28754
28755 @enumerate
28756 @item
28757 In the body of @code{Decls} a call is made from within the body of a library
28758 task to a subprogram in the package @code{Utils}. Since this call may
28759 occur at elaboration time (given that the task is activated at elaboration
28760 time), we have to assume the worst, i.e., that the
28761 call does happen at elaboration time.
28762
28763 @item
28764 This means that the body and spec of @code{Util} must be elaborated before
28765 the body of @code{Decls} so that this call does not cause an access before
28766 elaboration.
28767
28768 @item
28769 Within the body of @code{Util}, specifically within the body of
28770 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28771 by this package.
28772
28773 @item
28774 One such @code{with}'ed package is package @code{Decls}, so there
28775 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28776 In fact there is such a call in this example, but we would have to
28777 assume that there was such a call even if it were not there, since
28778 we are not supposed to write the body of @code{Decls} knowing what
28779 is in the body of @code{Utils}; certainly in the case of the
28780 static elaboration model, the compiler does not know what is in
28781 other bodies and must assume the worst.
28782
28783 @item
28784 This means that the spec and body of @code{Decls} must also be
28785 elaborated before we elaborate the unit containing the call, but
28786 that unit is @code{Decls}! This means that the body of @code{Decls}
28787 must be elaborated before itself, and that's a circularity.
28788 @end enumerate
28789
28790 @noindent
28791 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28792 the body of @code{Decls} you will get a true Ada Reference Manual
28793 circularity that makes the program illegal.
28794
28795 In practice, we have found that problems with the static model of
28796 elaboration in existing code often arise from library tasks, so
28797 we must address this particular situation.
28798
28799 Note that if we compile and run the program above, using the dynamic model of
28800 elaboration (that is to say use the @option{-gnatE} switch),
28801 then it compiles, binds,
28802 links, and runs, printing the expected result of 2. Therefore in some sense
28803 the circularity here is only apparent, and we need to capture
28804 the properties of this program that  distinguish it from other library-level
28805 tasks that have real elaboration problems.
28806
28807 We have four possible answers to this question:
28808
28809 @itemize @bullet
28810
28811 @item
28812 Use the dynamic model of elaboration.
28813
28814 If we use the @option{-gnatE} switch, then as noted above, the program works.
28815 Why is this? If we examine the task body, it is apparent that the task cannot
28816 proceed past the
28817 @code{accept} statement until after elaboration has been completed, because
28818 the corresponding entry call comes from the main program, not earlier.
28819 This is why the dynamic model works here. But that's really giving
28820 up on a precise analysis, and we prefer to take this approach only if we cannot
28821 solve the
28822 problem in any other manner. So let us examine two ways to reorganize
28823 the program to avoid the potential elaboration problem.
28824
28825 @item
28826 Split library tasks into separate packages.
28827
28828 Write separate packages, so that library tasks are isolated from
28829 other declarations as much as possible. Let us look at a variation on
28830 the above program.
28831
28832 @smallexample @c ada
28833 package Decls1 is
28834   task Lib_Task is
28835      entry Start;
28836   end Lib_Task;
28837 end Decls1;
28838
28839 with Utils;
28840 package body Decls1 is
28841   task body Lib_Task is
28842   begin
28843      accept Start;
28844      Utils.Put_Val (2);
28845   end Lib_Task;
28846 end Decls1;
28847
28848 package Decls2 is
28849   type My_Int is new Integer;
28850   function Ident (M : My_Int) return My_Int;
28851 end Decls2;
28852
28853 with Utils;
28854 package body Decls2 is
28855   function Ident (M : My_Int) return My_Int is
28856   begin
28857      return M;
28858   end Ident;
28859 end Decls2;
28860
28861 with Decls2;
28862 package Utils is
28863   procedure Put_Val (Arg : Decls2.My_Int);
28864 end Utils;
28865
28866 with Text_IO;
28867 package body Utils is
28868   procedure Put_Val (Arg : Decls2.My_Int) is
28869   begin
28870      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28871   end Put_Val;
28872 end Utils;
28873
28874 with Decls1;
28875 procedure Main is
28876 begin
28877    Decls1.Lib_Task.Start;
28878 end;
28879 @end smallexample
28880
28881 @noindent
28882 All we have done is to split @code{Decls} into two packages, one
28883 containing the library task, and one containing everything else. Now
28884 there is no cycle, and the program compiles, binds, links and executes
28885 using the default static model of elaboration.
28886
28887 @item
28888 Declare separate task types.
28889
28890 A significant part of the problem arises because of the use of the
28891 single task declaration form. This means that the elaboration of
28892 the task type, and the elaboration of the task itself (i.e.@: the
28893 creation of the task) happen at the same time. A good rule
28894 of style in Ada is to always create explicit task types. By
28895 following the additional step of placing task objects in separate
28896 packages from the task type declaration, many elaboration problems
28897 are avoided. Here is another modified example of the example program:
28898
28899 @smallexample @c ada
28900 package Decls is
28901   task type Lib_Task_Type is
28902      entry Start;
28903   end Lib_Task_Type;
28904
28905   type My_Int is new Integer;
28906
28907   function Ident (M : My_Int) return My_Int;
28908 end Decls;
28909
28910 with Utils;
28911 package body Decls is
28912   task body Lib_Task_Type is
28913   begin
28914      accept Start;
28915      Utils.Put_Val (2);
28916   end Lib_Task_Type;
28917
28918   function Ident (M : My_Int) return My_Int is
28919   begin
28920      return M;
28921   end Ident;
28922 end Decls;
28923
28924 with Decls;
28925 package Utils is
28926   procedure Put_Val (Arg : Decls.My_Int);
28927 end Utils;
28928
28929 with Text_IO;
28930 package body Utils is
28931   procedure Put_Val (Arg : Decls.My_Int) is
28932   begin
28933      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28934   end Put_Val;
28935 end Utils;
28936
28937 with Decls;
28938 package Declst is
28939    Lib_Task : Decls.Lib_Task_Type;
28940 end Declst;
28941
28942 with Declst;
28943 procedure Main is
28944 begin
28945    Declst.Lib_Task.Start;
28946 end;
28947 @end smallexample
28948
28949 @noindent
28950 What we have done here is to replace the @code{task} declaration in
28951 package @code{Decls} with a @code{task type} declaration. Then we
28952 introduce a separate package @code{Declst} to contain the actual
28953 task object. This separates the elaboration issues for
28954 the @code{task type}
28955 declaration, which causes no trouble, from the elaboration issues
28956 of the task object, which is also unproblematic, since it is now independent
28957 of the elaboration of  @code{Utils}.
28958 This separation of concerns also corresponds to
28959 a generally sound engineering principle of separating declarations
28960 from instances. This version of the program also compiles, binds, links,
28961 and executes, generating the expected output.
28962
28963 @item
28964 Use No_Entry_Calls_In_Elaboration_Code restriction.
28965 @cindex No_Entry_Calls_In_Elaboration_Code
28966
28967 The previous two approaches described how a program can be restructured
28968 to avoid the special problems caused by library task bodies. in practice,
28969 however, such restructuring may be difficult to apply to existing legacy code,
28970 so we must consider solutions that do not require massive rewriting.
28971
28972 Let us consider more carefully why our original sample program works
28973 under the dynamic model of elaboration. The reason is that the code
28974 in the task body blocks immediately on the @code{accept}
28975 statement. Now of course there is nothing to prohibit elaboration
28976 code from making entry calls (for example from another library level task),
28977 so we cannot tell in isolation that
28978 the task will not execute the accept statement  during elaboration.
28979
28980 However, in practice it is very unusual to see elaboration code
28981 make any entry calls, and the pattern of tasks starting
28982 at elaboration time and then immediately blocking on @code{accept} or
28983 @code{select} statements is very common. What this means is that
28984 the compiler is being too pessimistic when it analyzes the
28985 whole package body as though it might be executed at elaboration
28986 time.
28987
28988 If we know that the elaboration code contains no entry calls, (a very safe
28989 assumption most of the time, that could almost be made the default
28990 behavior), then we can compile all units of the program under control
28991 of the following configuration pragma:
28992
28993 @smallexample
28994 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28995 @end smallexample
28996
28997 @noindent
28998 This pragma can be placed in the @file{gnat.adc} file in the usual
28999 manner. If we take our original unmodified program and compile it
29000 in the presence of a @file{gnat.adc} containing the above pragma,
29001 then once again, we can compile, bind, link, and execute, obtaining
29002 the expected result. In the presence of this pragma, the compiler does
29003 not trace calls in a task body, that appear after the first @code{accept}
29004 or @code{select} statement, and therefore does not report a potential
29005 circularity in the original program.
29006
29007 The compiler will check to the extent it can that the above
29008 restriction is not violated, but it is not always possible to do a
29009 complete check at compile time, so it is important to use this
29010 pragma only if the stated restriction is in fact met, that is to say
29011 no task receives an entry call before elaboration of all units is completed.
29012
29013 @end itemize
29014
29015 @node Mixing Elaboration Models
29016 @section Mixing Elaboration Models
29017 @noindent
29018 So far, we have assumed that the entire program is either compiled
29019 using the dynamic model or static model, ensuring consistency. It
29020 is possible to mix the two models, but rules have to be followed
29021 if this mixing is done to ensure that elaboration checks are not
29022 omitted.
29023
29024 The basic rule is that @emph{a unit compiled with the static model cannot
29025 be @code{with'ed} by a unit compiled with the dynamic model}. The
29026 reason for this is that in the static model, a unit assumes that
29027 its clients guarantee to use (the equivalent of) pragma
29028 @code{Elaborate_All} so that no elaboration checks are required
29029 in inner subprograms, and this assumption is violated if the
29030 client is compiled with dynamic checks.
29031
29032 The precise rule is as follows. A unit that is compiled with dynamic
29033 checks can only @code{with} a unit that meets at least one of the
29034 following criteria:
29035
29036 @itemize @bullet
29037
29038 @item
29039 The @code{with'ed} unit is itself compiled with dynamic elaboration
29040 checks (that is with the @option{-gnatE} switch.
29041
29042 @item
29043 The @code{with'ed} unit is an internal GNAT implementation unit from
29044 the System, Interfaces, Ada, or GNAT hierarchies.
29045
29046 @item
29047 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29048
29049 @item
29050 The @code{with'ing} unit (that is the client) has an explicit pragma
29051 @code{Elaborate_All} for the @code{with'ed} unit.
29052
29053 @end itemize
29054
29055 @noindent
29056 If this rule is violated, that is if a unit with dynamic elaboration
29057 checks @code{with's} a unit that does not meet one of the above four
29058 criteria, then the binder (@code{gnatbind}) will issue a warning
29059 similar to that in the following example:
29060
29061 @smallexample
29062 warning: "x.ads" has dynamic elaboration checks and with's
29063 warning:   "y.ads" which has static elaboration checks
29064 @end smallexample
29065
29066 @noindent
29067 These warnings indicate that the rule has been violated, and that as a result
29068 elaboration checks may be missed in the resulting executable file.
29069 This warning may be suppressed using the @option{-ws} binder switch
29070 in the usual manner.
29071
29072 One useful application of this mixing rule is in the case of a subsystem
29073 which does not itself @code{with} units from the remainder of the
29074 application. In this case, the entire subsystem can be compiled with
29075 dynamic checks to resolve a circularity in the subsystem, while
29076 allowing the main application that uses this subsystem to be compiled
29077 using the more reliable default static model.
29078
29079 @node What to Do If the Default Elaboration Behavior Fails
29080 @section What to Do If the Default Elaboration Behavior Fails
29081
29082 @noindent
29083 If the binder cannot find an acceptable order, it outputs detailed
29084 diagnostics. For example:
29085 @smallexample
29086 @group
29087 @iftex
29088 @leftskip=0cm
29089 @end iftex
29090 error: elaboration circularity detected
29091 info:   "proc (body)" must be elaborated before "pack (body)"
29092 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29093 info:     recompile "pack (body)" with -gnatwl
29094 info:                             for full details
29095 info:       "proc (body)"
29096 info:         is needed by its spec:
29097 info:       "proc (spec)"
29098 info:         which is withed by:
29099 info:       "pack (body)"
29100 info:  "pack (body)" must be elaborated before "proc (body)"
29101 info:     reason: pragma Elaborate in unit "proc (body)"
29102 @end group
29103
29104 @end smallexample
29105
29106 @noindent
29107 In this case we have a cycle that the binder cannot break. On the one
29108 hand, there is an explicit pragma Elaborate in @code{proc} for
29109 @code{pack}. This means that the body of @code{pack} must be elaborated
29110 before the body of @code{proc}. On the other hand, there is elaboration
29111 code in @code{pack} that calls a subprogram in @code{proc}. This means
29112 that for maximum safety, there should really be a pragma
29113 Elaborate_All in @code{pack} for @code{proc} which would require that
29114 the body of @code{proc} be elaborated before the body of
29115 @code{pack}. Clearly both requirements cannot be satisfied.
29116 Faced with a circularity of this kind, you have three different options.
29117
29118 @table @asis
29119 @item Fix the program
29120 The most desirable option from the point of view of long-term maintenance
29121 is to rearrange the program so that the elaboration problems are avoided.
29122 One useful technique is to place the elaboration code into separate
29123 child packages. Another is to move some of the initialization code to
29124 explicitly called subprograms, where the program controls the order
29125 of initialization explicitly. Although this is the most desirable option,
29126 it may be impractical and involve too much modification, especially in
29127 the case of complex legacy code.
29128
29129 @item Perform dynamic checks
29130 If the compilations are done using the
29131 @option{-gnatE}
29132 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29133 manner. Dynamic checks are generated for all calls that could possibly result
29134 in raising an exception. With this switch, the compiler does not generate
29135 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29136 exactly as specified in the @cite{Ada Reference Manual}.
29137 The binder will generate
29138 an executable program that may or may not raise @code{Program_Error}, and then
29139 it is the programmer's job to ensure that it does not raise an exception. Note
29140 that it is important to compile all units with the switch, it cannot be used
29141 selectively.
29142
29143 @item Suppress checks
29144 The drawback of dynamic checks is that they generate a
29145 significant overhead at run time, both in space and time. If you
29146 are absolutely sure that your program cannot raise any elaboration
29147 exceptions, and you still want to use the dynamic elaboration model,
29148 then you can use the configuration pragma
29149 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29150 example this pragma could be placed in the @file{gnat.adc} file.
29151
29152 @item Suppress checks selectively
29153 When you know that certain calls or instantiations in elaboration code cannot
29154 possibly lead to an elaboration error, and the binder nevertheless complains
29155 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29156 elaboration circularities, it is possible to remove those warnings locally and
29157 obtain a program that will bind. Clearly this can be unsafe, and it is the
29158 responsibility of the programmer to make sure that the resulting program has no
29159 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29160 used with different granularity to suppress warnings and break elaboration
29161 circularities:
29162
29163 @itemize @bullet
29164 @item
29165 Place the pragma that names the called subprogram in the declarative part
29166 that contains the call.
29167
29168 @item
29169 Place the pragma in the declarative part, without naming an entity. This
29170 disables warnings on all calls in the corresponding  declarative region.
29171
29172 @item
29173 Place the pragma in the package spec that declares the called subprogram,
29174 and name the subprogram. This disables warnings on all elaboration calls to
29175 that subprogram.
29176
29177 @item
29178 Place the pragma in the package spec that declares the called subprogram,
29179 without naming any entity. This disables warnings on all elaboration calls to
29180 all subprograms declared in this spec.
29181
29182 @item Use Pragma Elaborate
29183 As previously described in section @xref{Treatment of Pragma Elaborate},
29184 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29185 that no elaboration checks are required on calls to the designated unit.
29186 There may be cases in which the caller knows that no transitive calls
29187 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29188 case where @code{pragma Elaborate_All} would cause a circularity.
29189 @end itemize
29190
29191 @noindent
29192 These five cases are listed in order of decreasing safety, and therefore
29193 require increasing programmer care in their application. Consider the
29194 following program:
29195
29196 @smallexample @c adanocomment
29197 package Pack1 is
29198   function F1 return Integer;
29199   X1 : Integer;
29200 end Pack1;
29201
29202 package Pack2 is
29203   function F2 return Integer;
29204   function Pure (x : integer) return integer;
29205   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29206   --  pragma Suppress (Elaboration_Check);              -- (4)
29207 end Pack2;
29208
29209 with Pack2;
29210 package body Pack1 is
29211   function F1 return Integer is
29212   begin
29213     return 100;
29214   end F1;
29215   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29216 begin
29217   declare
29218     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29219     --  pragma Suppress(Elaboration_Check);             -- (2)
29220   begin
29221     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29222   end;
29223 end Pack1;
29224
29225 with Pack1;
29226 package body Pack2 is
29227   function F2 return Integer is
29228   begin
29229      return Pack1.F1;
29230   end F2;
29231   function Pure (x : integer) return integer is
29232   begin
29233      return x ** 3 - 3 * x;
29234   end;
29235 end Pack2;
29236
29237 with Pack1, Ada.Text_IO;
29238 procedure Proc3 is
29239 begin
29240   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29241 end Proc3;
29242 @end smallexample
29243 In the absence of any pragmas, an attempt to bind this program produces
29244 the following diagnostics:
29245 @smallexample
29246 @group
29247 @iftex
29248 @leftskip=.5cm
29249 @end iftex
29250 error: elaboration circularity detected
29251 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29252 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29253 info:       recompile "pack1 (body)" with -gnatwl for full details
29254 info:          "pack1 (body)"
29255 info:             must be elaborated along with its spec:
29256 info:          "pack1 (spec)"
29257 info:             which is withed by:
29258 info:          "pack2 (body)"
29259 info:             which must be elaborated along with its spec:
29260 info:          "pack2 (spec)"
29261 info:             which is withed by:
29262 info:          "pack1 (body)"
29263 @end group
29264 @end smallexample
29265 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29266 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29267 F2 is safe, even though F2 calls F1, because the call appears after the
29268 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29269 remove the warning on the call. It is also possible to use pragma (2)
29270 because there are no other potentially unsafe calls in the block.
29271
29272 @noindent
29273 The call to @code{Pure} is safe because this function does not depend on the
29274 state of @code{Pack2}. Therefore any call to this function is safe, and it
29275 is correct to place pragma (3) in the corresponding package spec.
29276
29277 @noindent
29278 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29279 warnings on all calls to functions declared therein. Note that this is not
29280 necessarily safe, and requires more detailed examination of the subprogram
29281 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29282 be already elaborated.
29283 @end table
29284
29285 @noindent
29286 It is hard to generalize on which of these four approaches should be
29287 taken. Obviously if it is possible to fix the program so that the default
29288 treatment works, this is preferable, but this may not always be practical.
29289 It is certainly simple enough to use
29290 @option{-gnatE}
29291 but the danger in this case is that, even if the GNAT binder
29292 finds a correct elaboration order, it may not always do so,
29293 and certainly a binder from another Ada compiler might not. A
29294 combination of testing and analysis (for which the warnings generated
29295 with the
29296 @option{-gnatwl}
29297 switch can be useful) must be used to ensure that the program is free
29298 of errors. One switch that is useful in this testing is the
29299 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29300 switch for
29301 @code{gnatbind}.
29302 Normally the binder tries to find an order that has the best chance
29303 of avoiding elaboration problems. However, if this switch is used, the binder
29304 plays a devil's advocate role, and tries to choose the order that
29305 has the best chance of failing. If your program works even with this
29306 switch, then it has a better chance of being error free, but this is still
29307 not a guarantee.
29308
29309 For an example of this approach in action, consider the C-tests (executable
29310 tests) from the ACVC suite. If these are compiled and run with the default
29311 treatment, then all but one of them succeed without generating any error
29312 diagnostics from the binder. However, there is one test that fails, and
29313 this is not surprising, because the whole point of this test is to ensure
29314 that the compiler can handle cases where it is impossible to determine
29315 a correct order statically, and it checks that an exception is indeed
29316 raised at run time.
29317
29318 This one test must be compiled and run using the
29319 @option{-gnatE}
29320 switch, and then it passes. Alternatively, the entire suite can
29321 be run using this switch. It is never wrong to run with the dynamic
29322 elaboration switch if your code is correct, and we assume that the
29323 C-tests are indeed correct (it is less efficient, but efficiency is
29324 not a factor in running the ACVC tests.)
29325
29326 @node Elaboration for Access-to-Subprogram Values
29327 @section Elaboration for Access-to-Subprogram Values
29328 @cindex Access-to-subprogram
29329
29330 @noindent
29331 Access-to-subprogram types (introduced in Ada 95) complicate
29332 the handling of elaboration. The trouble is that it becomes
29333 impossible to tell at compile time which procedure
29334 is being called. This means that it is not possible for the binder
29335 to analyze the elaboration requirements in this case.
29336
29337 If at the point at which the access value is created
29338 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29339 the body of the subprogram is
29340 known to have been elaborated, then the access value is safe, and its use
29341 does not require a check. This may be achieved by appropriate arrangement
29342 of the order of declarations if the subprogram is in the current unit,
29343 or, if the subprogram is in another unit, by using pragma
29344 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29345 on the referenced unit.
29346
29347 If the referenced body is not known to have been elaborated at the point
29348 the access value is created, then any use of the access value must do a
29349 dynamic check, and this dynamic check will fail and raise a
29350 @code{Program_Error} exception if the body has not been elaborated yet.
29351 GNAT will generate the necessary checks, and in addition, if the
29352 @option{-gnatwl}
29353 switch is set, will generate warnings that such checks are required.
29354
29355 The use of dynamic dispatching for tagged types similarly generates
29356 a requirement for dynamic checks, and premature calls to any primitive
29357 operation of a tagged type before the body of the operation has been
29358 elaborated, will result in the raising of @code{Program_Error}.
29359
29360 @node Summary of Procedures for Elaboration Control
29361 @section Summary of Procedures for Elaboration Control
29362 @cindex Elaboration control
29363
29364 @noindent
29365 First, compile your program with the default options, using none of
29366 the special elaboration control switches. If the binder successfully
29367 binds your program, then you can be confident that, apart from issues
29368 raised by the use of access-to-subprogram types and dynamic dispatching,
29369 the program is free of elaboration errors. If it is important that the
29370 program be portable, then use the
29371 @option{-gnatwl}
29372 switch to generate warnings about missing @code{Elaborate} or
29373 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29374
29375 If the program fails to bind using the default static elaboration
29376 handling, then you can fix the program to eliminate the binder
29377 message, or recompile the entire program with the
29378 @option{-gnatE} switch to generate dynamic elaboration checks,
29379 and, if you are sure there really are no elaboration problems,
29380 use a global pragma @code{Suppress (Elaboration_Check)}.
29381
29382 @node Other Elaboration Order Considerations
29383 @section Other Elaboration Order Considerations
29384 @noindent
29385 This section has been entirely concerned with the issue of finding a valid
29386 elaboration order, as defined by the Ada Reference Manual. In a case
29387 where several elaboration orders are valid, the task is to find one
29388 of the possible valid elaboration orders (and the static model in GNAT
29389 will ensure that this is achieved).
29390
29391 The purpose of the elaboration rules in the Ada Reference Manual is to
29392 make sure that no entity is accessed before it has been elaborated. For
29393 a subprogram, this means that the spec and body must have been elaborated
29394 before the subprogram is called. For an object, this means that the object
29395 must have been elaborated before its value is read or written. A violation
29396 of either of these two requirements is an access before elaboration order,
29397 and this section has been all about avoiding such errors.
29398
29399 In the case where more than one order of elaboration is possible, in the
29400 sense that access before elaboration errors are avoided, then any one of
29401 the orders is ``correct'' in the sense that it meets the requirements of
29402 the Ada Reference Manual, and no such error occurs.
29403
29404 However, it may be the case for a given program, that there are
29405 constraints on the order of elaboration that come not from consideration
29406 of avoiding elaboration errors, but rather from extra-lingual logic
29407 requirements. Consider this example:
29408
29409 @smallexample @c ada
29410 with Init_Constants;
29411 package Constants is
29412    X : Integer := 0;
29413    Y : Integer := 0;
29414 end Constants;
29415
29416 package Init_Constants is
29417    procedure P; -- require a body
29418 end Init_Constants;
29419
29420 with Constants;
29421 package body Init_Constants is
29422    procedure P is begin null; end;
29423 begin
29424    Constants.X := 3;
29425    Constants.Y := 4;
29426 end Init_Constants;
29427
29428 with Constants;
29429 package Calc is
29430    Z : Integer := Constants.X + Constants.Y;
29431 end Calc;
29432
29433 with Calc;
29434 with Text_IO; use Text_IO;
29435 procedure Main is
29436 begin
29437    Put_Line (Calc.Z'Img);
29438 end Main;
29439 @end smallexample
29440
29441 @noindent
29442 In this example, there is more than one valid order of elaboration. For
29443 example both the following are correct orders:
29444
29445 @smallexample
29446 Init_Constants spec
29447 Constants spec
29448 Calc spec
29449 Init_Constants body
29450 Main body
29451
29452   and
29453
29454 Init_Constants spec
29455 Init_Constants body
29456 Constants spec
29457 Calc spec
29458 Main body
29459 @end smallexample
29460
29461 @noindent
29462 There is no language rule to prefer one or the other, both are correct
29463 from an order of elaboration point of view. But the programmatic effects
29464 of the two orders are very different. In the first, the elaboration routine
29465 of @code{Calc} initializes @code{Z} to zero, and then the main program
29466 runs with this value of zero. But in the second order, the elaboration
29467 routine of @code{Calc} runs after the body of Init_Constants has set
29468 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29469 runs.
29470
29471 One could perhaps by applying pretty clever non-artificial intelligence
29472 to the situation guess that it is more likely that the second order of
29473 elaboration is the one desired, but there is no formal linguistic reason
29474 to prefer one over the other. In fact in this particular case, GNAT will
29475 prefer the second order, because of the rule that bodies are elaborated
29476 as soon as possible, but it's just luck that this is what was wanted
29477 (if indeed the second order was preferred).
29478
29479 If the program cares about the order of elaboration routines in a case like
29480 this, it is important to specify the order required. In this particular
29481 case, that could have been achieved by adding to the spec of Calc:
29482
29483 @smallexample @c ada
29484 pragma Elaborate_All (Constants);
29485 @end smallexample
29486
29487 @noindent
29488 which requires that the body (if any) and spec of @code{Constants},
29489 as well as the body and spec of any unit @code{with}'ed by
29490 @code{Constants} be elaborated before @code{Calc} is elaborated.
29491
29492 Clearly no automatic method can always guess which alternative you require,
29493 and if you are working with legacy code that had constraints of this kind
29494 which were not properly specified by adding @code{Elaborate} or
29495 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29496 compilers can choose different orders.
29497
29498 However, GNAT does attempt to diagnose the common situation where there
29499 are uninitialized variables in the visible part of a package spec, and the
29500 corresponding package body has an elaboration block that directly or
29501 indirectly initialized one or more of these variables. This is the situation
29502 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29503 a warning that suggests this addition if it detects this situation.
29504
29505 The @code{gnatbind}
29506 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29507 out problems. This switch causes bodies to be elaborated as late as possible
29508 instead of as early as possible. In the example above, it would have forced
29509 the choice of the first elaboration order. If you get different results
29510 when using this switch, and particularly if one set of results is right,
29511 and one is wrong as far as you are concerned, it shows that you have some
29512 missing @code{Elaborate} pragmas. For the example above, we have the
29513 following output:
29514
29515 @smallexample
29516 gnatmake -f -q main
29517 main
29518  7
29519 gnatmake -f -q main -bargs -p
29520 main
29521  0
29522 @end smallexample
29523
29524 @noindent
29525 It is of course quite unlikely that both these results are correct, so
29526 it is up to you in a case like this to investigate the source of the
29527 difference, by looking at the two elaboration orders that are chosen,
29528 and figuring out which is correct, and then adding the necessary
29529 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29530
29531
29532
29533 @c *******************************
29534 @node Conditional Compilation
29535 @appendix Conditional Compilation
29536 @c *******************************
29537 @cindex Conditional compilation
29538
29539 @noindent
29540 It is often necessary to arrange for a single source program
29541 to serve multiple purposes, where it is compiled in different
29542 ways to achieve these different goals. Some examples of the
29543 need for this feature are
29544
29545 @itemize @bullet
29546 @item  Adapting a program to a different hardware environment
29547 @item  Adapting a program to a different target architecture
29548 @item  Turning debugging features on and off
29549 @item  Arranging for a program to compile with different compilers
29550 @end itemize
29551
29552 @noindent
29553 In C, or C++, the typical approach would be to use the preprocessor
29554 that is defined as part of the language. The Ada language does not
29555 contain such a feature. This is not an oversight, but rather a very
29556 deliberate design decision, based on the experience that overuse of
29557 the preprocessing features in C and C++ can result in programs that
29558 are extremely difficult to maintain. For example, if we have ten
29559 switches that can be on or off, this means that there are a thousand
29560 separate programs, any one of which might not even be syntactically
29561 correct, and even if syntactically correct, the resulting program
29562 might not work correctly. Testing all combinations can quickly become
29563 impossible.
29564
29565 Nevertheless, the need to tailor programs certainly exists, and in
29566 this Appendix we will discuss how this can
29567 be achieved using Ada in general, and GNAT in particular.
29568
29569 @menu
29570 * Use of Boolean Constants::
29571 * Debugging - A Special Case::
29572 * Conditionalizing Declarations::
29573 * Use of Alternative Implementations::
29574 * Preprocessing::
29575 @end menu
29576
29577 @node Use of Boolean Constants
29578 @section Use of Boolean Constants
29579
29580 @noindent
29581 In the case where the difference is simply which code
29582 sequence is executed, the cleanest solution is to use Boolean
29583 constants to control which code is executed.
29584
29585 @smallexample @c ada
29586 @group
29587 FP_Initialize_Required : constant Boolean := True;
29588 @dots{}
29589 if FP_Initialize_Required then
29590 @dots{}
29591 end if;
29592 @end group
29593 @end smallexample
29594
29595 @noindent
29596 Not only will the code inside the @code{if} statement not be executed if
29597 the constant Boolean is @code{False}, but it will also be completely
29598 deleted from the program.
29599 However, the code is only deleted after the @code{if} statement
29600 has been checked for syntactic and semantic correctness.
29601 (In contrast, with preprocessors the code is deleted before the
29602 compiler ever gets to see it, so it is not checked until the switch
29603 is turned on.)
29604 @cindex Preprocessors (contrasted with conditional compilation)
29605
29606 Typically the Boolean constants will be in a separate package,
29607 something like:
29608
29609 @smallexample @c ada
29610 @group
29611 package Config is
29612    FP_Initialize_Required : constant Boolean := True;
29613    Reset_Available        : constant Boolean := False;
29614    @dots{}
29615 end Config;
29616 @end group
29617 @end smallexample
29618
29619 @noindent
29620 The @code{Config} package exists in multiple forms for the various targets,
29621 with an appropriate script selecting the version of @code{Config} needed.
29622 Then any other unit requiring conditional compilation can do a @code{with}
29623 of @code{Config} to make the constants visible.
29624
29625
29626 @node Debugging - A Special Case
29627 @section Debugging - A Special Case
29628
29629 @noindent
29630 A common use of conditional code is to execute statements (for example
29631 dynamic checks, or output of intermediate results) under control of a
29632 debug switch, so that the debugging behavior can be turned on and off.
29633 This can be done using a Boolean constant to control whether the code
29634 is active:
29635
29636 @smallexample @c ada
29637 @group
29638 if Debugging then
29639    Put_Line ("got to the first stage!");
29640 end if;
29641 @end group
29642 @end smallexample
29643
29644 @noindent
29645 or
29646
29647 @smallexample @c ada
29648 @group
29649 if Debugging and then Temperature > 999.0 then
29650    raise Temperature_Crazy;
29651 end if;
29652 @end group
29653 @end smallexample
29654
29655 @noindent
29656 Since this is a common case, there are special features to deal with
29657 this in a convenient manner. For the case of tests, Ada 2005 has added
29658 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29659 @cindex pragma @code{Assert}
29660 on the @code{Assert} pragma that has always been available in GNAT, so this
29661 feature may be used with GNAT even if you are not using Ada 2005 features.
29662 The use of pragma @code{Assert} is described in
29663 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29664 example, the last test could be written:
29665
29666 @smallexample @c ada
29667 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29668 @end smallexample
29669
29670 @noindent
29671 or simply
29672
29673 @smallexample @c ada
29674 pragma Assert (Temperature <= 999.0);
29675 @end smallexample
29676
29677 @noindent
29678 In both cases, if assertions are active and the temperature is excessive,
29679 the exception @code{Assert_Failure} will be raised, with the given string in
29680 the first case or a string indicating the location of the pragma in the second
29681 case used as the exception message.
29682
29683 You can turn assertions on and off by using the @code{Assertion_Policy}
29684 pragma.
29685 @cindex pragma @code{Assertion_Policy}
29686 This is an Ada 2005 pragma which is implemented in all modes by
29687 GNAT, but only in the latest versions of GNAT which include Ada 2005
29688 capability. Alternatively, you can use the @option{-gnata} switch
29689 @cindex @option{-gnata} switch
29690 to enable assertions from the command line (this is recognized by all versions
29691 of GNAT).
29692
29693 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29694 @code{Debug} can be used:
29695 @cindex pragma @code{Debug}
29696
29697 @smallexample @c ada
29698 pragma Debug (Put_Line ("got to the first stage!"));
29699 @end smallexample
29700
29701 @noindent
29702 If debug pragmas are enabled, the argument, which must be of the form of
29703 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29704 Only one call can be present, but of course a special debugging procedure
29705 containing any code you like can be included in the program and then
29706 called in a pragma @code{Debug} argument as needed.
29707
29708 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29709 construct is that pragma @code{Debug} can appear in declarative contexts,
29710 such as at the very beginning of a procedure, before local declarations have
29711 been elaborated.
29712
29713 Debug pragmas are enabled using either the @option{-gnata} switch that also
29714 controls assertions, or with a separate Debug_Policy pragma.
29715 @cindex pragma @code{Debug_Policy}
29716 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29717 in Ada 95 and Ada 83 programs as well), and is analogous to
29718 pragma @code{Assertion_Policy} to control assertions.
29719
29720 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29721 and thus they can appear in @file{gnat.adc} if you are not using a
29722 project file, or in the file designated to contain configuration pragmas
29723 in a project file.
29724 They then apply to all subsequent compilations. In practice the use of
29725 the @option{-gnata} switch is often the most convenient method of controlling
29726 the status of these pragmas.
29727
29728 Note that a pragma is not a statement, so in contexts where a statement
29729 sequence is required, you can't just write a pragma on its own. You have
29730 to add a @code{null} statement.
29731
29732 @smallexample @c ada
29733 @group
29734 if @dots{} then
29735    @dots{} -- some statements
29736 else
29737    pragma Assert (Num_Cases < 10);
29738    null;
29739 end if;
29740 @end group
29741 @end smallexample
29742
29743
29744 @node Conditionalizing Declarations
29745 @section Conditionalizing Declarations
29746
29747 @noindent
29748 In some cases, it may be necessary to conditionalize declarations to meet
29749 different requirements. For example we might want a bit string whose length
29750 is set to meet some hardware message requirement.
29751
29752 In some cases, it may be possible to do this using declare blocks controlled
29753 by conditional constants:
29754
29755 @smallexample @c ada
29756 @group
29757 if Small_Machine then
29758    declare
29759       X : Bit_String (1 .. 10);
29760    begin
29761       @dots{}
29762    end;
29763 else
29764    declare
29765       X : Large_Bit_String (1 .. 1000);
29766    begin
29767       @dots{}
29768    end;
29769 end if;
29770 @end group
29771 @end smallexample
29772
29773 @noindent
29774 Note that in this approach, both declarations are analyzed by the
29775 compiler so this can only be used where both declarations are legal,
29776 even though one of them will not be used.
29777
29778 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29779 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29780 that are parameterized by these constants. For example
29781
29782 @smallexample @c ada
29783 @group
29784 for Rec use
29785   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29786 end record;
29787 @end group
29788 @end smallexample
29789
29790 @noindent
29791 If @code{Bits_Per_Word} is set to 32, this generates either
29792
29793 @smallexample @c ada
29794 @group
29795 for Rec use
29796   Field1 at 0 range 0 .. 32;
29797 end record;
29798 @end group
29799 @end smallexample
29800
29801 @noindent
29802 for the big endian case, or
29803
29804 @smallexample @c ada
29805 @group
29806 for Rec use record
29807   Field1 at 0 range 10 .. 32;
29808 end record;
29809 @end group
29810 @end smallexample
29811
29812 @noindent
29813 for the little endian case. Since a powerful subset of Ada expression
29814 notation is usable for creating static constants, clever use of this
29815 feature can often solve quite difficult problems in conditionalizing
29816 compilation (note incidentally that in Ada 95, the little endian
29817 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29818 need to define this one yourself).
29819
29820
29821 @node Use of Alternative Implementations
29822 @section Use of Alternative Implementations
29823
29824 @noindent
29825 In some cases, none of the approaches described above are adequate. This
29826 can occur for example if the set of declarations required is radically
29827 different for two different configurations.
29828
29829 In this situation, the official Ada way of dealing with conditionalizing
29830 such code is to write separate units for the different cases. As long as
29831 this does not result in excessive duplication of code, this can be done
29832 without creating maintenance problems. The approach is to share common
29833 code as far as possible, and then isolate the code and declarations
29834 that are different. Subunits are often a convenient method for breaking
29835 out a piece of a unit that is to be conditionalized, with separate files
29836 for different versions of the subunit for different targets, where the
29837 build script selects the right one to give to the compiler.
29838 @cindex Subunits (and conditional compilation)
29839
29840 As an example, consider a situation where a new feature in Ada 2005
29841 allows something to be done in a really nice way. But your code must be able
29842 to compile with an Ada 95 compiler. Conceptually you want to say:
29843
29844 @smallexample @c ada
29845 @group
29846 if Ada_2005 then
29847    @dots{} neat Ada 2005 code
29848 else
29849    @dots{} not quite as neat Ada 95 code
29850 end if;
29851 @end group
29852 @end smallexample
29853
29854 @noindent
29855 where @code{Ada_2005} is a Boolean constant.
29856
29857 But this won't work when @code{Ada_2005} is set to @code{False},
29858 since the @code{then} clause will be illegal for an Ada 95 compiler.
29859 (Recall that although such unreachable code would eventually be deleted
29860 by the compiler, it still needs to be legal.  If it uses features
29861 introduced in Ada 2005, it will be illegal in Ada 95.)
29862
29863 So instead we write
29864
29865 @smallexample @c ada
29866 procedure Insert is separate;
29867 @end smallexample
29868
29869 @noindent
29870 Then we have two files for the subunit @code{Insert}, with the two sets of
29871 code.
29872 If the package containing this is called @code{File_Queries}, then we might
29873 have two files
29874
29875 @itemize @bullet
29876 @item    @file{file_queries-insert-2005.adb}
29877 @item    @file{file_queries-insert-95.adb}
29878 @end itemize
29879
29880 @noindent
29881 and the build script renames the appropriate file to
29882
29883 @smallexample
29884 file_queries-insert.adb
29885 @end smallexample
29886
29887 @noindent
29888 and then carries out the compilation.
29889
29890 This can also be done with project files' naming schemes. For example:
29891
29892 @smallexample @c project
29893 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29894 @end smallexample
29895
29896 @noindent
29897 Note also that with project files it is desirable to use a different extension
29898 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29899 conflict may arise through another commonly used feature: to declare as part
29900 of the project a set of directories containing all the sources obeying the
29901 default naming scheme.
29902
29903 The use of alternative units is certainly feasible in all situations,
29904 and for example the Ada part of the GNAT run-time is conditionalized
29905 based on the target architecture using this approach. As a specific example,
29906 consider the implementation of the AST feature in VMS. There is one
29907 spec:
29908
29909 @smallexample
29910 s-asthan.ads
29911 @end smallexample
29912
29913 @noindent
29914 which is the same for all architectures, and three bodies:
29915
29916 @table @file
29917 @item    s-asthan.adb
29918 used for all non-VMS operating systems
29919 @item    s-asthan-vms-alpha.adb
29920 used for VMS on the Alpha
29921 @item    s-asthan-vms-ia64.adb
29922 used for VMS on the ia64
29923 @end table
29924
29925 @noindent
29926 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29927 this operating system feature is not available, and the two remaining
29928 versions interface with the corresponding versions of VMS to provide
29929 VMS-compatible AST handling. The GNAT build script knows the architecture
29930 and operating system, and automatically selects the right version,
29931 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29932
29933 Another style for arranging alternative implementations is through Ada's
29934 access-to-subprogram facility.
29935 In case some functionality is to be conditionally included,
29936 you can declare an access-to-procedure variable @code{Ref} that is initialized
29937 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29938 when appropriate.
29939 In some library package, set @code{Ref} to @code{Proc'Access} for some
29940 procedure @code{Proc} that performs the relevant processing.
29941 The initialization only occurs if the library package is included in the
29942 program.
29943 The same idea can also be implemented using tagged types and dispatching
29944 calls.
29945
29946
29947 @node Preprocessing
29948 @section Preprocessing
29949 @cindex Preprocessing
29950
29951 @noindent
29952 Although it is quite possible to conditionalize code without the use of
29953 C-style preprocessing, as described earlier in this section, it is
29954 nevertheless convenient in some cases to use the C approach. Moreover,
29955 older Ada compilers have often provided some preprocessing capability,
29956 so legacy code may depend on this approach, even though it is not
29957 standard.
29958
29959 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29960 extent on the various preprocessors that have been used
29961 with legacy code on other compilers, to enable easier transition).
29962
29963 The preprocessor may be used in two separate modes. It can be used quite
29964 separately from the compiler, to generate a separate output source file
29965 that is then fed to the compiler as a separate step. This is the
29966 @code{gnatprep} utility, whose use is fully described in
29967 @ref{Preprocessing Using gnatprep}.
29968 @cindex @code{gnatprep}
29969
29970 The preprocessing language allows such constructs as
29971
29972 @smallexample
29973 @group
29974 #if DEBUG or PRIORITY > 4 then
29975    bunch of declarations
29976 #else
29977    completely different bunch of declarations
29978 #end if;
29979 @end group
29980 @end smallexample
29981
29982 @noindent
29983 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29984 defined either on the command line or in a separate file.
29985
29986 The other way of running the preprocessor is even closer to the C style and
29987 often more convenient. In this approach the preprocessing is integrated into
29988 the compilation process. The compiler is fed the preprocessor input which
29989 includes @code{#if} lines etc, and then the compiler carries out the
29990 preprocessing internally and processes the resulting output.
29991 For more details on this approach, see @ref{Integrated Preprocessing}.
29992
29993
29994 @c *******************************
29995 @node Inline Assembler
29996 @appendix Inline Assembler
29997 @c *******************************
29998
29999 @noindent
30000 If you need to write low-level software that interacts directly
30001 with the hardware, Ada provides two ways to incorporate assembly
30002 language code into your program.  First, you can import and invoke
30003 external routines written in assembly language, an Ada feature fully
30004 supported by GNAT@.  However, for small sections of code it may be simpler
30005 or more efficient to include assembly language statements directly
30006 in your Ada source program, using the facilities of the implementation-defined
30007 package @code{System.Machine_Code}, which incorporates the gcc
30008 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30009 including the following:
30010
30011 @itemize @bullet
30012 @item No need to use non-Ada tools
30013 @item Consistent interface over different targets
30014 @item Automatic usage of the proper calling conventions
30015 @item Access to Ada constants and variables
30016 @item Definition of intrinsic routines
30017 @item Possibility of inlining a subprogram comprising assembler code
30018 @item Code optimizer can take Inline Assembler code into account
30019 @end itemize
30020
30021 This chapter presents a series of examples to show you how to use
30022 the Inline Assembler.  Although it focuses on the Intel x86,
30023 the general approach applies also to other processors.
30024 It is assumed that you are familiar with Ada
30025 and with assembly language programming.
30026
30027 @menu
30028 * Basic Assembler Syntax::
30029 * A Simple Example of Inline Assembler::
30030 * Output Variables in Inline Assembler::
30031 * Input Variables in Inline Assembler::
30032 * Inlining Inline Assembler Code::
30033 * Other Asm Functionality::
30034 @end menu
30035
30036 @c ---------------------------------------------------------------------------
30037 @node Basic Assembler Syntax
30038 @section Basic Assembler Syntax
30039
30040 @noindent
30041 The assembler used by GNAT and gcc is based not on the Intel assembly
30042 language, but rather on a language that descends from the AT&T Unix
30043 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30044 The following table summarizes the main features of @emph{as} syntax
30045 and points out the differences from the Intel conventions.
30046 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30047 pre-processor) documentation for further information.
30048
30049 @table @asis
30050 @item Register names
30051 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30052 @*
30053 Intel: No extra punctuation; for example @code{eax}
30054
30055 @item Immediate operand
30056 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30057 @*
30058 Intel: No extra punctuation; for example @code{4}
30059
30060 @item Address
30061 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30062 @*
30063 Intel: No extra punctuation; for example @code{loc}
30064
30065 @item Memory contents
30066 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30067 @*
30068 Intel: Square brackets; for example @code{[loc]}
30069
30070 @item Register contents
30071 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30072 @*
30073 Intel: Square brackets; for example @code{[eax]}
30074
30075 @item Hexadecimal numbers
30076 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30077 @*
30078 Intel: Trailing ``h''; for example @code{A0h}
30079
30080 @item Operand size
30081 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30082 a 16-bit word
30083 @*
30084 Intel: Implicit, deduced by assembler; for example @code{mov}
30085
30086 @item Instruction repetition
30087 gcc / @emph{as}: Split into two lines; for example
30088 @*
30089 @code{rep}
30090 @*
30091 @code{stosl}
30092 @*
30093 Intel: Keep on one line; for example @code{rep stosl}
30094
30095 @item Order of operands
30096 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30097 @*
30098 Intel: Destination first; for example @code{mov eax, 4}
30099 @end table
30100
30101 @c ---------------------------------------------------------------------------
30102 @node A Simple Example of Inline Assembler
30103 @section A Simple Example of Inline Assembler
30104
30105 @noindent
30106 The following example will generate a single assembly language statement,
30107 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30108 the example will be useful in illustrating the basics of
30109 the Inline Assembler facility.
30110
30111 @smallexample @c ada
30112 @group
30113 with System.Machine_Code; use System.Machine_Code;
30114 procedure Nothing is
30115 begin
30116    Asm ("nop");
30117 end Nothing;
30118 @end group
30119 @end smallexample
30120
30121 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30122 here it takes one parameter, a @emph{template string} that must be a static
30123 expression and that will form the generated instruction.
30124 @code{Asm} may be regarded as a compile-time procedure that parses
30125 the template string and additional parameters (none here),
30126 from which it generates a sequence of assembly language instructions.
30127
30128 The examples in this chapter will illustrate several of the forms
30129 for invoking @code{Asm}; a complete specification of the syntax
30130 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30131 Manual}.
30132
30133 Under the standard GNAT conventions, the @code{Nothing} procedure
30134 should be in a file named @file{nothing.adb}.
30135 You can build the executable in the usual way:
30136 @smallexample
30137 gnatmake nothing
30138 @end smallexample
30139 However, the interesting aspect of this example is not its run-time behavior
30140 but rather the generated assembly code.
30141 To see this output, invoke the compiler as follows:
30142 @smallexample
30143    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30144 @end smallexample
30145 where the options are:
30146
30147 @table @code
30148 @item -c
30149 compile only (no bind or link)
30150 @item -S
30151 generate assembler listing
30152 @item -fomit-frame-pointer
30153 do not set up separate stack frames
30154 @item -gnatp
30155 do not add runtime checks
30156 @end table
30157
30158 This gives a human-readable assembler version of the code. The resulting
30159 file will have the same name as the Ada source file, but with a @code{.s}
30160 extension. In our example, the file @file{nothing.s} has the following
30161 contents:
30162
30163 @smallexample
30164 @group
30165 .file "nothing.adb"
30166 gcc2_compiled.:
30167 ___gnu_compiled_ada:
30168 .text
30169    .align 4
30170 .globl __ada_nothing
30171 __ada_nothing:
30172 #APP
30173    nop
30174 #NO_APP
30175    jmp L1
30176    .align 2,0x90
30177 L1:
30178    ret
30179 @end group
30180 @end smallexample
30181
30182 The assembly code you included is clearly indicated by
30183 the compiler, between the @code{#APP} and @code{#NO_APP}
30184 delimiters. The character before the 'APP' and 'NOAPP'
30185 can differ on different targets. For example, GNU/Linux uses '#APP' while
30186 on NT you will see '/APP'.
30187
30188 If you make a mistake in your assembler code (such as using the
30189 wrong size modifier, or using a wrong operand for the instruction) GNAT
30190 will report this error in a temporary file, which will be deleted when
30191 the compilation is finished.  Generating an assembler file will help
30192 in such cases, since you can assemble this file separately using the
30193 @emph{as} assembler that comes with gcc.
30194
30195 Assembling the file using the command
30196
30197 @smallexample
30198 as @file{nothing.s}
30199 @end smallexample
30200 @noindent
30201 will give you error messages whose lines correspond to the assembler
30202 input file, so you can easily find and correct any mistakes you made.
30203 If there are no errors, @emph{as} will generate an object file
30204 @file{nothing.out}.
30205
30206 @c ---------------------------------------------------------------------------
30207 @node Output Variables in Inline Assembler
30208 @section Output Variables in Inline Assembler
30209
30210 @noindent
30211 The examples in this section, showing how to access the processor flags,
30212 illustrate how to specify the destination operands for assembly language
30213 statements.
30214
30215 @smallexample @c ada
30216 @group
30217 with Interfaces; use Interfaces;
30218 with Ada.Text_IO; use Ada.Text_IO;
30219 with System.Machine_Code; use System.Machine_Code;
30220 procedure Get_Flags is
30221    Flags : Unsigned_32;
30222    use ASCII;
30223 begin
30224    Asm ("pushfl"          & LF & HT & -- push flags on stack
30225         "popl %%eax"      & LF & HT & -- load eax with flags
30226         "movl %%eax, %0",             -- store flags in variable
30227         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30228    Put_Line ("Flags register:" & Flags'Img);
30229 end Get_Flags;
30230 @end group
30231 @end smallexample
30232
30233 In order to have a nicely aligned assembly listing, we have separated
30234 multiple assembler statements in the Asm template string with linefeed
30235 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30236 The resulting section of the assembly output file is:
30237
30238 @smallexample
30239 @group
30240 #APP
30241    pushfl
30242    popl %eax
30243    movl %eax, -40(%ebp)
30244 #NO_APP
30245 @end group
30246 @end smallexample
30247
30248 It would have been legal to write the Asm invocation as:
30249
30250 @smallexample
30251 Asm ("pushfl popl %%eax movl %%eax, %0")
30252 @end smallexample
30253
30254 but in the generated assembler file, this would come out as:
30255
30256 @smallexample
30257 #APP
30258    pushfl popl %eax movl %eax, -40(%ebp)
30259 #NO_APP
30260 @end smallexample
30261
30262 which is not so convenient for the human reader.
30263
30264 We use Ada comments
30265 at the end of each line to explain what the assembler instructions
30266 actually do.  This is a useful convention.
30267
30268 When writing Inline Assembler instructions, you need to precede each register
30269 and variable name with a percent sign.  Since the assembler already requires
30270 a percent sign at the beginning of a register name, you need two consecutive
30271 percent signs for such names in the Asm template string, thus @code{%%eax}.
30272 In the generated assembly code, one of the percent signs will be stripped off.
30273
30274 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30275 variables: operands you later define using @code{Input} or @code{Output}
30276 parameters to @code{Asm}.
30277 An output variable is illustrated in
30278 the third statement in the Asm template string:
30279 @smallexample
30280 movl %%eax, %0
30281 @end smallexample
30282 The intent is to store the contents of the eax register in a variable that can
30283 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30284 necessarily work, since the compiler might optimize by using a register
30285 to hold Flags, and the expansion of the @code{movl} instruction would not be
30286 aware of this optimization.  The solution is not to store the result directly
30287 but rather to advise the compiler to choose the correct operand form;
30288 that is the purpose of the @code{%0} output variable.
30289
30290 Information about the output variable is supplied in the @code{Outputs}
30291 parameter to @code{Asm}:
30292 @smallexample
30293 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30294 @end smallexample
30295
30296 The output is defined by the @code{Asm_Output} attribute of the target type;
30297 the general format is
30298 @smallexample
30299 Type'Asm_Output (constraint_string, variable_name)
30300 @end smallexample
30301
30302 The constraint string directs the compiler how
30303 to store/access the associated variable.  In the example
30304 @smallexample
30305 Unsigned_32'Asm_Output ("=m", Flags);
30306 @end smallexample
30307 the @code{"m"} (memory) constraint tells the compiler that the variable
30308 @code{Flags} should be stored in a memory variable, thus preventing
30309 the optimizer from keeping it in a register.  In contrast,
30310 @smallexample
30311 Unsigned_32'Asm_Output ("=r", Flags);
30312 @end smallexample
30313 uses the @code{"r"} (register) constraint, telling the compiler to
30314 store the variable in a register.
30315
30316 If the constraint is preceded by the equal character (@strong{=}), it tells
30317 the compiler that the variable will be used to store data into it.
30318
30319 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30320 allowing the optimizer to choose whatever it deems best.
30321
30322 There are a fairly large number of constraints, but the ones that are
30323 most useful (for the Intel x86 processor) are the following:
30324
30325 @table @code
30326 @item =
30327 output constraint
30328 @item g
30329 global (i.e.@: can be stored anywhere)
30330 @item m
30331 in memory
30332 @item I
30333 a constant
30334 @item a
30335 use eax
30336 @item b
30337 use ebx
30338 @item c
30339 use ecx
30340 @item d
30341 use edx
30342 @item S
30343 use esi
30344 @item D
30345 use edi
30346 @item r
30347 use one of eax, ebx, ecx or edx
30348 @item q
30349 use one of eax, ebx, ecx, edx, esi or edi
30350 @end table
30351
30352 The full set of constraints is described in the gcc and @emph{as}
30353 documentation; note that it is possible to combine certain constraints
30354 in one constraint string.
30355
30356 You specify the association of an output variable with an assembler operand
30357 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30358 integer.  Thus in
30359 @smallexample @c ada
30360 @group
30361 Asm ("pushfl"          & LF & HT & -- push flags on stack
30362      "popl %%eax"      & LF & HT & -- load eax with flags
30363      "movl %%eax, %0",             -- store flags in variable
30364      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30365 @end group
30366 @end smallexample
30367 @noindent
30368 @code{%0} will be replaced in the expanded code by the appropriate operand,
30369 whatever
30370 the compiler decided for the @code{Flags} variable.
30371
30372 In general, you may have any number of output variables:
30373 @itemize @bullet
30374 @item
30375 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30376 @item
30377 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30378 of @code{Asm_Output} attributes
30379 @end itemize
30380
30381 For example:
30382 @smallexample @c ada
30383 @group
30384 Asm ("movl %%eax, %0" & LF & HT &
30385      "movl %%ebx, %1" & LF & HT &
30386      "movl %%ecx, %2",
30387      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30388                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30389                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30390 @end group
30391 @end smallexample
30392 @noindent
30393 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30394 in the Ada program.
30395
30396 As a variation on the @code{Get_Flags} example, we can use the constraints
30397 string to direct the compiler to store the eax register into the @code{Flags}
30398 variable, instead of including the store instruction explicitly in the
30399 @code{Asm} template string:
30400
30401 @smallexample @c ada
30402 @group
30403 with Interfaces; use Interfaces;
30404 with Ada.Text_IO; use Ada.Text_IO;
30405 with System.Machine_Code; use System.Machine_Code;
30406 procedure Get_Flags_2 is
30407    Flags : Unsigned_32;
30408    use ASCII;
30409 begin
30410    Asm ("pushfl"      & LF & HT & -- push flags on stack
30411         "popl %%eax",             -- save flags in eax
30412         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30413    Put_Line ("Flags register:" & Flags'Img);
30414 end Get_Flags_2;
30415 @end group
30416 @end smallexample
30417
30418 @noindent
30419 The @code{"a"} constraint tells the compiler that the @code{Flags}
30420 variable will come from the eax register. Here is the resulting code:
30421
30422 @smallexample
30423 @group
30424 #APP
30425    pushfl
30426    popl %eax
30427 #NO_APP
30428    movl %eax,-40(%ebp)
30429 @end group
30430 @end smallexample
30431
30432 @noindent
30433 The compiler generated the store of eax into Flags after
30434 expanding the assembler code.
30435
30436 Actually, there was no need to pop the flags into the eax register;
30437 more simply, we could just pop the flags directly into the program variable:
30438
30439 @smallexample @c ada
30440 @group
30441 with Interfaces; use Interfaces;
30442 with Ada.Text_IO; use Ada.Text_IO;
30443 with System.Machine_Code; use System.Machine_Code;
30444 procedure Get_Flags_3 is
30445    Flags : Unsigned_32;
30446    use ASCII;
30447 begin
30448    Asm ("pushfl"  & LF & HT & -- push flags on stack
30449         "pop %0",             -- save flags in Flags
30450         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30451    Put_Line ("Flags register:" & Flags'Img);
30452 end Get_Flags_3;
30453 @end group
30454 @end smallexample
30455
30456 @c ---------------------------------------------------------------------------
30457 @node Input Variables in Inline Assembler
30458 @section Input Variables in Inline Assembler
30459
30460 @noindent
30461 The example in this section illustrates how to specify the source operands
30462 for assembly language statements.
30463 The program simply increments its input value by 1:
30464
30465 @smallexample @c ada
30466 @group
30467 with Interfaces; use Interfaces;
30468 with Ada.Text_IO; use Ada.Text_IO;
30469 with System.Machine_Code; use System.Machine_Code;
30470 procedure Increment is
30471
30472    function Incr (Value : Unsigned_32) return Unsigned_32 is
30473       Result : Unsigned_32;
30474    begin
30475       Asm ("incl %0",
30476            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30477            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30478       return Result;
30479    end Incr;
30480
30481    Value : Unsigned_32;
30482
30483 begin
30484    Value := 5;
30485    Put_Line ("Value before is" & Value'Img);
30486    Value := Incr (Value);
30487    Put_Line ("Value after is" & Value'Img);
30488 end Increment;
30489 @end group
30490 @end smallexample
30491
30492 The @code{Outputs} parameter to @code{Asm} specifies
30493 that the result will be in the eax register and that it is to be stored
30494 in the @code{Result} variable.
30495
30496 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30497 but with an @code{Asm_Input} attribute.
30498 The @code{"="} constraint, indicating an output value, is not present.
30499
30500 You can have multiple input variables, in the same way that you can have more
30501 than one output variable.
30502
30503 The parameter count (%0, %1) etc, now starts at the first input
30504 statement, and continues with the output statements.
30505 When both parameters use the same variable, the
30506 compiler will treat them as the same %n operand, which is the case here.
30507
30508 Just as the @code{Outputs} parameter causes the register to be stored into the
30509 target variable after execution of the assembler statements, so does the
30510 @code{Inputs} parameter cause its variable to be loaded into the register
30511 before execution of the assembler statements.
30512
30513 Thus the effect of the @code{Asm} invocation is:
30514 @enumerate
30515 @item load the 32-bit value of @code{Value} into eax
30516 @item execute the @code{incl %eax} instruction
30517 @item store the contents of eax into the @code{Result} variable
30518 @end enumerate
30519
30520 The resulting assembler file (with @option{-O2} optimization) contains:
30521 @smallexample
30522 @group
30523 _increment__incr.1:
30524    subl $4,%esp
30525    movl 8(%esp),%eax
30526 #APP
30527    incl %eax
30528 #NO_APP
30529    movl %eax,%edx
30530    movl %ecx,(%esp)
30531    addl $4,%esp
30532    ret
30533 @end group
30534 @end smallexample
30535
30536 @c ---------------------------------------------------------------------------
30537 @node Inlining Inline Assembler Code
30538 @section Inlining Inline Assembler Code
30539
30540 @noindent
30541 For a short subprogram such as the @code{Incr} function in the previous
30542 section, the overhead of the call and return (creating / deleting the stack
30543 frame) can be significant, compared to the amount of code in the subprogram
30544 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30545 which directs the compiler to expand invocations of the subprogram at the
30546 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30547 Here is the resulting program:
30548
30549 @smallexample @c ada
30550 @group
30551 with Interfaces; use Interfaces;
30552 with Ada.Text_IO; use Ada.Text_IO;
30553 with System.Machine_Code; use System.Machine_Code;
30554 procedure Increment_2 is
30555
30556    function Incr (Value : Unsigned_32) return Unsigned_32 is
30557       Result : Unsigned_32;
30558    begin
30559       Asm ("incl %0",
30560            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30561            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30562       return Result;
30563    end Incr;
30564    pragma Inline (Increment);
30565
30566    Value : Unsigned_32;
30567
30568 begin
30569    Value := 5;
30570    Put_Line ("Value before is" & Value'Img);
30571    Value := Increment (Value);
30572    Put_Line ("Value after is" & Value'Img);
30573 end Increment_2;
30574 @end group
30575 @end smallexample
30576
30577 Compile the program with both optimization (@option{-O2}) and inlining
30578 (@option{-gnatn}) enabled.
30579
30580 The @code{Incr} function is still compiled as usual, but at the
30581 point in @code{Increment} where our function used to be called:
30582
30583 @smallexample
30584 @group
30585 pushl %edi
30586 call _increment__incr.1
30587 @end group
30588 @end smallexample
30589
30590 @noindent
30591 the code for the function body directly appears:
30592
30593 @smallexample
30594 @group
30595 movl %esi,%eax
30596 #APP
30597    incl %eax
30598 #NO_APP
30599    movl %eax,%edx
30600 @end group
30601 @end smallexample
30602
30603 @noindent
30604 thus saving the overhead of stack frame setup and an out-of-line call.
30605
30606 @c ---------------------------------------------------------------------------
30607 @node Other Asm Functionality
30608 @section Other @code{Asm} Functionality
30609
30610 @noindent
30611 This section describes two important parameters to the @code{Asm}
30612 procedure: @code{Clobber}, which identifies register usage;
30613 and @code{Volatile}, which inhibits unwanted optimizations.
30614
30615 @menu
30616 * The Clobber Parameter::
30617 * The Volatile Parameter::
30618 @end menu
30619
30620 @c ---------------------------------------------------------------------------
30621 @node The Clobber Parameter
30622 @subsection The @code{Clobber} Parameter
30623
30624 @noindent
30625 One of the dangers of intermixing assembly language and a compiled language
30626 such as Ada is that the compiler needs to be aware of which registers are
30627 being used by the assembly code.  In some cases, such as the earlier examples,
30628 the constraint string is sufficient to indicate register usage (e.g.,
30629 @code{"a"} for
30630 the eax register).  But more generally, the compiler needs an explicit
30631 identification of the registers that are used by the Inline Assembly
30632 statements.
30633
30634 Using a register that the compiler doesn't know about
30635 could be a side effect of an instruction (like @code{mull}
30636 storing its result in both eax and edx).
30637 It can also arise from explicit register usage in your
30638 assembly code; for example:
30639 @smallexample
30640 @group
30641 Asm ("movl %0, %%ebx" & LF & HT &
30642      "movl %%ebx, %1",
30643      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30644      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30645 @end group
30646 @end smallexample
30647 @noindent
30648 where the compiler (since it does not analyze the @code{Asm} template string)
30649 does not know you are using the ebx register.
30650
30651 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30652 to identify the registers that will be used by your assembly code:
30653
30654 @smallexample
30655 @group
30656 Asm ("movl %0, %%ebx" & LF & HT &
30657      "movl %%ebx, %1",
30658      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30659      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30660      Clobber => "ebx");
30661 @end group
30662 @end smallexample
30663
30664 The Clobber parameter is a static string expression specifying the
30665 register(s) you are using.  Note that register names are @emph{not} prefixed
30666 by a percent sign. Also, if more than one register is used then their names
30667 are separated by commas; e.g., @code{"eax, ebx"}
30668
30669 The @code{Clobber} parameter has several additional uses:
30670 @enumerate
30671 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30672 @item Use ``register'' name @code{memory} if you changed a memory location
30673 @end enumerate
30674
30675 @c ---------------------------------------------------------------------------
30676 @node The Volatile Parameter
30677 @subsection The @code{Volatile} Parameter
30678 @cindex Volatile parameter
30679
30680 @noindent
30681 Compiler optimizations in the presence of Inline Assembler may sometimes have
30682 unwanted effects.  For example, when an @code{Asm} invocation with an input
30683 variable is inside a loop, the compiler might move the loading of the input
30684 variable outside the loop, regarding it as a one-time initialization.
30685
30686 If this effect is not desired, you can disable such optimizations by setting
30687 the @code{Volatile} parameter to @code{True}; for example:
30688
30689 @smallexample @c ada
30690 @group
30691 Asm ("movl %0, %%ebx" & LF & HT &
30692      "movl %%ebx, %1",
30693      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30694      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30695      Clobber  => "ebx",
30696      Volatile => True);
30697 @end group
30698 @end smallexample
30699
30700 By default, @code{Volatile} is set to @code{False} unless there is no
30701 @code{Outputs} parameter.
30702
30703 Although setting @code{Volatile} to @code{True} prevents unwanted
30704 optimizations, it will also disable other optimizations that might be
30705 important for efficiency. In general, you should set @code{Volatile}
30706 to @code{True} only if the compiler's optimizations have created
30707 problems.
30708 @c END OF INLINE ASSEMBLER CHAPTER
30709 @c ===============================
30710
30711 @c ***********************************
30712 @c * Compatibility and Porting Guide *
30713 @c ***********************************
30714 @node Compatibility and Porting Guide
30715 @appendix Compatibility and Porting Guide
30716
30717 @noindent
30718 This chapter describes the compatibility issues that may arise between
30719 GNAT and other Ada compilation systems (including those for Ada 83),
30720 and shows how GNAT can expedite porting
30721 applications developed in other Ada environments.
30722
30723 @menu
30724 * Compatibility with Ada 83::
30725 * Compatibility between Ada 95 and Ada 2005::
30726 * Implementation-dependent characteristics::
30727 * Compatibility with Other Ada Systems::
30728 * Representation Clauses::
30729 @ifclear vms
30730 @c Brief section is only in non-VMS version
30731 @c Full chapter is in VMS version
30732 * Compatibility with HP Ada 83::
30733 @end ifclear
30734 @ifset vms
30735 * Transitioning to 64-Bit GNAT for OpenVMS::
30736 @end ifset
30737 @end menu
30738
30739 @node Compatibility with Ada 83
30740 @section Compatibility with Ada 83
30741 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30742
30743 @noindent
30744 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30745 particular, the design intention was that the difficulties associated
30746 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30747 that occur when moving from one Ada 83 system to another.
30748
30749 However, there are a number of points at which there are minor
30750 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30751 full details of these issues,
30752 and should be consulted for a complete treatment.
30753 In practice the
30754 following subsections treat the most likely issues to be encountered.
30755
30756 @menu
30757 * Legal Ada 83 programs that are illegal in Ada 95::
30758 * More deterministic semantics::
30759 * Changed semantics::
30760 * Other language compatibility issues::
30761 @end menu
30762
30763 @node Legal Ada 83 programs that are illegal in Ada 95
30764 @subsection Legal Ada 83 programs that are illegal in Ada 95
30765
30766 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30767 Ada 95 and thus also in Ada 2005:
30768
30769 @table @emph
30770 @item Character literals
30771 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30772 @code{Wide_Character} as a new predefined character type, some uses of
30773 character literals that were legal in Ada 83 are illegal in Ada 95.
30774 For example:
30775 @smallexample @c ada
30776    for Char in 'A' .. 'Z' loop @dots{} end loop;
30777 @end smallexample
30778
30779 @noindent
30780 The problem is that @code{'A'} and @code{'Z'} could be from either
30781 @code{Character} or @code{Wide_Character}.  The simplest correction
30782 is to make the type explicit; e.g.:
30783 @smallexample @c ada
30784    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30785 @end smallexample
30786
30787 @item New reserved words
30788 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30789 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30790 Existing Ada 83 code using any of these identifiers must be edited to
30791 use some alternative name.
30792
30793 @item Freezing rules
30794 The rules in Ada 95 are slightly different with regard to the point at
30795 which entities are frozen, and representation pragmas and clauses are
30796 not permitted past the freeze point.  This shows up most typically in
30797 the form of an error message complaining that a representation item
30798 appears too late, and the appropriate corrective action is to move
30799 the item nearer to the declaration of the entity to which it refers.
30800
30801 A particular case is that representation pragmas
30802 @ifset vms
30803 (including the
30804 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30805 @end ifset
30806 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30807 declaration must be introduced to which the pragma can be applied.
30808
30809 @item Optional bodies for library packages
30810 In Ada 83, a package that did not require a package body was nevertheless
30811 allowed to have one.  This lead to certain surprises in compiling large
30812 systems (situations in which the body could be unexpectedly ignored by the
30813 binder).  In Ada 95, if a package does not require a body then it is not
30814 permitted to have a body.  To fix this problem, simply remove a redundant
30815 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30816 into the spec that makes the body required.  One approach is to add a private
30817 part to the package declaration (if necessary), and define a parameterless
30818 procedure called @code{Requires_Body}, which must then be given a dummy
30819 procedure body in the package body, which then becomes required.
30820 Another approach (assuming that this does not introduce elaboration
30821 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30822 since one effect of this pragma is to require the presence of a package body.
30823
30824 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30825 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30826 @code{Constraint_Error}.
30827 This means that it is illegal to have separate exception handlers for
30828 the two exceptions.  The fix is simply to remove the handler for the
30829 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30830 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30831
30832 @item Indefinite subtypes in generics
30833 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30834 as the actual for a generic formal private type, but then the instantiation
30835 would be illegal if there were any instances of declarations of variables
30836 of this type in the generic body.  In Ada 95, to avoid this clear violation
30837 of the methodological principle known as the ``contract model'',
30838 the generic declaration explicitly indicates whether
30839 or not such instantiations are permitted.  If a generic formal parameter
30840 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30841 type name, then it can be instantiated with indefinite types, but no
30842 stand-alone variables can be declared of this type.  Any attempt to declare
30843 such a variable will result in an illegality at the time the generic is
30844 declared.  If the @code{(<>)} notation is not used, then it is illegal
30845 to instantiate the generic with an indefinite type.
30846 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30847 It will show up as a compile time error, and
30848 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30849 @end table
30850
30851 @node More deterministic semantics
30852 @subsection More deterministic semantics
30853
30854 @table @emph
30855 @item Conversions
30856 Conversions from real types to integer types round away from 0.  In Ada 83
30857 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30858 implementation freedom was intended to support unbiased rounding in
30859 statistical applications, but in practice it interfered with portability.
30860 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30861 is required.  Numeric code may be affected by this change in semantics.
30862 Note, though, that this issue is no worse than already existed in Ada 83
30863 when porting code from one vendor to another.
30864
30865 @item Tasking
30866 The Real-Time Annex introduces a set of policies that define the behavior of
30867 features that were implementation dependent in Ada 83, such as the order in
30868 which open select branches are executed.
30869 @end table
30870
30871 @node Changed semantics
30872 @subsection Changed semantics
30873
30874 @noindent
30875 The worst kind of incompatibility is one where a program that is legal in
30876 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30877 possible in Ada 83.  Fortunately this is extremely rare, but the one
30878 situation that you should be alert to is the change in the predefined type
30879 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30880
30881 @table @emph
30882 @item Range of type @code{Character}
30883 The range of @code{Standard.Character} is now the full 256 characters
30884 of Latin-1, whereas in most Ada 83 implementations it was restricted
30885 to 128 characters. Although some of the effects of
30886 this change will be manifest in compile-time rejection of legal
30887 Ada 83 programs it is possible for a working Ada 83 program to have
30888 a different effect in Ada 95, one that was not permitted in Ada 83.
30889 As an example, the expression
30890 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30891 delivers @code{255} as its value.
30892 In general, you should look at the logic of any
30893 character-processing Ada 83 program and see whether it needs to be adapted
30894 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
30895 character handling package that may be relevant if code needs to be adapted
30896 to account for the additional Latin-1 elements.
30897 The desirable fix is to
30898 modify the program to accommodate the full character set, but in some cases
30899 it may be convenient to define a subtype or derived type of Character that
30900 covers only the restricted range.
30901 @cindex Latin-1
30902 @end table
30903
30904 @node Other language compatibility issues
30905 @subsection Other language compatibility issues
30906
30907 @table @emph
30908 @item @option{-gnat83} switch
30909 All implementations of GNAT provide a switch that causes GNAT to operate
30910 in Ada 83 mode.  In this mode, some but not all compatibility problems
30911 of the type described above are handled automatically.  For example, the
30912 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30913 as identifiers as in Ada 83.
30914 However,
30915 in practice, it is usually advisable to make the necessary modifications
30916 to the program to remove the need for using this switch.
30917 See @ref{Compiling Different Versions of Ada}.
30918
30919 @item Support for removed Ada 83 pragmas and attributes
30920 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30921 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
30922 compilers are allowed, but not required, to implement these missing
30923 elements.  In contrast with some other compilers, GNAT implements all
30924 such pragmas and attributes, eliminating this compatibility concern.  These
30925 include @code{pragma Interface} and the floating point type attributes
30926 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30927 @end table
30928
30929
30930 @node Compatibility between Ada 95 and Ada 2005
30931 @section Compatibility between Ada 95 and Ada 2005
30932 @cindex Compatibility between Ada 95 and Ada 2005
30933
30934 @noindent
30935 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30936 a number of incompatibilities. Several are enumerated below;
30937 for a complete description please see the
30938 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30939 @cite{Rationale for Ada 2005}.
30940
30941 @table @emph
30942 @item New reserved words.
30943 The words @code{interface}, @code{overriding} and @code{synchronized} are
30944 reserved in Ada 2005.
30945 A pre-Ada 2005 program that uses any of these as an identifier will be
30946 illegal.
30947
30948 @item New declarations in predefined packages.
30949 A number of packages in the predefined environment contain new declarations:
30950 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30951 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30952 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30953 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30954 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30955 If an Ada 95 program does a @code{with} and @code{use} of any of these
30956 packages, the new declarations may cause name clashes.
30957
30958 @item Access parameters.
30959 A nondispatching subprogram with an access parameter cannot be renamed
30960 as a dispatching operation.  This was permitted in Ada 95.
30961
30962 @item Access types, discriminants, and constraints.
30963 Rule changes in this area have led to some incompatibilities; for example,
30964 constrained subtypes of some access types are not permitted in Ada 2005.
30965
30966 @item Aggregates for limited types.
30967 The allowance of aggregates for limited types in Ada 2005 raises the
30968 possibility of ambiguities in legal Ada 95 programs, since additional types
30969 now need to be considered in expression resolution.
30970
30971 @item Fixed-point multiplication and division.
30972 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30973 were legal in Ada 95 and invoked the predefined versions of these operations,
30974 are now ambiguous.
30975 The ambiguity may be resolved either by applying a type conversion to the
30976 expression, or by explicitly invoking the operation from package
30977 @code{Standard}.
30978
30979 @item Return-by-reference types.
30980 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
30981 can declare a function returning a value from an anonymous access type.
30982 @end table
30983
30984
30985 @node Implementation-dependent characteristics
30986 @section Implementation-dependent characteristics
30987 @noindent
30988 Although the Ada language defines the semantics of each construct as
30989 precisely as practical, in some situations (for example for reasons of
30990 efficiency, or where the effect is heavily dependent on the host or target
30991 platform) the implementation is allowed some freedom.  In porting Ada 83
30992 code to GNAT, you need to be aware of whether / how the existing code
30993 exercised such implementation dependencies.  Such characteristics fall into
30994 several categories, and GNAT offers specific support in assisting the
30995 transition from certain Ada 83 compilers.
30996
30997 @menu
30998 * Implementation-defined pragmas::
30999 * Implementation-defined attributes::
31000 * Libraries::
31001 * Elaboration order::
31002 * Target-specific aspects::
31003 @end menu
31004
31005 @node Implementation-defined pragmas
31006 @subsection Implementation-defined pragmas
31007
31008 @noindent
31009 Ada compilers are allowed to supplement the language-defined pragmas, and
31010 these are a potential source of non-portability.  All GNAT-defined pragmas
31011 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31012 Reference Manual}, and these include several that are specifically
31013 intended to correspond to other vendors' Ada 83 pragmas.
31014 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31015 For compatibility with HP Ada 83, GNAT supplies the pragmas
31016 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31017 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31018 and @code{Volatile}.
31019 Other relevant pragmas include @code{External} and @code{Link_With}.
31020 Some vendor-specific
31021 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31022 recognized, thus
31023 avoiding compiler rejection of units that contain such pragmas; they are not
31024 relevant in a GNAT context and hence are not otherwise implemented.
31025
31026 @node Implementation-defined attributes
31027 @subsection Implementation-defined attributes
31028
31029 Analogous to pragmas, the set of attributes may be extended by an
31030 implementation.  All GNAT-defined attributes are described in
31031 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31032 Manual}, and these include several that are specifically intended
31033 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31034 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31035 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31036 @code{Type_Class}.
31037
31038 @node Libraries
31039 @subsection Libraries
31040 @noindent
31041 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31042 code uses vendor-specific libraries then there are several ways to manage
31043 this in Ada 95 or Ada 2005:
31044 @enumerate
31045 @item
31046 If the source code for the libraries (specs and bodies) are
31047 available, then the libraries can be migrated in the same way as the
31048 application.
31049 @item
31050 If the source code for the specs but not the bodies are
31051 available, then you can reimplement the bodies.
31052 @item
31053 Some features introduced by Ada 95 obviate the need for library support.  For
31054 example most Ada 83 vendors supplied a package for unsigned integers.  The
31055 Ada 95 modular type feature is the preferred way to handle this need, so
31056 instead of migrating or reimplementing the unsigned integer package it may
31057 be preferable to retrofit the application using modular types.
31058 @end enumerate
31059
31060 @node Elaboration order
31061 @subsection Elaboration order
31062 @noindent
31063 The implementation can choose any elaboration order consistent with the unit
31064 dependency relationship.  This freedom means that some orders can result in
31065 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31066 to invoke a subprogram its body has been elaborated, or to instantiate a
31067 generic before the generic body has been elaborated.  By default GNAT
31068 attempts to choose a safe order (one that will not encounter access before
31069 elaboration problems) by implicitly inserting @code{Elaborate} or
31070 @code{Elaborate_All} pragmas where
31071 needed.  However, this can lead to the creation of elaboration circularities
31072 and a resulting rejection of the program by gnatbind.  This issue is
31073 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31074 In brief, there are several
31075 ways to deal with this situation:
31076
31077 @itemize @bullet
31078 @item
31079 Modify the program to eliminate the circularities, e.g.@: by moving
31080 elaboration-time code into explicitly-invoked procedures
31081 @item
31082 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31083 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31084 @code{Elaborate_All}
31085 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31086 (by selectively suppressing elaboration checks via pragma
31087 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31088 @end itemize
31089
31090 @node Target-specific aspects
31091 @subsection Target-specific aspects
31092 @noindent
31093 Low-level applications need to deal with machine addresses, data
31094 representations, interfacing with assembler code, and similar issues.  If
31095 such an Ada 83 application is being ported to different target hardware (for
31096 example where the byte endianness has changed) then you will need to
31097 carefully examine the program logic; the porting effort will heavily depend
31098 on the robustness of the original design.  Moreover, Ada 95 (and thus
31099 Ada 2005) are sometimes
31100 incompatible with typical Ada 83 compiler practices regarding implicit
31101 packing, the meaning of the Size attribute, and the size of access values.
31102 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31103
31104 @node Compatibility with Other Ada Systems
31105 @section Compatibility with Other Ada Systems
31106
31107 @noindent
31108 If programs avoid the use of implementation dependent and
31109 implementation defined features, as documented in the @cite{Ada
31110 Reference Manual}, there should be a high degree of portability between
31111 GNAT and other Ada systems.  The following are specific items which
31112 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31113 compilers, but do not affect porting code to GNAT@.
31114 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31115 the following issues may or may not arise for Ada 2005 programs
31116 when other compilers appear.)
31117
31118 @table @emph
31119 @item Ada 83 Pragmas and Attributes
31120 Ada 95 compilers are allowed, but not required, to implement the missing
31121 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31122 GNAT implements all such pragmas and attributes, eliminating this as
31123 a compatibility concern, but some other Ada 95 compilers reject these
31124 pragmas and attributes.
31125
31126 @item Specialized Needs Annexes
31127 GNAT implements the full set of special needs annexes.  At the
31128 current time, it is the only Ada 95 compiler to do so.  This means that
31129 programs making use of these features may not be portable to other Ada
31130 95 compilation systems.
31131
31132 @item Representation Clauses
31133 Some other Ada 95 compilers implement only the minimal set of
31134 representation clauses required by the Ada 95 reference manual.  GNAT goes
31135 far beyond this minimal set, as described in the next section.
31136 @end table
31137
31138 @node Representation Clauses
31139 @section Representation Clauses
31140
31141 @noindent
31142 The Ada 83 reference manual was quite vague in describing both the minimal
31143 required implementation of representation clauses, and also their precise
31144 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31145 minimal set of capabilities required is still quite limited.
31146
31147 GNAT implements the full required set of capabilities in
31148 Ada 95 and Ada 2005, but also goes much further, and in particular
31149 an effort has been made to be compatible with existing Ada 83 usage to the
31150 greatest extent possible.
31151
31152 A few cases exist in which Ada 83 compiler behavior is incompatible with
31153 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31154 intentional or accidental dependence on specific implementation dependent
31155 characteristics of these Ada 83 compilers.  The following is a list of
31156 the cases most likely to arise in existing Ada 83 code.
31157
31158 @table @emph
31159 @item Implicit Packing
31160 Some Ada 83 compilers allowed a Size specification to cause implicit
31161 packing of an array or record.  This could cause expensive implicit
31162 conversions for change of representation in the presence of derived
31163 types, and the Ada design intends to avoid this possibility.
31164 Subsequent AI's were issued to make it clear that such implicit
31165 change of representation in response to a Size clause is inadvisable,
31166 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31167 Reference Manuals as implementation advice that is followed by GNAT@.
31168 The problem will show up as an error
31169 message rejecting the size clause.  The fix is simply to provide
31170 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31171 a Component_Size clause.
31172
31173 @item Meaning of Size Attribute
31174 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31175 the minimal number of bits required to hold values of the type.  For example,
31176 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31177 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31178 some 32 in this situation.  This problem will usually show up as a compile
31179 time error, but not always.  It is a good idea to check all uses of the
31180 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31181 Object_Size can provide a useful way of duplicating the behavior of
31182 some Ada 83 compiler systems.
31183
31184 @item Size of Access Types
31185 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31186 and that therefore it will be the same size as a System.Address value.  This
31187 assumption is true for GNAT in most cases with one exception.  For the case of
31188 a pointer to an unconstrained array type (where the bounds may vary from one
31189 value of the access type to another), the default is to use a ``fat pointer'',
31190 which is represented as two separate pointers, one to the bounds, and one to
31191 the array.  This representation has a number of advantages, including improved
31192 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31193 code which makes the assumption that, for example, pointers fit in 32 bits on
31194 a machine with 32-bit addressing.
31195
31196 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31197 access types in this case (where the designated type is an unconstrained array
31198 type).  These thin pointers are indeed the same size as a System.Address value.
31199 To specify a thin pointer, use a size clause for the type, for example:
31200
31201 @smallexample @c ada
31202 type X is access all String;
31203 for X'Size use Standard'Address_Size;
31204 @end smallexample
31205
31206 @noindent
31207 which will cause the type X to be represented using a single pointer.
31208 When using this representation, the bounds are right behind the array.
31209 This representation is slightly less efficient, and does not allow quite
31210 such flexibility in the use of foreign pointers or in using the
31211 Unrestricted_Access attribute to create pointers to non-aliased objects.
31212 But for any standard portable use of the access type it will work in
31213 a functionally correct manner and allow porting of existing code.
31214 Note that another way of forcing a thin pointer representation
31215 is to use a component size clause for the element size in an array,
31216 or a record representation clause for an access field in a record.
31217 @end table
31218
31219 @ifclear vms
31220 @c This brief section is only in the non-VMS version
31221 @c The complete chapter on HP Ada is in the VMS version
31222 @node Compatibility with HP Ada 83
31223 @section Compatibility with HP Ada 83
31224
31225 @noindent
31226 The VMS version of GNAT fully implements all the pragmas and attributes
31227 provided by HP Ada 83, as well as providing the standard HP Ada 83
31228 libraries, including Starlet.  In addition, data layouts and parameter
31229 passing conventions are highly compatible.  This means that porting
31230 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31231 most other porting efforts.  The following are some of the most
31232 significant differences between GNAT and HP Ada 83.
31233
31234 @table @emph
31235 @item Default floating-point representation
31236 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31237 it is VMS format.  GNAT does implement the necessary pragmas
31238 (Long_Float, Float_Representation) for changing this default.
31239
31240 @item System
31241 The package System in GNAT exactly corresponds to the definition in the
31242 Ada 95 reference manual, which means that it excludes many of the
31243 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31244 that contains the additional definitions, and a special pragma,
31245 Extend_System allows this package to be treated transparently as an
31246 extension of package System.
31247
31248 @item To_Address
31249 The definitions provided by Aux_DEC are exactly compatible with those
31250 in the HP Ada 83 version of System, with one exception.
31251 HP Ada provides the following declarations:
31252
31253 @smallexample @c ada
31254 TO_ADDRESS (INTEGER)
31255 TO_ADDRESS (UNSIGNED_LONGWORD)
31256 TO_ADDRESS (@i{universal_integer})
31257 @end smallexample
31258
31259 @noindent
31260 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31261 an extension to Ada 83 not strictly compatible with the reference manual.
31262 In GNAT, we are constrained to be exactly compatible with the standard,
31263 and this means we cannot provide this capability.  In HP Ada 83, the
31264 point of this definition is to deal with a call like:
31265
31266 @smallexample @c ada
31267 TO_ADDRESS (16#12777#);
31268 @end smallexample
31269
31270 @noindent
31271 Normally, according to the Ada 83 standard, one would expect this to be
31272 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31273 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31274 definition using @i{universal_integer} takes precedence.
31275
31276 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31277 is not possible to be 100% compatible.  Since there are many programs using
31278 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31279 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31280 declarations provided in the GNAT version of AUX_Dec are:
31281
31282 @smallexample @c ada
31283 function To_Address (X : Integer) return Address;
31284 pragma Pure_Function (To_Address);
31285
31286 function To_Address_Long (X : Unsigned_Longword)
31287  return Address;
31288 pragma Pure_Function (To_Address_Long);
31289 @end smallexample
31290
31291 @noindent
31292 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31293 change the name to TO_ADDRESS_LONG@.
31294
31295 @item Task_Id values
31296 The Task_Id values assigned will be different in the two systems, and GNAT
31297 does not provide a specified value for the Task_Id of the environment task,
31298 which in GNAT is treated like any other declared task.
31299 @end table
31300
31301 @noindent
31302 For full details on these and other less significant compatibility issues,
31303 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31304 Overview and Comparison on HP Platforms}.
31305
31306 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31307 attributes are recognized, although only a subset of them can sensibly
31308 be implemented.  The description of pragmas in @ref{Implementation
31309 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31310 indicates whether or not they are applicable to non-VMS systems.
31311 @end ifclear
31312
31313 @ifset vms
31314 @node Transitioning to 64-Bit GNAT for OpenVMS
31315 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31316
31317 @noindent
31318 This section is meant to assist users of pre-2006 @value{EDITION}
31319 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31320 the version of the GNAT technology supplied in 2006 and later for
31321 OpenVMS on both Alpha and I64.
31322
31323 @menu
31324 * Introduction to transitioning::
31325 * Migration of 32 bit code::
31326 * Taking advantage of 64 bit addressing::
31327 * Technical details::
31328 @end menu
31329
31330 @node Introduction to transitioning
31331 @subsection Introduction
31332
31333 @noindent
31334 64-bit @value{EDITION} for Open VMS has been designed to meet
31335 three main goals:
31336
31337 @enumerate
31338 @item
31339 Providing a full conforming implementation of Ada 95 and Ada 2005
31340
31341 @item
31342 Allowing maximum backward compatibility, thus easing migration of existing
31343 Ada source code
31344
31345 @item
31346 Supplying a path for exploiting the full 64-bit address range
31347 @end enumerate
31348
31349 @noindent
31350 Ada's strong typing semantics has made it
31351 impractical to have different 32-bit and 64-bit modes. As soon as
31352 one object could possibly be outside the 32-bit address space, this
31353 would make it necessary for the @code{System.Address} type to be 64 bits.
31354 In particular, this would cause inconsistencies if 32-bit code is
31355 called from 64-bit code that raises an exception.
31356
31357 This issue has been resolved by always using 64-bit addressing
31358 at the system level, but allowing for automatic conversions between
31359 32-bit and 64-bit addresses where required. Thus users who
31360 do not currently require 64-bit addressing capabilities, can
31361 recompile their code with only minimal changes (and indeed
31362 if the code is written in portable Ada, with no assumptions about
31363 the size of the @code{Address} type, then no changes at all are necessary).
31364 At the same time,
31365 this approach provides a simple, gradual upgrade path to future
31366 use of larger memories than available for 32-bit systems.
31367 Also, newly written applications or libraries will by default
31368 be fully compatible with future systems exploiting 64-bit
31369 addressing capabilities.
31370
31371 @ref{Migration of 32 bit code}, will focus on porting applications
31372 that do not require more than 2 GB of
31373 addressable memory. This code will be referred to as
31374 @emph{32-bit code}.
31375 For applications intending to exploit the full 64-bit address space,
31376 @ref{Taking advantage of 64 bit addressing},
31377 will consider further changes that may be required.
31378 Such code will be referred to below as @emph{64-bit code}.
31379
31380 @node Migration of 32 bit code
31381 @subsection Migration of 32-bit code
31382
31383 @menu
31384 * Address types::
31385 * Access types::
31386 * Unchecked conversions::
31387 * Predefined constants::
31388 * Interfacing with C::
31389 * Experience with source compatibility::
31390 @end menu
31391
31392 @node Address types
31393 @subsubsection Address types
31394
31395 @noindent
31396 To solve the problem of mixing 64-bit and 32-bit addressing,
31397 while maintaining maximum backward compatibility, the following
31398 approach has been taken:
31399
31400 @itemize @bullet
31401 @item
31402 @code{System.Address} always has a size of 64 bits
31403
31404 @item
31405 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31406 @end itemize
31407
31408 @noindent
31409 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31410 a @code{Short_Address}
31411 may be used where an @code{Address} is required, and vice versa, without
31412 needing explicit type conversions.
31413 By virtue of the Open VMS parameter passing conventions,
31414 even imported
31415 and exported subprograms that have 32-bit address parameters are
31416 compatible with those that have 64-bit address parameters.
31417 (See @ref{Making code 64 bit clean} for details.)
31418
31419 The areas that may need attention are those where record types have
31420 been defined that contain components of the type @code{System.Address}, and
31421 where objects of this type are passed to code expecting a record layout with
31422 32-bit addresses.
31423
31424 Different compilers on different platforms cannot be
31425 expected to represent the same type in the same way,
31426 since alignment constraints
31427 and other system-dependent properties affect the compiler's decision.
31428 For that reason, Ada code
31429 generally uses representation clauses to specify the expected
31430 layout where required.
31431
31432 If such a representation clause uses 32 bits for a component having
31433 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31434 will detect that error and produce a specific diagnostic message.
31435 The developer should then determine whether the representation
31436 should be 64 bits or not and make either of two changes:
31437 change the size to 64 bits and leave the type as @code{System.Address}, or
31438 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31439 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31440 required in any code setting or accessing the field; the compiler will
31441 automatically perform any needed conversions between address
31442 formats.
31443
31444 @node Access types
31445 @subsubsection Access types
31446
31447 @noindent
31448 By default, objects designated by access values are always
31449 allocated in the 32-bit
31450 address space. Thus legacy code will never contain
31451 any objects that are not addressable with 32-bit addresses, and
31452 the compiler will never raise exceptions as result of mixing
31453 32-bit and 64-bit addresses.
31454
31455 However, the access values themselves are represented in 64 bits, for optimum
31456 performance and future compatibility with 64-bit code. As was
31457 the case with @code{System.Address}, the compiler will give an error message
31458 if an object or record component has a representation clause that
31459 requires the access value to fit in 32 bits. In such a situation,
31460 an explicit size clause for the access type, specifying 32 bits,
31461 will have the desired effect.
31462
31463 General access types (declared with @code{access all}) can never be
31464 32 bits, as values of such types must be able to refer to any object
31465 of the  designated type,
31466 including objects residing outside the 32-bit address range.
31467 Existing Ada 83 code will not contain such type definitions,
31468 however, since general access types were introduced in Ada 95.
31469
31470 @node Unchecked conversions
31471 @subsubsection Unchecked conversions
31472
31473 @noindent
31474 In the case of an @code{Unchecked_Conversion} where the source type is a
31475 64-bit access type or the type @code{System.Address}, and the target
31476 type is a 32-bit type, the compiler will generate a warning.
31477 Even though the generated code will still perform the required
31478 conversions, it is highly recommended in these cases to use
31479 respectively a 32-bit access type or @code{System.Short_Address}
31480 as the source type.
31481
31482 @node Predefined constants
31483 @subsubsection Predefined constants
31484
31485 @noindent
31486 The following table shows the correspondence between pre-2006 versions of
31487 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31488 (``New''):
31489
31490 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31491 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31492 @item   @code{System.Word_Size}          @tab 32      @tab 64
31493 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31494 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31495 @item   @code{System.Address_Size}       @tab 32      @tab 64
31496 @end multitable
31497
31498 @noindent
31499 If you need to refer to the specific
31500 memory size of a 32-bit implementation, instead of the
31501 actual memory size, use @code{System.Short_Memory_Size}
31502 rather than @code{System.Memory_Size}.
31503 Similarly, references to @code{System.Address_Size} may need
31504 to be replaced by @code{System.Short_Address'Size}.
31505 The program @command{gnatfind} may be useful for locating
31506 references to the above constants, so that you can verify that they
31507 are still correct.
31508
31509 @node Interfacing with C
31510 @subsubsection Interfacing with C
31511
31512 @noindent
31513 In order to minimize the impact of the transition to 64-bit addresses on
31514 legacy programs, some fundamental types in the @code{Interfaces.C}
31515 package hierarchy continue to be represented in 32 bits.
31516 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31517 This eases integration with the default HP C layout choices, for example
31518 as found in the system routines in @code{DECC$SHR.EXE}.
31519 Because of this implementation choice, the type fully compatible with
31520 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31521 Depending on the context the compiler will issue a
31522 warning or an error when type @code{Address} is used, alerting the user to a
31523 potential problem. Otherwise 32-bit programs that use
31524 @code{Interfaces.C} should normally not require code modifications
31525
31526 The other issue arising with C interfacing concerns pragma @code{Convention}.
31527 For VMS 64-bit systems, there is an issue of the appropriate default size
31528 of C convention pointers in the absence of an explicit size clause. The HP
31529 C compiler can choose either 32 or 64 bits depending on compiler options.
31530 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31531 clause is given. This proves a better choice for porting 32-bit legacy
31532 applications. In order to have a 64-bit representation, it is necessary to
31533 specify a size representation clause. For example:
31534
31535 @smallexample @c ada
31536 type int_star is access Interfaces.C.int;
31537 pragma Convention(C, int_star);
31538 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31539 @end smallexample
31540
31541 @node Experience with source compatibility
31542 @subsubsection Experience with source compatibility
31543
31544 @noindent
31545 The Security Server and STARLET on I64 provide an interesting ``test case''
31546 for source compatibility issues, since it is in such system code
31547 where assumptions about @code{Address} size might be expected to occur.
31548 Indeed, there were a small number of occasions in the Security Server
31549 file @file{jibdef.ads}
31550 where a representation clause for a record type specified
31551 32 bits for a component of type @code{Address}.
31552 All of these errors were detected by the compiler.
31553 The repair was obvious and immediate; to simply replace @code{Address} by
31554 @code{Short_Address}.
31555
31556 In the case of STARLET, there were several record types that should
31557 have had representation clauses but did not.  In these record types
31558 there was an implicit assumption that an @code{Address} value occupied
31559 32 bits.
31560 These compiled without error, but their usage resulted in run-time error
31561 returns from STARLET system calls.
31562 Future GNAT technology enhancements may include a tool that detects and flags
31563 these sorts of potential source code porting problems.
31564
31565 @c ****************************************
31566 @node Taking advantage of 64 bit addressing
31567 @subsection Taking advantage of 64-bit addressing
31568
31569 @menu
31570 * Making code 64 bit clean::
31571 * Allocating memory from the 64 bit storage pool::
31572 * Restrictions on use of 64 bit objects::
31573 * Using 64 bit storage pools by default::
31574 * General access types::
31575 * STARLET and other predefined libraries::
31576 @end menu
31577
31578 @node Making code 64 bit clean
31579 @subsubsection Making code 64-bit clean
31580
31581 @noindent
31582 In order to prevent problems that may occur when (parts of) a
31583 system start using memory outside the 32-bit address range,
31584 we recommend some additional guidelines:
31585
31586 @itemize @bullet
31587 @item
31588 For imported subprograms that take parameters of the
31589 type @code{System.Address}, ensure that these subprograms can
31590 indeed handle 64-bit addresses. If not, or when in doubt,
31591 change the subprogram declaration to specify
31592 @code{System.Short_Address} instead.
31593
31594 @item
31595 Resolve all warnings related to size mismatches in
31596 unchecked conversions. Failing to do so causes
31597 erroneous execution if the source object is outside
31598 the 32-bit address space.
31599
31600 @item
31601 (optional) Explicitly use the 32-bit storage pool
31602 for access types used in a 32-bit context, or use
31603 generic access types where possible
31604 (@pxref{Restrictions on use of 64 bit objects}).
31605 @end itemize
31606
31607 @noindent
31608 If these rules are followed, the compiler will automatically insert
31609 any necessary checks to ensure that no addresses or access values
31610 passed to 32-bit code ever refer to objects outside the 32-bit
31611 address range.
31612 Any attempt to do this will raise @code{Constraint_Error}.
31613
31614 @node Allocating memory from the 64 bit storage pool
31615 @subsubsection Allocating memory from the 64-bit storage pool
31616
31617 @noindent
31618 For any access type @code{T} that potentially requires memory allocations
31619 beyond the 32-bit address space,
31620 use the following representation clause:
31621
31622 @smallexample @c ada
31623    for T'Storage_Pool use System.Pool_64;
31624 @end smallexample
31625
31626 @node Restrictions on use of 64 bit objects
31627 @subsubsection Restrictions on use of 64-bit objects
31628
31629 @noindent
31630 Taking the address of an object allocated from a 64-bit storage pool,
31631 and then passing this address to a subprogram expecting
31632 @code{System.Short_Address},
31633 or assigning it to a variable of type @code{Short_Address}, will cause
31634 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31635 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31636 no exception is raised and execution
31637 will become erroneous.
31638
31639 @node Using 64 bit storage pools by default
31640 @subsubsection Using 64-bit storage pools by default
31641
31642 @noindent
31643 In some cases it may be desirable to have the compiler allocate
31644 from 64-bit storage pools by default. This may be the case for
31645 libraries that are 64-bit clean, but may be used in both 32-bit
31646 and 64-bit contexts. For these cases the following configuration
31647 pragma may be specified:
31648
31649 @smallexample @c ada
31650   pragma Pool_64_Default;
31651 @end smallexample
31652
31653 @noindent
31654 Any code compiled in the context of this pragma will by default
31655 use the @code{System.Pool_64} storage pool. This default may be overridden
31656 for a specific access type @code{T} by the representation clause:
31657
31658 @smallexample @c ada
31659    for T'Storage_Pool use System.Pool_32;
31660 @end smallexample
31661
31662 @noindent
31663 Any object whose address may be passed to a subprogram with a
31664 @code{Short_Address} argument, or assigned to a variable of type
31665 @code{Short_Address}, needs to be allocated from this pool.
31666
31667 @node General access types
31668 @subsubsection General access types
31669
31670 @noindent
31671 Objects designated by access values from a
31672 general access type (declared with @code{access all}) are never allocated
31673 from a 64-bit storage pool. Code that uses general access types will
31674 accept objects allocated in either 32-bit or 64-bit address spaces,
31675 but never allocate objects outside the 32-bit address space.
31676 Using general access types ensures maximum compatibility with both
31677 32-bit and 64-bit code.
31678
31679 @node STARLET and other predefined libraries
31680 @subsubsection STARLET and other predefined libraries
31681
31682 @noindent
31683 All code that comes as part of GNAT is 64-bit clean, but the
31684 restrictions given in @ref{Restrictions on use of 64 bit objects},
31685 still apply. Look at the package
31686 specs to see in which contexts objects allocated
31687 in 64-bit address space are acceptable.
31688
31689 @node Technical details
31690 @subsection Technical details
31691
31692 @noindent
31693 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31694 Ada standard with respect to the type of @code{System.Address}. Previous
31695 versions of GNAT Pro have defined this type as private and implemented it as a
31696 modular type.
31697
31698 In order to allow defining @code{System.Short_Address} as a proper subtype,
31699 and to match the implicit sign extension in parameter passing,
31700 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31701 visible (i.e., non-private) integer type.
31702 Standard operations on the type, such as the binary operators ``+'', ``-'',
31703 etc., that take @code{Address} operands and return an @code{Address} result,
31704 have been hidden by declaring these
31705 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31706 ambiguities that would otherwise result from overloading.
31707 (Note that, although @code{Address} is a visible integer type,
31708 good programming practice dictates against exploiting the type's
31709 integer properties such as literals, since this will compromise
31710 code portability.)
31711
31712 Defining @code{Address} as a visible integer type helps achieve
31713 maximum compatibility for existing Ada code,
31714 without sacrificing the capabilities of the 64-bit architecture.
31715 @end ifset
31716
31717 @c ************************************************
31718 @ifset unw
31719 @node Microsoft Windows Topics
31720 @appendix Microsoft Windows Topics
31721 @cindex Windows NT
31722 @cindex Windows 95
31723 @cindex Windows 98
31724
31725 @noindent
31726 This chapter describes topics that are specific to the Microsoft Windows
31727 platforms (NT, 2000, and XP Professional).
31728
31729 @menu
31730 * Using GNAT on Windows::
31731 * Using a network installation of GNAT::
31732 * CONSOLE and WINDOWS subsystems::
31733 * Temporary Files::
31734 * Mixed-Language Programming on Windows::
31735 * Windows Calling Conventions::
31736 * Introduction to Dynamic Link Libraries (DLLs)::
31737 * Using DLLs with GNAT::
31738 * Building DLLs with GNAT::
31739 * Building DLLs with GNAT Project files::
31740 * Building DLLs with gnatdll::
31741 * GNAT and Windows Resources::
31742 * Debugging a DLL::
31743 * Setting Stack Size from gnatlink::
31744 * Setting Heap Size from gnatlink::
31745 @end menu
31746
31747 @node Using GNAT on Windows
31748 @section Using GNAT on Windows
31749
31750 @noindent
31751 One of the strengths of the GNAT technology is that its tool set
31752 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31753 @code{gdb} debugger, etc.) is used in the same way regardless of the
31754 platform.
31755
31756 On Windows this tool set is complemented by a number of Microsoft-specific
31757 tools that have been provided to facilitate interoperability with Windows
31758 when this is required. With these tools:
31759
31760 @itemize @bullet
31761
31762 @item
31763 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31764 subsystems.
31765
31766 @item
31767 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31768 relocatable and non-relocatable DLLs are supported).
31769
31770 @item
31771 You can build Ada DLLs for use in other applications. These applications
31772 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31773 relocatable and non-relocatable Ada DLLs are supported.
31774
31775 @item
31776 You can include Windows resources in your Ada application.
31777
31778 @item
31779 You can use or create COM/DCOM objects.
31780 @end itemize
31781
31782 @noindent
31783 Immediately below are listed all known general GNAT-for-Windows restrictions.
31784 Other restrictions about specific features like Windows Resources and DLLs
31785 are listed in separate sections below.
31786
31787 @itemize @bullet
31788
31789 @item
31790 It is not possible to use @code{GetLastError} and @code{SetLastError}
31791 when tasking, protected records, or exceptions are used. In these
31792 cases, in order to implement Ada semantics, the GNAT run-time system
31793 calls certain Win32 routines that set the last error variable to 0 upon
31794 success. It should be possible to use @code{GetLastError} and
31795 @code{SetLastError} when tasking, protected record, and exception
31796 features are not used, but it is not guaranteed to work.
31797
31798 @item
31799 It is not possible to link against Microsoft libraries except for
31800 import libraries. The library must be built to be compatible with
31801 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31802 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31803 not be compatible with the GNAT runtime. Even if the library is
31804 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31805
31806 @item
31807 When the compilation environment is located on FAT32 drives, users may
31808 experience recompilations of the source files that have not changed if
31809 Daylight Saving Time (DST) state has changed since the last time files
31810 were compiled. NTFS drives do not have this problem.
31811
31812 @item
31813 No components of the GNAT toolset use any entries in the Windows
31814 registry. The only entries that can be created are file associations and
31815 PATH settings, provided the user has chosen to create them at installation
31816 time, as well as some minimal book-keeping information needed to correctly
31817 uninstall or integrate different GNAT products.
31818 @end itemize
31819
31820 @node Using a network installation of GNAT
31821 @section Using a network installation of GNAT
31822
31823 @noindent
31824 Make sure the system on which GNAT is installed is accessible from the
31825 current machine, i.e., the install location is shared over the network.
31826 Shared resources are accessed on Windows by means of UNC paths, which
31827 have the format @code{\\server\sharename\path}
31828
31829 In order to use such a network installation, simply add the UNC path of the
31830 @file{bin} directory of your GNAT installation in front of your PATH. For
31831 example, if GNAT is installed in @file{\GNAT} directory of a share location
31832 called @file{c-drive} on a machine @file{LOKI}, the following command will
31833 make it available:
31834
31835 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31836
31837 Be aware that every compilation using the network installation results in the
31838 transfer of large amounts of data across the network and will likely cause
31839 serious performance penalty.
31840
31841 @node CONSOLE and WINDOWS subsystems
31842 @section CONSOLE and WINDOWS subsystems
31843 @cindex CONSOLE Subsystem
31844 @cindex WINDOWS Subsystem
31845 @cindex -mwindows
31846
31847 @noindent
31848 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31849 (which is the default subsystem) will always create a console when
31850 launching the application. This is not something desirable when the
31851 application has a Windows GUI. To get rid of this console the
31852 application must be using the @code{WINDOWS} subsystem. To do so
31853 the @option{-mwindows} linker option must be specified.
31854
31855 @smallexample
31856 $ gnatmake winprog -largs -mwindows
31857 @end smallexample
31858
31859 @node Temporary Files
31860 @section Temporary Files
31861 @cindex Temporary files
31862
31863 @noindent
31864 It is possible to control where temporary files gets created by setting
31865 the @env{TMP} environment variable. The file will be created:
31866
31867 @itemize
31868 @item Under the directory pointed to by the @env{TMP} environment variable if
31869 this directory exists.
31870
31871 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31872 set (or not pointing to a directory) and if this directory exists.
31873
31874 @item Under the current working directory otherwise.
31875 @end itemize
31876
31877 @noindent
31878 This allows you to determine exactly where the temporary
31879 file will be created. This is particularly useful in networked
31880 environments where you may not have write access to some
31881 directories.
31882
31883 @node Mixed-Language Programming on Windows
31884 @section Mixed-Language Programming on Windows
31885
31886 @noindent
31887 Developing pure Ada applications on Windows is no different than on
31888 other GNAT-supported platforms. However, when developing or porting an
31889 application that contains a mix of Ada and C/C++, the choice of your
31890 Windows C/C++ development environment conditions your overall
31891 interoperability strategy.
31892
31893 If you use @command{gcc} to compile the non-Ada part of your application,
31894 there are no Windows-specific restrictions that affect the overall
31895 interoperability with your Ada code. If you plan to use
31896 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31897 the following limitations:
31898
31899 @itemize @bullet
31900 @item
31901 You cannot link your Ada code with an object or library generated with
31902 Microsoft tools if these use the @code{.tls} section (Thread Local
31903 Storage section) since the GNAT linker does not yet support this section.
31904
31905 @item
31906 You cannot link your Ada code with an object or library generated with
31907 Microsoft tools if these use I/O routines other than those provided in
31908 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31909 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31910 libraries can cause a conflict with @code{msvcrt.dll} services. For
31911 instance Visual C++ I/O stream routines conflict with those in
31912 @code{msvcrt.dll}.
31913 @end itemize
31914
31915 @noindent
31916 If you do want to use the Microsoft tools for your non-Ada code and hit one
31917 of the above limitations, you have two choices:
31918
31919 @enumerate
31920 @item
31921 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31922 application. In this case, use the Microsoft or whatever environment to
31923 build the DLL and use GNAT to build your executable
31924 (@pxref{Using DLLs with GNAT}).
31925
31926 @item
31927 Or you can encapsulate your Ada code in a DLL to be linked with the
31928 other part of your application. In this case, use GNAT to build the DLL
31929 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31930 environment to build your executable.
31931 @end enumerate
31932
31933 @node Windows Calling Conventions
31934 @section Windows Calling Conventions
31935 @findex Stdcall
31936 @findex APIENTRY
31937
31938 @menu
31939 * C Calling Convention::
31940 * Stdcall Calling Convention::
31941 * Win32 Calling Convention::
31942 * DLL Calling Convention::
31943 @end menu
31944
31945 @noindent
31946 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31947 (callee), there are several ways to push @code{G}'s parameters on the
31948 stack and there are several possible scenarios to clean up the stack
31949 upon @code{G}'s return. A calling convention is an agreed upon software
31950 protocol whereby the responsibilities between the caller (@code{F}) and
31951 the callee (@code{G}) are clearly defined. Several calling conventions
31952 are available for Windows:
31953
31954 @itemize @bullet
31955 @item
31956 @code{C} (Microsoft defined)
31957
31958 @item
31959 @code{Stdcall} (Microsoft defined)
31960
31961 @item
31962 @code{Win32} (GNAT specific)
31963
31964 @item
31965 @code{DLL} (GNAT specific)
31966 @end itemize
31967
31968 @node C Calling Convention
31969 @subsection @code{C} Calling Convention
31970
31971 @noindent
31972 This is the default calling convention used when interfacing to C/C++
31973 routines compiled with either @command{gcc} or Microsoft Visual C++.
31974
31975 In the @code{C} calling convention subprogram parameters are pushed on the
31976 stack by the caller from right to left. The caller itself is in charge of
31977 cleaning up the stack after the call. In addition, the name of a routine
31978 with @code{C} calling convention is mangled by adding a leading underscore.
31979
31980 The name to use on the Ada side when importing (or exporting) a routine
31981 with @code{C} calling convention is the name of the routine. For
31982 instance the C function:
31983
31984 @smallexample
31985 int get_val (long);
31986 @end smallexample
31987
31988 @noindent
31989 should be imported from Ada as follows:
31990
31991 @smallexample @c ada
31992 @group
31993 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31994 pragma Import (C, Get_Val, External_Name => "get_val");
31995 @end group
31996 @end smallexample
31997
31998 @noindent
31999 Note that in this particular case the @code{External_Name} parameter could
32000 have been omitted since, when missing, this parameter is taken to be the
32001 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32002 is missing, as in the above example, this parameter is set to be the
32003 @code{External_Name} with a leading underscore.
32004
32005 When importing a variable defined in C, you should always use the @code{C}
32006 calling convention unless the object containing the variable is part of a
32007 DLL (in which case you should use the @code{Stdcall} calling
32008 convention, @pxref{Stdcall Calling Convention}).
32009
32010 @node Stdcall Calling Convention
32011 @subsection @code{Stdcall} Calling Convention
32012
32013 @noindent
32014 This convention, which was the calling convention used for Pascal
32015 programs, is used by Microsoft for all the routines in the Win32 API for
32016 efficiency reasons. It must be used to import any routine for which this
32017 convention was specified.
32018
32019 In the @code{Stdcall} calling convention subprogram parameters are pushed
32020 on the stack by the caller from right to left. The callee (and not the
32021 caller) is in charge of cleaning the stack on routine exit. In addition,
32022 the name of a routine with @code{Stdcall} calling convention is mangled by
32023 adding a leading underscore (as for the @code{C} calling convention) and a
32024 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32025 bytes) of the parameters passed to the routine.
32026
32027 The name to use on the Ada side when importing a C routine with a
32028 @code{Stdcall} calling convention is the name of the C routine. The leading
32029 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32030 the compiler. For instance the Win32 function:
32031
32032 @smallexample
32033 @b{APIENTRY} int get_val (long);
32034 @end smallexample
32035
32036 @noindent
32037 should be imported from Ada as follows:
32038
32039 @smallexample @c ada
32040 @group
32041 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32042 pragma Import (Stdcall, Get_Val);
32043 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32044 @end group
32045 @end smallexample
32046
32047 @noindent
32048 As for the @code{C} calling convention, when the @code{External_Name}
32049 parameter is missing, it is taken to be the name of the Ada entity in lower
32050 case. If instead of writing the above import pragma you write:
32051
32052 @smallexample @c ada
32053 @group
32054 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32055 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32056 @end group
32057 @end smallexample
32058
32059 @noindent
32060 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32061 of specifying the @code{External_Name} parameter you specify the
32062 @code{Link_Name} as in the following example:
32063
32064 @smallexample @c ada
32065 @group
32066 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32067 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32068 @end group
32069 @end smallexample
32070
32071 @noindent
32072 then the imported routine is @code{retrieve_val}, that is, there is no
32073 decoration at all. No leading underscore and no Stdcall suffix
32074 @code{@@}@code{@var{nn}}.
32075
32076 @noindent
32077 This is especially important as in some special cases a DLL's entry
32078 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32079 name generated for a call has it.
32080
32081 @noindent
32082 It is also possible to import variables defined in a DLL by using an
32083 import pragma for a variable. As an example, if a DLL contains a
32084 variable defined as:
32085
32086 @smallexample
32087 int my_var;
32088 @end smallexample
32089
32090 @noindent
32091 then, to access this variable from Ada you should write:
32092
32093 @smallexample @c ada
32094 @group
32095 My_Var : Interfaces.C.int;
32096 pragma Import (Stdcall, My_Var);
32097 @end group
32098 @end smallexample
32099
32100 @noindent
32101 Note that to ease building cross-platform bindings this convention
32102 will be handled as a @code{C} calling convention on non-Windows platforms.
32103
32104 @node Win32 Calling Convention
32105 @subsection @code{Win32} Calling Convention
32106
32107 @noindent
32108 This convention, which is GNAT-specific is fully equivalent to the
32109 @code{Stdcall} calling convention described above.
32110
32111 @node DLL Calling Convention
32112 @subsection @code{DLL} Calling Convention
32113
32114 @noindent
32115 This convention, which is GNAT-specific is fully equivalent to the
32116 @code{Stdcall} calling convention described above.
32117
32118 @node Introduction to Dynamic Link Libraries (DLLs)
32119 @section Introduction to Dynamic Link Libraries (DLLs)
32120 @findex DLL
32121
32122 @noindent
32123 A Dynamically Linked Library (DLL) is a library that can be shared by
32124 several applications running under Windows. A DLL can contain any number of
32125 routines and variables.
32126
32127 One advantage of DLLs is that you can change and enhance them without
32128 forcing all the applications that depend on them to be relinked or
32129 recompiled. However, you should be aware than all calls to DLL routines are
32130 slower since, as you will understand below, such calls are indirect.
32131
32132 To illustrate the remainder of this section, suppose that an application
32133 wants to use the services of a DLL @file{API.dll}. To use the services
32134 provided by @file{API.dll} you must statically link against the DLL or
32135 an import library which contains a jump table with an entry for each
32136 routine and variable exported by the DLL. In the Microsoft world this
32137 import library is called @file{API.lib}. When using GNAT this import
32138 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32139 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32140
32141 After you have linked your application with the DLL or the import library
32142 and you run your application, here is what happens:
32143
32144 @enumerate
32145 @item
32146 Your application is loaded into memory.
32147
32148 @item
32149 The DLL @file{API.dll} is mapped into the address space of your
32150 application. This means that:
32151
32152 @itemize @bullet
32153 @item
32154 The DLL will use the stack of the calling thread.
32155
32156 @item
32157 The DLL will use the virtual address space of the calling process.
32158
32159 @item
32160 The DLL will allocate memory from the virtual address space of the calling
32161 process.
32162
32163 @item
32164 Handles (pointers) can be safely exchanged between routines in the DLL
32165 routines and routines in the application using the DLL.
32166 @end itemize
32167
32168 @item
32169 The entries in the jump table (from the import library @file{libAPI.dll.a}
32170 or @file{API.lib} or automatically created when linking against a DLL)
32171 which is part of your application are initialized with the addresses
32172 of the routines and variables in @file{API.dll}.
32173
32174 @item
32175 If present in @file{API.dll}, routines @code{DllMain} or
32176 @code{DllMainCRTStartup} are invoked. These routines typically contain
32177 the initialization code needed for the well-being of the routines and
32178 variables exported by the DLL.
32179 @end enumerate
32180
32181 @noindent
32182 There is an additional point which is worth mentioning. In the Windows
32183 world there are two kind of DLLs: relocatable and non-relocatable
32184 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32185 in the target application address space. If the addresses of two
32186 non-relocatable DLLs overlap and these happen to be used by the same
32187 application, a conflict will occur and the application will run
32188 incorrectly. Hence, when possible, it is always preferable to use and
32189 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32190 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32191 User's Guide) removes the debugging symbols from the DLL but the DLL can
32192 still be relocated.
32193
32194 As a side note, an interesting difference between Microsoft DLLs and
32195 Unix shared libraries, is the fact that on most Unix systems all public
32196 routines are exported by default in a Unix shared library, while under
32197 Windows it is possible (but not required) to list exported routines in
32198 a definition file (@pxref{The Definition File}).
32199
32200 @node Using DLLs with GNAT
32201 @section Using DLLs with GNAT
32202
32203 @menu
32204 * Creating an Ada Spec for the DLL Services::
32205 * Creating an Import Library::
32206 @end menu
32207
32208 @noindent
32209 To use the services of a DLL, say @file{API.dll}, in your Ada application
32210 you must have:
32211
32212 @enumerate
32213 @item
32214 The Ada spec for the routines and/or variables you want to access in
32215 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32216 header files provided with the DLL.
32217
32218 @item
32219 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32220 mentioned an import library is a statically linked library containing the
32221 import table which will be filled at load time to point to the actual
32222 @file{API.dll} routines. Sometimes you don't have an import library for the
32223 DLL you want to use. The following sections will explain how to build
32224 one. Note that this is optional.
32225
32226 @item
32227 The actual DLL, @file{API.dll}.
32228 @end enumerate
32229
32230 @noindent
32231 Once you have all the above, to compile an Ada application that uses the
32232 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32233 you simply issue the command
32234
32235 @smallexample
32236 $ gnatmake my_ada_app -largs -lAPI
32237 @end smallexample
32238
32239 @noindent
32240 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32241 tells the GNAT linker to look first for a library named @file{API.lib}
32242 (Microsoft-style name) and if not found for a libraries named
32243 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32244 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32245 contains the following pragma
32246
32247 @smallexample @c ada
32248 pragma Linker_Options ("-lAPI");
32249 @end smallexample
32250
32251 @noindent
32252 you do not have to add @option{-largs -lAPI} at the end of the
32253 @command{gnatmake} command.
32254
32255 If any one of the items above is missing you will have to create it
32256 yourself. The following sections explain how to do so using as an
32257 example a fictitious DLL called @file{API.dll}.
32258
32259 @node Creating an Ada Spec for the DLL Services
32260 @subsection Creating an Ada Spec for the DLL Services
32261
32262 @noindent
32263 A DLL typically comes with a C/C++ header file which provides the
32264 definitions of the routines and variables exported by the DLL. The Ada
32265 equivalent of this header file is a package spec that contains definitions
32266 for the imported entities. If the DLL you intend to use does not come with
32267 an Ada spec you have to generate one such spec yourself. For example if
32268 the header file of @file{API.dll} is a file @file{api.h} containing the
32269 following two definitions:
32270
32271 @smallexample
32272 @group
32273 @cartouche
32274 int some_var;
32275 int get (char *);
32276 @end cartouche
32277 @end group
32278 @end smallexample
32279
32280 @noindent
32281 then the equivalent Ada spec could be:
32282
32283 @smallexample @c ada
32284 @group
32285 @cartouche
32286 with Interfaces.C.Strings;
32287 package API is
32288    use Interfaces;
32289
32290    Some_Var : C.int;
32291    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32292
32293 private
32294    pragma Import (C, Get);
32295    pragma Import (DLL, Some_Var);
32296 end API;
32297 @end cartouche
32298 @end group
32299 @end smallexample
32300
32301 @noindent
32302 Note that a variable is
32303 @strong{always imported with a Stdcall convention}. A function
32304 can have @code{C} or @code{Stdcall} convention.
32305 (@pxref{Windows Calling Conventions}).
32306
32307 @node Creating an Import Library
32308 @subsection Creating an Import Library
32309 @cindex Import library
32310
32311 @menu
32312 * The Definition File::
32313 * GNAT-Style Import Library::
32314 * Microsoft-Style Import Library::
32315 @end menu
32316
32317 @noindent
32318 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32319 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32320 with @file{API.dll} you can skip this section. You can also skip this
32321 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32322 as in this case it is possible to link directly against the
32323 DLL. Otherwise read on.
32324
32325 @node The Definition File
32326 @subsubsection The Definition File
32327 @cindex Definition file
32328 @findex .def
32329
32330 @noindent
32331 As previously mentioned, and unlike Unix systems, the list of symbols
32332 that are exported from a DLL must be provided explicitly in Windows.
32333 The main goal of a definition file is precisely that: list the symbols
32334 exported by a DLL. A definition file (usually a file with a @code{.def}
32335 suffix) has the following structure:
32336
32337 @smallexample
32338 @group
32339 @cartouche
32340 @r{[}LIBRARY @var{name}@r{]}
32341 @r{[}DESCRIPTION @var{string}@r{]}
32342 EXPORTS
32343    @var{symbol1}
32344    @var{symbol2}
32345    @dots{}
32346 @end cartouche
32347 @end group
32348 @end smallexample
32349
32350 @table @code
32351 @item LIBRARY @var{name}
32352 This section, which is optional, gives the name of the DLL.
32353
32354 @item DESCRIPTION @var{string}
32355 This section, which is optional, gives a description string that will be
32356 embedded in the import library.
32357
32358 @item EXPORTS
32359 This section gives the list of exported symbols (procedures, functions or
32360 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32361 section of @file{API.def} looks like:
32362
32363 @smallexample
32364 @group
32365 @cartouche
32366 EXPORTS
32367    some_var
32368    get
32369 @end cartouche
32370 @end group
32371 @end smallexample
32372 @end table
32373
32374 @noindent
32375 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32376 (@pxref{Windows Calling Conventions}) for a Stdcall
32377 calling convention function in the exported symbols list.
32378
32379 @noindent
32380 There can actually be other sections in a definition file, but these
32381 sections are not relevant to the discussion at hand.
32382
32383 @node GNAT-Style Import Library
32384 @subsubsection GNAT-Style Import Library
32385
32386 @noindent
32387 To create a static import library from @file{API.dll} with the GNAT tools
32388 you should proceed as follows:
32389
32390 @enumerate
32391 @item
32392 Create the definition file @file{API.def} (@pxref{The Definition File}).
32393 For that use the @code{dll2def} tool as follows:
32394
32395 @smallexample
32396 $ dll2def API.dll > API.def
32397 @end smallexample
32398
32399 @noindent
32400 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32401 to standard output the list of entry points in the DLL. Note that if
32402 some routines in the DLL have the @code{Stdcall} convention
32403 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32404 suffix then you'll have to edit @file{api.def} to add it, and specify
32405 @option{-k} to @command{gnatdll} when creating the import library.
32406
32407 @noindent
32408 Here are some hints to find the right @code{@@}@var{nn} suffix.
32409
32410 @enumerate
32411 @item
32412 If you have the Microsoft import library (.lib), it is possible to get
32413 the right symbols by using Microsoft @code{dumpbin} tool (see the
32414 corresponding Microsoft documentation for further details).
32415
32416 @smallexample
32417 $ dumpbin /exports api.lib
32418 @end smallexample
32419
32420 @item
32421 If you have a message about a missing symbol at link time the compiler
32422 tells you what symbol is expected. You just have to go back to the
32423 definition file and add the right suffix.
32424 @end enumerate
32425
32426 @item
32427 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32428 (@pxref{Using gnatdll}) as follows:
32429
32430 @smallexample
32431 $ gnatdll -e API.def -d API.dll
32432 @end smallexample
32433
32434 @noindent
32435 @code{gnatdll} takes as input a definition file @file{API.def} and the
32436 name of the DLL containing the services listed in the definition file
32437 @file{API.dll}. The name of the static import library generated is
32438 computed from the name of the definition file as follows: if the
32439 definition file name is @var{xyz}@code{.def}, the import library name will
32440 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32441 @option{-e} could have been removed because the name of the definition
32442 file (before the ``@code{.def}'' suffix) is the same as the name of the
32443 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32444 @end enumerate
32445
32446 @node Microsoft-Style Import Library
32447 @subsubsection Microsoft-Style Import Library
32448
32449 @noindent
32450 With GNAT you can either use a GNAT-style or Microsoft-style import
32451 library. A Microsoft import library is needed only if you plan to make an
32452 Ada DLL available to applications developed with Microsoft
32453 tools (@pxref{Mixed-Language Programming on Windows}).
32454
32455 To create a Microsoft-style import library for @file{API.dll} you
32456 should proceed as follows:
32457
32458 @enumerate
32459 @item
32460 Create the definition file @file{API.def} from the DLL. For this use either
32461 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32462 tool (see the corresponding Microsoft documentation for further details).
32463
32464 @item
32465 Build the actual import library using Microsoft's @code{lib} utility:
32466
32467 @smallexample
32468 $ lib -machine:IX86 -def:API.def -out:API.lib
32469 @end smallexample
32470
32471 @noindent
32472 If you use the above command the definition file @file{API.def} must
32473 contain a line giving the name of the DLL:
32474
32475 @smallexample
32476 LIBRARY      "API"
32477 @end smallexample
32478
32479 @noindent
32480 See the Microsoft documentation for further details about the usage of
32481 @code{lib}.
32482 @end enumerate
32483
32484 @node Building DLLs with GNAT
32485 @section Building DLLs with GNAT
32486 @cindex DLLs, building
32487
32488 @noindent
32489 This section explain how to build DLLs using the GNAT built-in DLL
32490 support. With the following procedure it is straight forward to build
32491 and use DLLs with GNAT.
32492
32493 @enumerate
32494
32495 @item building object files
32496
32497 The first step is to build all objects files that are to be included
32498 into the DLL. This is done by using the standard @command{gnatmake} tool.
32499
32500 @item building the DLL
32501
32502 To build the DLL you must use @command{gcc}'s @option{-shared}
32503 option. It is quite simple to use this method:
32504
32505 @smallexample
32506 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32507 @end smallexample
32508
32509 It is important to note that in this case all symbols found in the
32510 object files are automatically exported. It is possible to restrict
32511 the set of symbols to export by passing to @command{gcc} a definition
32512 file, @pxref{The Definition File}. For example:
32513
32514 @smallexample
32515 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32516 @end smallexample
32517
32518 If you use a definition file you must export the elaboration procedures
32519 for every package that required one. Elaboration procedures are named
32520 using the package name followed by "_E".
32521
32522 @item preparing DLL to be used
32523
32524 For the DLL to be used by client programs the bodies must be hidden
32525 from it and the .ali set with read-only attribute. This is very important
32526 otherwise GNAT will recompile all packages and will not actually use
32527 the code in the DLL. For example:
32528
32529 @smallexample
32530 $ mkdir apilib
32531 $ copy *.ads *.ali api.dll apilib
32532 $ attrib +R apilib\*.ali
32533 @end smallexample
32534
32535 @end enumerate
32536
32537 At this point it is possible to use the DLL by directly linking
32538 against it. Note that you must use the GNAT shared runtime when using
32539 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32540 option.
32541
32542 @smallexample
32543 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32544 @end smallexample
32545
32546 @node Building DLLs with GNAT Project files
32547 @section Building DLLs with GNAT Project files
32548 @cindex DLLs, building
32549
32550 @noindent
32551 There is nothing specific to Windows in the build process.
32552 @pxref{Library Projects}.
32553
32554 @noindent
32555 Due to a system limitation, it is not possible under Windows to create threads
32556 when inside the @code{DllMain} routine which is used for auto-initialization
32557 of shared libraries, so it is not possible to have library level tasks in SALs.
32558
32559 @node Building DLLs with gnatdll
32560 @section Building DLLs with gnatdll
32561 @cindex DLLs, building
32562
32563 @menu
32564 * Limitations When Using Ada DLLs from Ada::
32565 * Exporting Ada Entities::
32566 * Ada DLLs and Elaboration::
32567 * Ada DLLs and Finalization::
32568 * Creating a Spec for Ada DLLs::
32569 * Creating the Definition File::
32570 * Using gnatdll::
32571 @end menu
32572
32573 @noindent
32574 Note that it is preferred to use the built-in GNAT DLL support
32575 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32576 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32577
32578 This section explains how to build DLLs containing Ada code using
32579 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32580 remainder of this section.
32581
32582 The steps required to build an Ada DLL that is to be used by Ada as well as
32583 non-Ada applications are as follows:
32584
32585 @enumerate
32586 @item
32587 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32588 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32589 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32590 skip this step if you plan to use the Ada DLL only from Ada applications.
32591
32592 @item
32593 Your Ada code must export an initialization routine which calls the routine
32594 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32595 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32596 routine exported by the Ada DLL must be invoked by the clients of the DLL
32597 to initialize the DLL.
32598
32599 @item
32600 When useful, the DLL should also export a finalization routine which calls
32601 routine @code{adafinal} generated by @command{gnatbind} to perform the
32602 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32603 The finalization routine exported by the Ada DLL must be invoked by the
32604 clients of the DLL when the DLL services are no further needed.
32605
32606 @item
32607 You must provide a spec for the services exported by the Ada DLL in each
32608 of the programming languages to which you plan to make the DLL available.
32609
32610 @item
32611 You must provide a definition file listing the exported entities
32612 (@pxref{The Definition File}).
32613
32614 @item
32615 Finally you must use @code{gnatdll} to produce the DLL and the import
32616 library (@pxref{Using gnatdll}).
32617 @end enumerate
32618
32619 @noindent
32620 Note that a relocatable DLL stripped using the @code{strip}
32621 binutils tool will not be relocatable anymore. To build a DLL without
32622 debug information pass @code{-largs -s} to @code{gnatdll}. This
32623 restriction does not apply to a DLL built using a Library Project.
32624 @pxref{Library Projects}.
32625
32626 @node Limitations When Using Ada DLLs from Ada
32627 @subsection Limitations When Using Ada DLLs from Ada
32628
32629 @noindent
32630 When using Ada DLLs from Ada applications there is a limitation users
32631 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32632 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32633 each Ada DLL includes the services of the GNAT run time that are necessary
32634 to the Ada code inside the DLL. As a result, when an Ada program uses an
32635 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32636 one in the main program.
32637
32638 It is therefore not possible to exchange GNAT run-time objects between the
32639 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32640 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32641 types, etc.
32642
32643 It is completely safe to exchange plain elementary, array or record types,
32644 Windows object handles, etc.
32645
32646 @node Exporting Ada Entities
32647 @subsection Exporting Ada Entities
32648 @cindex Export table
32649
32650 @noindent
32651 Building a DLL is a way to encapsulate a set of services usable from any
32652 application. As a result, the Ada entities exported by a DLL should be
32653 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32654 any Ada name mangling. As an example here is an Ada package
32655 @code{API}, spec and body, exporting two procedures, a function, and a
32656 variable:
32657
32658 @smallexample @c ada
32659 @group
32660 @cartouche
32661 with Interfaces.C; use Interfaces;
32662 package API is
32663    Count : C.int := 0;
32664    function Factorial (Val : C.int) return C.int;
32665
32666    procedure Initialize_API;
32667    procedure Finalize_API;
32668    --  Initialization & Finalization routines. More in the next section.
32669 private
32670    pragma Export (C, Initialize_API);
32671    pragma Export (C, Finalize_API);
32672    pragma Export (C, Count);
32673    pragma Export (C, Factorial);
32674 end API;
32675 @end cartouche
32676 @end group
32677 @end smallexample
32678
32679 @smallexample @c ada
32680 @group
32681 @cartouche
32682 package body API is
32683    function Factorial (Val : C.int) return C.int is
32684       Fact : C.int := 1;
32685    begin
32686       Count := Count + 1;
32687       for K in 1 .. Val loop
32688          Fact := Fact * K;
32689       end loop;
32690       return Fact;
32691    end Factorial;
32692
32693    procedure Initialize_API is
32694       procedure Adainit;
32695       pragma Import (C, Adainit);
32696    begin
32697       Adainit;
32698    end Initialize_API;
32699
32700    procedure Finalize_API is
32701       procedure Adafinal;
32702       pragma Import (C, Adafinal);
32703    begin
32704       Adafinal;
32705    end Finalize_API;
32706 end API;
32707 @end cartouche
32708 @end group
32709 @end smallexample
32710
32711 @noindent
32712 If the Ada DLL you are building will only be used by Ada applications
32713 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32714 convention. As an example, the previous package could be written as
32715 follows:
32716
32717 @smallexample @c ada
32718 @group
32719 @cartouche
32720 package API is
32721    Count : Integer := 0;
32722    function Factorial (Val : Integer) return Integer;
32723
32724    procedure Initialize_API;
32725    procedure Finalize_API;
32726    --  Initialization and Finalization routines.
32727 end API;
32728 @end cartouche
32729 @end group
32730 @end smallexample
32731
32732 @smallexample @c ada
32733 @group
32734 @cartouche
32735 package body API is
32736    function Factorial (Val : Integer) return Integer is
32737       Fact : Integer := 1;
32738    begin
32739       Count := Count + 1;
32740       for K in 1 .. Val loop
32741          Fact := Fact * K;
32742       end loop;
32743       return Fact;
32744    end Factorial;
32745
32746    @dots{}
32747    --  The remainder of this package body is unchanged.
32748 end API;
32749 @end cartouche
32750 @end group
32751 @end smallexample
32752
32753 @noindent
32754 Note that if you do not export the Ada entities with a @code{C} or
32755 @code{Stdcall} convention you will have to provide the mangled Ada names
32756 in the definition file of the Ada DLL
32757 (@pxref{Creating the Definition File}).
32758
32759 @node Ada DLLs and Elaboration
32760 @subsection Ada DLLs and Elaboration
32761 @cindex DLLs and elaboration
32762
32763 @noindent
32764 The DLL that you are building contains your Ada code as well as all the
32765 routines in the Ada library that are needed by it. The first thing a
32766 user of your DLL must do is elaborate the Ada code
32767 (@pxref{Elaboration Order Handling in GNAT}).
32768
32769 To achieve this you must export an initialization routine
32770 (@code{Initialize_API} in the previous example), which must be invoked
32771 before using any of the DLL services. This elaboration routine must call
32772 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32773 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32774 @code{Initialize_Api} for an example. Note that the GNAT binder is
32775 automatically invoked during the DLL build process by the @code{gnatdll}
32776 tool (@pxref{Using gnatdll}).
32777
32778 When a DLL is loaded, Windows systematically invokes a routine called
32779 @code{DllMain}. It would therefore be possible to call @code{adainit}
32780 directly from @code{DllMain} without having to provide an explicit
32781 initialization routine. Unfortunately, it is not possible to call
32782 @code{adainit} from the @code{DllMain} if your program has library level
32783 tasks because access to the @code{DllMain} entry point is serialized by
32784 the system (that is, only a single thread can execute ``through'' it at a
32785 time), which means that the GNAT run time will deadlock waiting for the
32786 newly created task to complete its initialization.
32787
32788 @node Ada DLLs and Finalization
32789 @subsection Ada DLLs and Finalization
32790 @cindex DLLs and finalization
32791
32792 @noindent
32793 When the services of an Ada DLL are no longer needed, the client code should
32794 invoke the DLL finalization routine, if available. The DLL finalization
32795 routine is in charge of releasing all resources acquired by the DLL. In the
32796 case of the Ada code contained in the DLL, this is achieved by calling
32797 routine @code{adafinal} generated by the GNAT binder
32798 (@pxref{Binding with Non-Ada Main Programs}).
32799 See the body of @code{Finalize_Api} for an
32800 example. As already pointed out the GNAT binder is automatically invoked
32801 during the DLL build process by the @code{gnatdll} tool
32802 (@pxref{Using gnatdll}).
32803
32804 @node Creating a Spec for Ada DLLs
32805 @subsection Creating a Spec for Ada DLLs
32806
32807 @noindent
32808 To use the services exported by the Ada DLL from another programming
32809 language (e.g.@: C), you have to translate the specs of the exported Ada
32810 entities in that language. For instance in the case of @code{API.dll},
32811 the corresponding C header file could look like:
32812
32813 @smallexample
32814 @group
32815 @cartouche
32816 extern int *_imp__count;
32817 #define count (*_imp__count)
32818 int factorial (int);
32819 @end cartouche
32820 @end group
32821 @end smallexample
32822
32823 @noindent
32824 It is important to understand that when building an Ada DLL to be used by
32825 other Ada applications, you need two different specs for the packages
32826 contained in the DLL: one for building the DLL and the other for using
32827 the DLL. This is because the @code{DLL} calling convention is needed to
32828 use a variable defined in a DLL, but when building the DLL, the variable
32829 must have either the @code{Ada} or @code{C} calling convention. As an
32830 example consider a DLL comprising the following package @code{API}:
32831
32832 @smallexample @c ada
32833 @group
32834 @cartouche
32835 package API is
32836    Count : Integer := 0;
32837    @dots{}
32838    --  Remainder of the package omitted.
32839 end API;
32840 @end cartouche
32841 @end group
32842 @end smallexample
32843
32844 @noindent
32845 After producing a DLL containing package @code{API}, the spec that
32846 must be used to import @code{API.Count} from Ada code outside of the
32847 DLL is:
32848
32849 @smallexample @c ada
32850 @group
32851 @cartouche
32852 package API is
32853    Count : Integer;
32854    pragma Import (DLL, Count);
32855 end API;
32856 @end cartouche
32857 @end group
32858 @end smallexample
32859
32860 @node Creating the Definition File
32861 @subsection Creating the Definition File
32862
32863 @noindent
32864 The definition file is the last file needed to build the DLL. It lists
32865 the exported symbols. As an example, the definition file for a DLL
32866 containing only package @code{API} (where all the entities are exported
32867 with a @code{C} calling convention) is:
32868
32869 @smallexample
32870 @group
32871 @cartouche
32872 EXPORTS
32873     count
32874     factorial
32875     finalize_api
32876     initialize_api
32877 @end cartouche
32878 @end group
32879 @end smallexample
32880
32881 @noindent
32882 If the @code{C} calling convention is missing from package @code{API},
32883 then the definition file contains the mangled Ada names of the above
32884 entities, which in this case are:
32885
32886 @smallexample
32887 @group
32888 @cartouche
32889 EXPORTS
32890     api__count
32891     api__factorial
32892     api__finalize_api
32893     api__initialize_api
32894 @end cartouche
32895 @end group
32896 @end smallexample
32897
32898 @node Using gnatdll
32899 @subsection Using @code{gnatdll}
32900 @findex gnatdll
32901
32902 @menu
32903 * gnatdll Example::
32904 * gnatdll behind the Scenes::
32905 * Using dlltool::
32906 @end menu
32907
32908 @noindent
32909 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32910 and non-Ada sources that make up your DLL have been compiled.
32911 @code{gnatdll} is actually in charge of two distinct tasks: build the
32912 static import library for the DLL and the actual DLL. The form of the
32913 @code{gnatdll} command is
32914
32915 @smallexample
32916 @cartouche
32917 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32918 @end cartouche
32919 @end smallexample
32920
32921 @noindent
32922 where @var{list-of-files} is a list of ALI and object files. The object
32923 file list must be the exact list of objects corresponding to the non-Ada
32924 sources whose services are to be included in the DLL. The ALI file list
32925 must be the exact list of ALI files for the corresponding Ada sources
32926 whose services are to be included in the DLL. If @var{list-of-files} is
32927 missing, only the static import library is generated.
32928
32929 @noindent
32930 You may specify any of the following switches to @code{gnatdll}:
32931
32932 @table @code
32933 @item -a@ovar{address}
32934 @cindex @option{-a} (@code{gnatdll})
32935 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32936 specified the default address @var{0x11000000} will be used. By default,
32937 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32938 advise the reader to build relocatable DLL.
32939
32940 @item -b @var{address}
32941 @cindex @option{-b} (@code{gnatdll})
32942 Set the relocatable DLL base address. By default the address is
32943 @code{0x11000000}.
32944
32945 @item -bargs @var{opts}
32946 @cindex @option{-bargs} (@code{gnatdll})
32947 Binder options. Pass @var{opts} to the binder.
32948
32949 @item -d @var{dllfile}
32950 @cindex @option{-d} (@code{gnatdll})
32951 @var{dllfile} is the name of the DLL. This switch must be present for
32952 @code{gnatdll} to do anything. The name of the generated import library is
32953 obtained algorithmically from @var{dllfile} as shown in the following
32954 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32955 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32956 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32957 as shown in the following example:
32958 if @var{dllfile} is @code{xyz.dll}, the definition
32959 file used is @code{xyz.def}.
32960
32961 @item -e @var{deffile}
32962 @cindex @option{-e} (@code{gnatdll})
32963 @var{deffile} is the name of the definition file.
32964
32965 @item -g
32966 @cindex @option{-g} (@code{gnatdll})
32967 Generate debugging information. This information is stored in the object
32968 file and copied from there to the final DLL file by the linker,
32969 where it can be read by the debugger. You must use the
32970 @option{-g} switch if you plan on using the debugger or the symbolic
32971 stack traceback.
32972
32973 @item -h
32974 @cindex @option{-h} (@code{gnatdll})
32975 Help mode. Displays @code{gnatdll} switch usage information.
32976
32977 @item -Idir
32978 @cindex @option{-I} (@code{gnatdll})
32979 Direct @code{gnatdll} to search the @var{dir} directory for source and
32980 object files needed to build the DLL.
32981 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32982
32983 @item -k
32984 @cindex @option{-k} (@code{gnatdll})
32985 Removes the @code{@@}@var{nn} suffix from the import library's exported
32986 names, but keeps them for the link names. You must specify this
32987 option if you want to use a @code{Stdcall} function in a DLL for which
32988 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32989 of the Windows NT DLL for example. This option has no effect when
32990 @option{-n} option is specified.
32991
32992 @item -l @var{file}
32993 @cindex @option{-l} (@code{gnatdll})
32994 The list of ALI and object files used to build the DLL are listed in
32995 @var{file}, instead of being given in the command line. Each line in
32996 @var{file} contains the name of an ALI or object file.
32997
32998 @item -n
32999 @cindex @option{-n} (@code{gnatdll})
33000 No Import. Do not create the import library.
33001
33002 @item -q
33003 @cindex @option{-q} (@code{gnatdll})
33004 Quiet mode. Do not display unnecessary messages.
33005
33006 @item -v
33007 @cindex @option{-v} (@code{gnatdll})
33008 Verbose mode. Display extra information.
33009
33010 @item -largs @var{opts}
33011 @cindex @option{-largs} (@code{gnatdll})
33012 Linker options. Pass @var{opts} to the linker.
33013 @end table
33014
33015 @node gnatdll Example
33016 @subsubsection @code{gnatdll} Example
33017
33018 @noindent
33019 As an example the command to build a relocatable DLL from @file{api.adb}
33020 once @file{api.adb} has been compiled and @file{api.def} created is
33021
33022 @smallexample
33023 $ gnatdll -d api.dll api.ali
33024 @end smallexample
33025
33026 @noindent
33027 The above command creates two files: @file{libapi.dll.a} (the import
33028 library) and @file{api.dll} (the actual DLL). If you want to create
33029 only the DLL, just type:
33030
33031 @smallexample
33032 $ gnatdll -d api.dll -n api.ali
33033 @end smallexample
33034
33035 @noindent
33036 Alternatively if you want to create just the import library, type:
33037
33038 @smallexample
33039 $ gnatdll -d api.dll
33040 @end smallexample
33041
33042 @node gnatdll behind the Scenes
33043 @subsubsection @code{gnatdll} behind the Scenes
33044
33045 @noindent
33046 This section details the steps involved in creating a DLL. @code{gnatdll}
33047 does these steps for you. Unless you are interested in understanding what
33048 goes on behind the scenes, you should skip this section.
33049
33050 We use the previous example of a DLL containing the Ada package @code{API},
33051 to illustrate the steps necessary to build a DLL. The starting point is a
33052 set of objects that will make up the DLL and the corresponding ALI
33053 files. In the case of this example this means that @file{api.o} and
33054 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33055 the following:
33056
33057 @enumerate
33058 @item
33059 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33060 the information necessary to generate relocation information for the
33061 DLL.
33062
33063 @smallexample
33064 @group
33065 $ gnatbind -n api
33066 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33067 @end group
33068 @end smallexample
33069
33070 @noindent
33071 In addition to the base file, the @command{gnatlink} command generates an
33072 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33073 asks @command{gnatlink} to generate the routines @code{DllMain} and
33074 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33075 is loaded into memory.
33076
33077 @item
33078 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33079 export table (@file{api.exp}). The export table contains the relocation
33080 information in a form which can be used during the final link to ensure
33081 that the Windows loader is able to place the DLL anywhere in memory.
33082
33083 @smallexample
33084 @group
33085 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33086           --output-exp api.exp
33087 @end group
33088 @end smallexample
33089
33090 @item
33091 @code{gnatdll} builds the base file using the new export table. Note that
33092 @command{gnatbind} must be called once again since the binder generated file
33093 has been deleted during the previous call to @command{gnatlink}.
33094
33095 @smallexample
33096 @group
33097 $ gnatbind -n api
33098 $ gnatlink api -o api.jnk api.exp -mdll
33099       -Wl,--base-file,api.base
33100 @end group
33101 @end smallexample
33102
33103 @item
33104 @code{gnatdll} builds the new export table using the new base file and
33105 generates the DLL import library @file{libAPI.dll.a}.
33106
33107 @smallexample
33108 @group
33109 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33110           --output-exp api.exp --output-lib libAPI.a
33111 @end group
33112 @end smallexample
33113
33114 @item
33115 Finally @code{gnatdll} builds the relocatable DLL using the final export
33116 table.
33117
33118 @smallexample
33119 @group
33120 $ gnatbind -n api
33121 $ gnatlink api api.exp -o api.dll -mdll
33122 @end group
33123 @end smallexample
33124 @end enumerate
33125
33126 @node Using dlltool
33127 @subsubsection Using @code{dlltool}
33128
33129 @noindent
33130 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33131 DLLs and static import libraries. This section summarizes the most
33132 common @code{dlltool} switches. The form of the @code{dlltool} command
33133 is
33134
33135 @smallexample
33136 $ dlltool @ovar{switches}
33137 @end smallexample
33138
33139 @noindent
33140 @code{dlltool} switches include:
33141
33142 @table @option
33143 @item --base-file @var{basefile}
33144 @cindex @option{--base-file} (@command{dlltool})
33145 Read the base file @var{basefile} generated by the linker. This switch
33146 is used to create a relocatable DLL.
33147
33148 @item --def @var{deffile}
33149 @cindex @option{--def} (@command{dlltool})
33150 Read the definition file.
33151
33152 @item --dllname @var{name}
33153 @cindex @option{--dllname} (@command{dlltool})
33154 Gives the name of the DLL. This switch is used to embed the name of the
33155 DLL in the static import library generated by @code{dlltool} with switch
33156 @option{--output-lib}.
33157
33158 @item -k
33159 @cindex @option{-k} (@command{dlltool})
33160 Kill @code{@@}@var{nn} from exported names
33161 (@pxref{Windows Calling Conventions}
33162 for a discussion about @code{Stdcall}-style symbols.
33163
33164 @item --help
33165 @cindex @option{--help} (@command{dlltool})
33166 Prints the @code{dlltool} switches with a concise description.
33167
33168 @item --output-exp @var{exportfile}
33169 @cindex @option{--output-exp} (@command{dlltool})
33170 Generate an export file @var{exportfile}. The export file contains the
33171 export table (list of symbols in the DLL) and is used to create the DLL.
33172
33173 @item --output-lib @var{libfile}
33174 @cindex @option{--output-lib} (@command{dlltool})
33175 Generate a static import library @var{libfile}.
33176
33177 @item -v
33178 @cindex @option{-v} (@command{dlltool})
33179 Verbose mode.
33180
33181 @item --as @var{assembler-name}
33182 @cindex @option{--as} (@command{dlltool})
33183 Use @var{assembler-name} as the assembler. The default is @code{as}.
33184 @end table
33185
33186 @node GNAT and Windows Resources
33187 @section GNAT and Windows Resources
33188 @cindex Resources, windows
33189
33190 @menu
33191 * Building Resources::
33192 * Compiling Resources::
33193 * Using Resources::
33194 @end menu
33195
33196 @noindent
33197 Resources are an easy way to add Windows specific objects to your
33198 application. The objects that can be added as resources include:
33199
33200 @itemize @bullet
33201 @item
33202 menus
33203
33204 @item
33205 accelerators
33206
33207 @item
33208 dialog boxes
33209
33210 @item
33211 string tables
33212
33213 @item
33214 bitmaps
33215
33216 @item
33217 cursors
33218
33219 @item
33220 icons
33221
33222 @item
33223 fonts
33224 @end itemize
33225
33226 @noindent
33227 This section explains how to build, compile and use resources.
33228
33229 @node Building Resources
33230 @subsection Building Resources
33231 @cindex Resources, building
33232
33233 @noindent
33234 A resource file is an ASCII file. By convention resource files have an
33235 @file{.rc} extension.
33236 The easiest way to build a resource file is to use Microsoft tools
33237 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33238 @code{dlgedit.exe} to build dialogs.
33239 It is always possible to build an @file{.rc} file yourself by writing a
33240 resource script.
33241
33242 It is not our objective to explain how to write a resource file. A
33243 complete description of the resource script language can be found in the
33244 Microsoft documentation.
33245
33246 @node Compiling Resources
33247 @subsection Compiling Resources
33248 @findex rc
33249 @findex windres
33250 @cindex Resources, compiling
33251
33252 @noindent
33253 This section describes how to build a GNAT-compatible (COFF) object file
33254 containing the resources. This is done using the Resource Compiler
33255 @code{windres} as follows:
33256
33257 @smallexample
33258 $ windres -i myres.rc -o myres.o
33259 @end smallexample
33260
33261 @noindent
33262 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33263 file. You can specify an alternate preprocessor (usually named
33264 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33265 parameter. A list of all possible options may be obtained by entering
33266 the command @code{windres} @option{--help}.
33267
33268 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33269 to produce a @file{.res} file (binary resource file). See the
33270 corresponding Microsoft documentation for further details. In this case
33271 you need to use @code{windres} to translate the @file{.res} file to a
33272 GNAT-compatible object file as follows:
33273
33274 @smallexample
33275 $ windres -i myres.res -o myres.o
33276 @end smallexample
33277
33278 @node Using Resources
33279 @subsection Using Resources
33280 @cindex Resources, using
33281
33282 @noindent
33283 To include the resource file in your program just add the
33284 GNAT-compatible object file for the resource(s) to the linker
33285 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33286 option:
33287
33288 @smallexample
33289 $ gnatmake myprog -largs myres.o
33290 @end smallexample
33291
33292 @node Debugging a DLL
33293 @section Debugging a DLL
33294 @cindex DLL debugging
33295
33296 @menu
33297 * Program and DLL Both Built with GCC/GNAT::
33298 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33299 @end menu
33300
33301 @noindent
33302 Debugging a DLL is similar to debugging a standard program. But
33303 we have to deal with two different executable parts: the DLL and the
33304 program that uses it. We have the following four possibilities:
33305
33306 @enumerate 1
33307 @item
33308 The program and the DLL are built with @code{GCC/GNAT}.
33309 @item
33310 The program is built with foreign tools and the DLL is built with
33311 @code{GCC/GNAT}.
33312 @item
33313 The program is built with @code{GCC/GNAT} and the DLL is built with
33314 foreign tools.
33315 @item
33316 @end enumerate
33317
33318 @noindent
33319 In this section we address only cases one and two above.
33320 There is no point in trying to debug
33321 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33322 information in it. To do so you must use a debugger compatible with the
33323 tools suite used to build the DLL.
33324
33325 @node Program and DLL Both Built with GCC/GNAT
33326 @subsection Program and DLL Both Built with GCC/GNAT
33327
33328 @noindent
33329 This is the simplest case. Both the DLL and the program have @code{GDB}
33330 compatible debugging information. It is then possible to break anywhere in
33331 the process. Let's suppose here that the main procedure is named
33332 @code{ada_main} and that in the DLL there is an entry point named
33333 @code{ada_dll}.
33334
33335 @noindent
33336 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33337 program must have been built with the debugging information (see GNAT -g
33338 switch). Here are the step-by-step instructions for debugging it:
33339
33340 @enumerate 1
33341 @item Launch @code{GDB} on the main program.
33342
33343 @smallexample
33344 $ gdb -nw ada_main
33345 @end smallexample
33346
33347 @item Start the program and stop at the beginning of the main procedure
33348
33349 @smallexample
33350 (gdb) start
33351 @end smallexample
33352
33353 @noindent
33354 This step is required to be able to set a breakpoint inside the DLL. As long
33355 as the program is not run, the DLL is not loaded. This has the
33356 consequence that the DLL debugging information is also not loaded, so it is not
33357 possible to set a breakpoint in the DLL.
33358
33359 @item Set a breakpoint inside the DLL
33360
33361 @smallexample
33362 (gdb) break ada_dll
33363 (gdb) cont
33364 @end smallexample
33365
33366 @end enumerate
33367
33368 @noindent
33369 At this stage a breakpoint is set inside the DLL. From there on
33370 you can use the standard approach to debug the whole program
33371 (@pxref{Running and Debugging Ada Programs}).
33372
33373 @ignore
33374 @c This used to work, probably because the DLLs were non-relocatable
33375 @c keep this section around until the problem is sorted out.
33376
33377 To break on the @code{DllMain} routine it is not possible to follow
33378 the procedure above. At the time the program stop on @code{ada_main}
33379 the @code{DllMain} routine as already been called. Either you can use
33380 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33381
33382 @enumerate 1
33383 @item Launch @code{GDB} on the main program.
33384
33385 @smallexample
33386 $ gdb ada_main
33387 @end smallexample
33388
33389 @item Load DLL symbols
33390
33391 @smallexample
33392 (gdb) add-sym api.dll
33393 @end smallexample
33394
33395 @item Set a breakpoint inside the DLL
33396
33397 @smallexample
33398 (gdb) break ada_dll.adb:45
33399 @end smallexample
33400
33401 Note that at this point it is not possible to break using the routine symbol
33402 directly as the program is not yet running. The solution is to break
33403 on the proper line (break in @file{ada_dll.adb} line 45).
33404
33405 @item Start the program
33406
33407 @smallexample
33408 (gdb) run
33409 @end smallexample
33410
33411 @end enumerate
33412 @end ignore
33413
33414 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33415 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33416
33417 @menu
33418 * Debugging the DLL Directly::
33419 * Attaching to a Running Process::
33420 @end menu
33421
33422 @noindent
33423 In this case things are slightly more complex because it is not possible to
33424 start the main program and then break at the beginning to load the DLL and the
33425 associated DLL debugging information. It is not possible to break at the
33426 beginning of the program because there is no @code{GDB} debugging information,
33427 and therefore there is no direct way of getting initial control. This
33428 section addresses this issue by describing some methods that can be used
33429 to break somewhere in the DLL to debug it.
33430
33431 @noindent
33432 First suppose that the main procedure is named @code{main} (this is for
33433 example some C code built with Microsoft Visual C) and that there is a
33434 DLL named @code{test.dll} containing an Ada entry point named
33435 @code{ada_dll}.
33436
33437 @noindent
33438 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33439 been built with debugging information (see GNAT -g option).
33440
33441 @node Debugging the DLL Directly
33442 @subsubsection Debugging the DLL Directly
33443
33444 @enumerate 1
33445 @item
33446 Find out the executable starting address
33447
33448 @smallexample
33449 $ objdump --file-header main.exe
33450 @end smallexample
33451
33452 The starting address is reported on the last line. For example:
33453
33454 @smallexample
33455 main.exe:     file format pei-i386
33456 architecture: i386, flags 0x0000010a:
33457 EXEC_P, HAS_DEBUG, D_PAGED
33458 start address 0x00401010
33459 @end smallexample
33460
33461 @item
33462 Launch the debugger on the executable.
33463
33464 @smallexample
33465 $ gdb main.exe
33466 @end smallexample
33467
33468 @item
33469 Set a breakpoint at the starting address, and launch the program.
33470
33471 @smallexample
33472 $ (gdb) break *0x00401010
33473 $ (gdb) run
33474 @end smallexample
33475
33476 The program will stop at the given address.
33477
33478 @item
33479 Set a breakpoint on a DLL subroutine.
33480
33481 @smallexample
33482 (gdb) break ada_dll.adb:45
33483 @end smallexample
33484
33485 Or if you want to break using a symbol on the DLL, you need first to
33486 select the Ada language (language used by the DLL).
33487
33488 @smallexample
33489 (gdb) set language ada
33490 (gdb) break ada_dll
33491 @end smallexample
33492
33493 @item
33494 Continue the program.
33495
33496 @smallexample
33497 (gdb) cont
33498 @end smallexample
33499
33500 @noindent
33501 This will run the program until it reaches the breakpoint that has been
33502 set. From that point you can use the standard way to debug a program
33503 as described in (@pxref{Running and Debugging Ada Programs}).
33504
33505 @end enumerate
33506
33507 @noindent
33508 It is also possible to debug the DLL by attaching to a running process.
33509
33510 @node Attaching to a Running Process
33511 @subsubsection Attaching to a Running Process
33512 @cindex DLL debugging, attach to process
33513
33514 @noindent
33515 With @code{GDB} it is always possible to debug a running process by
33516 attaching to it. It is possible to debug a DLL this way. The limitation
33517 of this approach is that the DLL must run long enough to perform the
33518 attach operation. It may be useful for instance to insert a time wasting
33519 loop in the code of the DLL to meet this criterion.
33520
33521 @enumerate 1
33522
33523 @item Launch the main program @file{main.exe}.
33524
33525 @smallexample
33526 $ main
33527 @end smallexample
33528
33529 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33530 that the process PID for @file{main.exe} is 208.
33531
33532 @item Launch gdb.
33533
33534 @smallexample
33535 $ gdb
33536 @end smallexample
33537
33538 @item Attach to the running process to be debugged.
33539
33540 @smallexample
33541 (gdb) attach 208
33542 @end smallexample
33543
33544 @item Load the process debugging information.
33545
33546 @smallexample
33547 (gdb) symbol-file main.exe
33548 @end smallexample
33549
33550 @item Break somewhere in the DLL.
33551
33552 @smallexample
33553 (gdb) break ada_dll
33554 @end smallexample
33555
33556 @item Continue process execution.
33557
33558 @smallexample
33559 (gdb) cont
33560 @end smallexample
33561
33562 @end enumerate
33563
33564 @noindent
33565 This last step will resume the process execution, and stop at
33566 the breakpoint we have set. From there you can use the standard
33567 approach to debug a program as described in
33568 (@pxref{Running and Debugging Ada Programs}).
33569
33570 @node Setting Stack Size from gnatlink
33571 @section Setting Stack Size from @command{gnatlink}
33572
33573 @noindent
33574 It is possible to specify the program stack size at link time. On modern
33575 versions of Windows, starting with XP, this is mostly useful to set the size of
33576 the main stack (environment task). The other task stacks are set with pragma
33577 Storage_Size or with the @command{gnatbind -d} command.
33578
33579 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33580 reserve size of individual tasks, the link-time stack size applies to all
33581 tasks, and pragma Storage_Size has no effect.
33582 In particular, Stack Overflow checks are made against this
33583 link-time specified size.
33584
33585 This setting can be done with
33586 @command{gnatlink} using either:
33587
33588 @itemize @bullet
33589
33590 @item using @option{-Xlinker} linker option
33591
33592 @smallexample
33593 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33594 @end smallexample
33595
33596 This sets the stack reserve size to 0x10000 bytes and the stack commit
33597 size to 0x1000 bytes.
33598
33599 @item using @option{-Wl} linker option
33600
33601 @smallexample
33602 $ gnatlink hello -Wl,--stack=0x1000000
33603 @end smallexample
33604
33605 This sets the stack reserve size to 0x1000000 bytes. Note that with
33606 @option{-Wl} option it is not possible to set the stack commit size
33607 because the coma is a separator for this option.
33608
33609 @end itemize
33610
33611 @node Setting Heap Size from gnatlink
33612 @section Setting Heap Size from @command{gnatlink}
33613
33614 @noindent
33615 Under Windows systems, it is possible to specify the program heap size from
33616 @command{gnatlink} using either:
33617
33618 @itemize @bullet
33619
33620 @item using @option{-Xlinker} linker option
33621
33622 @smallexample
33623 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33624 @end smallexample
33625
33626 This sets the heap reserve size to 0x10000 bytes and the heap commit
33627 size to 0x1000 bytes.
33628
33629 @item using @option{-Wl} linker option
33630
33631 @smallexample
33632 $ gnatlink hello -Wl,--heap=0x1000000
33633 @end smallexample
33634
33635 This sets the heap reserve size to 0x1000000 bytes. Note that with
33636 @option{-Wl} option it is not possible to set the heap commit size
33637 because the coma is a separator for this option.
33638
33639 @end itemize
33640
33641 @end ifset
33642
33643 @c **********************************
33644 @c * GNU Free Documentation License *
33645 @c **********************************
33646 @include fdl.texi
33647 @c GNU Free Documentation License
33648
33649 @node Index,,GNU Free Documentation License, Top
33650 @unnumbered Index
33651
33652 @printindex cp
33653
33654 @contents
33655 @c Put table of contents at end, otherwise it precedes the "title page" in
33656 @c the .txt version
33657 @c Edit the pdf file to move the contents to the beginning, after the title
33658 @c page
33659
33660 @bye