OSDN Git Service

2009-07-13 Emmanuel Briot <briot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.2 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * gnatxref Switches::
394 * gnatfind Switches::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Predefined Rules::
494
495 Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 * Converting Ada Files to html with gnathtml::
505
506 @ifclear vms
507 Code Coverage and Profiling
508
509 * Code Coverage of Ada Programs using gcov::
510 * Profiling an Ada Program using gprof::
511 @end ifclear
512
513 Running and Debugging Ada Programs
514
515 * The GNAT Debugger GDB::
516 * Running GDB::
517 * Introduction to GDB Commands::
518 * Using Ada Expressions::
519 * Calling User-Defined Subprograms::
520 * Using the Next Command in a Function::
521 * Ada Exceptions::
522 * Ada Tasks::
523 * Debugging Generic Units::
524 * GNAT Abnormal Termination or Failure to Terminate::
525 * Naming Conventions for GNAT Source Files::
526 * Getting Internal Debugging Information::
527 * Stack Traceback::
528
529 @ifset vms
530 * LSE::
531 @end ifset
532
533 @ifset vms
534 Compatibility with HP Ada
535
536 * Ada Language Compatibility::
537 * Differences in the Definition of Package System::
538 * Language-Related Features::
539 * The Package STANDARD::
540 * The Package SYSTEM::
541 * Tasking and Task-Related Features::
542 * Pragmas and Pragma-Related Features::
543 * Library of Predefined Units::
544 * Bindings::
545 * Main Program Definition::
546 * Implementation-Defined Attributes::
547 * Compiler and Run-Time Interfacing::
548 * Program Compilation and Library Management::
549 * Input-Output::
550 * Implementation Limits::
551 * Tools and Utilities::
552
553 Language-Related Features
554
555 * Integer Types and Representations::
556 * Floating-Point Types and Representations::
557 * Pragmas Float_Representation and Long_Float::
558 * Fixed-Point Types and Representations::
559 * Record and Array Component Alignment::
560 * Address Clauses::
561 * Other Representation Clauses::
562
563 Tasking and Task-Related Features
564
565 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
566 * Assigning Task IDs::
567 * Task IDs and Delays::
568 * Task-Related Pragmas::
569 * Scheduling and Task Priority::
570 * The Task Stack::
571 * External Interrupts::
572
573 Pragmas and Pragma-Related Features
574
575 * Restrictions on the Pragma INLINE::
576 * Restrictions on the Pragma INTERFACE::
577 * Restrictions on the Pragma SYSTEM_NAME::
578
579 Library of Predefined Units
580
581 * Changes to DECLIB::
582
583 Bindings
584
585 * Shared Libraries and Options Files::
586 * Interfaces to C::
587 @end ifset
588
589 Platform-Specific Information for the Run-Time Libraries
590
591 * Summary of Run-Time Configurations::
592 * Specifying a Run-Time Library::
593 * Choosing the Scheduling Policy::
594 * Solaris-Specific Considerations::
595 * Linux-Specific Considerations::
596 * AIX-Specific Considerations::
597 * Irix-Specific Considerations::
598
599 Example of Binder Output File
600
601 Elaboration Order Handling in GNAT
602
603 * Elaboration Code::
604 * Checking the Elaboration Order::
605 * Controlling the Elaboration Order::
606 * Controlling Elaboration in GNAT - Internal Calls::
607 * Controlling Elaboration in GNAT - External Calls::
608 * Default Behavior in GNAT - Ensuring Safety::
609 * Treatment of Pragma Elaborate::
610 * Elaboration Issues for Library Tasks::
611 * Mixing Elaboration Models::
612 * What to Do If the Default Elaboration Behavior Fails::
613 * Elaboration for Access-to-Subprogram Values::
614 * Summary of Procedures for Elaboration Control::
615 * Other Elaboration Order Considerations::
616
617 Conditional Compilation
618 * Use of Boolean Constants::
619 * Debugging - A Special Case::
620 * Conditionalizing Declarations::
621 * Use of Alternative Implementations::
622 * Preprocessing::
623
624 Inline Assembler
625
626 * Basic Assembler Syntax::
627 * A Simple Example of Inline Assembler::
628 * Output Variables in Inline Assembler::
629 * Input Variables in Inline Assembler::
630 * Inlining Inline Assembler Code::
631 * Other Asm Functionality::
632
633 Compatibility and Porting Guide
634
635 * Compatibility with Ada 83::
636 * Compatibility between Ada 95 and Ada 2005::
637 * Implementation-dependent characteristics::
638 @ifclear vms
639 @c This brief section is only in the non-VMS version
640 @c The complete chapter on HP Ada issues is in the VMS version
641 * Compatibility with HP Ada 83::
642 @end ifclear
643 * Compatibility with Other Ada Systems::
644 * Representation Clauses::
645 @ifset vms
646 * Transitioning to 64-Bit GNAT for OpenVMS::
647 @end ifset
648
649 @ifset unw
650 Microsoft Windows Topics
651
652 * Using GNAT on Windows::
653 * CONSOLE and WINDOWS subsystems::
654 * Temporary Files::
655 * Mixed-Language Programming on Windows::
656 * Windows Calling Conventions::
657 * Introduction to Dynamic Link Libraries (DLLs)::
658 * Using DLLs with GNAT::
659 * Building DLLs with GNAT::
660 * GNAT and Windows Resources::
661 * Debugging a DLL::
662 * Setting Stack Size from gnatlink::
663 * Setting Heap Size from gnatlink::
664 @end ifset
665
666 * Index::
667 @end menu
668 @end ifnottex
669
670 @node About This Guide
671 @unnumbered About This Guide
672
673 @noindent
674 @ifset vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development toolset for the full Ada
677 programming language, implemented on OpenVMS for HP's Alpha and
678 Integrity server (I64) platforms.
679 @end ifset
680 @ifclear vms
681 This guide describes the use of @value{EDITION},
682 a compiler and software development
683 toolset for the full Ada programming language.
684 @end ifclear
685 It documents the features of the compiler and tools, and explains
686 how to use them to build Ada applications.
687
688 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
689 Ada 83 compatibility mode.
690 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
691 but you can override with a compiler switch
692 (@pxref{Compiling Different Versions of Ada})
693 to explicitly specify the language version.
694 Throughout this manual, references to ``Ada'' without a year suffix
695 apply to both the Ada 95 and Ada 2005 versions of the language.
696
697
698 @ifclear FSFEDITION
699 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
700 ``GNAT'' in the remainder of this document.
701 @end ifclear
702
703
704
705
706 @menu
707 * What This Guide Contains::
708 * What You Should Know before Reading This Guide::
709 * Related Information::
710 * Conventions::
711 @end menu
712
713 @node What This Guide Contains
714 @unnumberedsec What This Guide Contains
715
716 @noindent
717 This guide contains the following chapters:
718 @itemize @bullet
719
720 @item
721 @ref{Getting Started with GNAT}, describes how to get started compiling
722 and running Ada programs with the GNAT Ada programming environment.
723 @item
724 @ref{The GNAT Compilation Model}, describes the compilation model used
725 by GNAT.
726
727 @item
728 @ref{Compiling Using gcc}, describes how to compile
729 Ada programs with @command{gcc}, the Ada compiler.
730
731 @item
732 @ref{Binding Using gnatbind}, describes how to
733 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 utility.
735
736 @item
737 @ref{Linking Using gnatlink},
738 describes @command{gnatlink}, a
739 program that provides for linking using the GNAT run-time library to
740 construct a program. @command{gnatlink} can also incorporate foreign language
741 object units into the executable.
742
743 @item
744 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
745 utility that automatically determines the set of sources
746 needed by an Ada compilation unit, and executes the necessary compilations
747 binding and link.
748
749 @item
750 @ref{Improving Performance}, shows various techniques for making your
751 Ada program run faster or take less space.
752 It discusses the effect of the compiler's optimization switch and
753 also describes the @command{gnatelim} tool and unused subprogram/data
754 elimination.
755
756 @item
757 @ref{Renaming Files Using gnatchop}, describes
758 @code{gnatchop}, a utility that allows you to preprocess a file that
759 contains Ada source code, and split it into one or more new files, one
760 for each compilation unit.
761
762 @item
763 @ref{Configuration Pragmas}, describes the configuration pragmas
764 handled by GNAT.
765
766 @item
767 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
768 shows how to override the default GNAT file naming conventions,
769 either for an individual unit or globally.
770
771 @item
772 @ref{GNAT Project Manager}, describes how to use project files
773 to organize large projects.
774
775 @item
776 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
777 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
778 way to navigate through sources.
779
780 @item
781 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
782 version of an Ada source file with control over casing, indentation,
783 comment placement, and other elements of program presentation style.
784
785 @item
786 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
787 metrics for an Ada source file, such as the number of types and subprograms,
788 and assorted complexity measures.
789
790 @item
791 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
792 file name krunching utility, used to handle shortened
793 file names on operating systems with a limit on the length of names.
794
795 @item
796 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
797 preprocessor utility that allows a single source file to be used to
798 generate multiple or parameterized source files by means of macro
799 substitution.
800
801 @ifset vms
802 @item
803 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
804 a tool for rebuilding the GNAT run time with user-supplied
805 configuration pragmas.
806 @end ifset
807
808 @item
809 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
810 utility that displays information about compiled units, including dependences
811 on the corresponding sources files, and consistency of compilations.
812
813 @item
814 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
815 to delete files that are produced by the compiler, binder and linker.
816
817 @ifclear vms
818 @item
819 @ref{GNAT and Libraries}, describes the process of creating and using
820 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 library.
822
823 @item
824 @ref{Using the GNU make Utility}, describes some techniques for using
825 the GNAT toolset in Makefiles.
826 @end ifclear
827
828 @item
829 @ref{Memory Management Issues}, describes some useful predefined storage pools
830 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 memory references.
832 @ifclear vms
833 It also describes @command{gnatmem}, a utility that monitors dynamic
834 allocation and deallocation and helps detect ``memory leaks''.
835 @end ifclear
836
837 @item
838 @ref{Stack Related Facilities}, describes some useful tools associated with
839 stack checking and analysis.
840
841 @item
842 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
843 a utility that checks Ada code against a set of rules.
844
845 @item
846 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
847 a utility that generates empty but compilable bodies for library units.
848
849 @item
850 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
851 generate automatically Ada bindings from C and C++ headers.
852
853 @item
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
856
857 @ifclear vms
858 @item
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
861 @end ifclear
862
863 @item
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
865 Ada programs.
866
867 @ifset vms
868 @item
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
873 @cindex DEC Ada
874 and for
875 historical compatibility reasons, the relevant libraries still use the
876 DEC prefix.
877 @end ifset
878
879 @item
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
884
885 @item
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
888
889 @item
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
892
893 @item
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
896
897 @item
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
899 in an Ada program.
900
901 @item
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
905
906 @ifset unw
907 @item
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
910 @end ifset
911 @end itemize
912
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
917
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
920 @noindent
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
923 1995.
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
926 and Amendment 1).
927 Both reference manuals are included in the GNAT documentation
928 package.
929
930 @node Related Information
931 @unnumberedsec Related Information
932
933 @noindent
934 For further information about related tools, refer to the following
935 documents:
936
937 @itemize @bullet
938 @item
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
942
943 @ifset unw
944 @item
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
947
948 @item
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
951 @end ifset
952
953 @item
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
956
957 @item
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
960
961 @item
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
963 @ifset vms
964 in the GNU:[DOCS] directory,
965 @end ifset
966 for all details on the use of the GNU source-level debugger.
967
968 @item
969 @xref{Top,, The extensible self-documenting text editor, emacs,
970 GNU Emacs Manual},
971 @ifset vms
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
973 @end ifset
974 for full information on the extensible editor and programming
975 environment Emacs.
976
977 @end itemize
978
979 @c **************
980 @node Conventions
981 @unnumberedsec Conventions
982 @cindex Conventions
983 @cindex Typographical conventions
984
985 @noindent
986 Following are examples of the typographical and graphic conventions used
987 in this guide:
988
989 @itemize @bullet
990 @item
991 @code{Functions}, @command{utility program names}, @code{standard names},
992 and @code{classes}.
993
994 @item
995 @option{Option flags}
996
997 @item
998 @file{File names}, @samp{button names}, and @samp{field names}.
999
1000 @item
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1002 variables}.
1003
1004 @item
1005 @emph{Emphasis}.
1006
1007 @item
1008 @r{[}optional information or parameters@r{]}
1009
1010 @item
1011 Examples are described by text
1012 @smallexample
1013 and then shown this way.
1014 @end smallexample
1015 @end itemize
1016
1017 @noindent
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1024
1025 @ifset unw
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1030 @end ifset
1031
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1035
1036 @noindent
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1039 @ifset unw
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1050 @end ifset
1051
1052 @menu
1053 * Running GNAT::
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1057 @ifset vms
1058 * Editing with Emacs::
1059 @end ifset
1060 @ifclear vms
1061 * Introduction to GPS::
1062 @end ifclear
1063 @end menu
1064
1065 @node Running GNAT
1066 @section Running GNAT
1067
1068 @noindent
1069 Three steps are needed to create an executable file from an Ada source
1070 file:
1071
1072 @enumerate
1073 @item
1074 The source file(s) must be compiled.
1075 @item
1076 The file(s) must be bound using the GNAT binder.
1077 @item
1078 All appropriate object files must be linked to produce an executable.
1079 @end enumerate
1080
1081 @noindent
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1085
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1088
1089 @noindent
1090 Any text editor may be used to prepare an Ada program.
1091 (If @code{Emacs} is
1092 used, the optional Ada mode may be helpful in laying out the program.)
1093 The
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1097
1098 @smallexample @c ada
1099 @cartouche
1100 with Ada.Text_IO; use Ada.Text_IO;
1101 procedure Hello is
1102 begin
1103    Put_Line ("Hello WORLD!");
1104 end Hello;
1105 @end cartouche
1106 @end smallexample
1107
1108 @noindent
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1111 that each file
1112 contain a single compilation unit whose file name is the
1113 unit name,
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1124
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1127
1128 @smallexample
1129 $ gcc -c hello.adb
1130 @end smallexample
1131
1132 @noindent
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1138
1139 @ifclear vms
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1144 @end ifclear
1145
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1159
1160 @smallexample
1161 $ gnatbind hello
1162 $ gnatlink hello
1163 @end smallexample
1164
1165 @noindent
1166 A simpler method of carrying out these steps is to use
1167 @command{gnatmake},
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1174
1175 @smallexample
1176 $ gnatmake hello.adb
1177 @end smallexample
1178
1179 @noindent
1180 The result is an executable program called @file{hello}, which can be
1181 run by entering:
1182
1183 @smallexample
1184 $ ^hello^RUN HELLO^
1185 @end smallexample
1186
1187 @noindent
1188 assuming that the current directory is on the search path
1189 for executable programs.
1190
1191 @noindent
1192 and, if all has gone well, you will see
1193
1194 @smallexample
1195 Hello WORLD!
1196 @end smallexample
1197
1198 @noindent
1199 appear in response to this command.
1200
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1204
1205 @noindent
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1208
1209 @smallexample @c ada
1210 @cartouche
1211 @group
1212 package Greetings is
1213    procedure Hello;
1214    procedure Goodbye;
1215 end Greetings;
1216
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1219    procedure Hello is
1220    begin
1221       Put_Line ("Hello WORLD!");
1222    end Hello;
1223
1224    procedure Goodbye is
1225    begin
1226       Put_Line ("Goodbye WORLD!");
1227    end Goodbye;
1228 end Greetings;
1229 @end group
1230
1231 @group
1232 with Greetings;
1233 procedure Gmain is
1234 begin
1235    Greetings.Hello;
1236    Greetings.Goodbye;
1237 end Gmain;
1238 @end group
1239 @end cartouche
1240 @end smallexample
1241
1242 @noindent
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1245
1246 @table @file
1247 @item greetings.ads
1248 spec of package @code{Greetings}
1249
1250 @item greetings.adb
1251 body of package @code{Greetings}
1252
1253 @item gmain.adb
1254 body of main program
1255 @end table
1256
1257 @noindent
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1261
1262 @smallexample
1263 $ gcc -c gmain.adb
1264 $ gcc -c greetings.adb
1265 $ gnatbind gmain
1266 $ gnatlink gmain
1267 @end smallexample
1268
1269 @noindent
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1277
1278 @smallexample
1279 $ gcc -c greetings.ads -gnatc
1280 @end smallexample
1281
1282 @noindent
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1288
1289 @smallexample
1290 $ gnatmake gmain.adb
1291 @end smallexample
1292
1293 @noindent
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1295 more detail.
1296
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1300
1301 @noindent
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1311
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1321
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1324
1325 @smallexample
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1328 @end smallexample
1329
1330 @noindent
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1339
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1349
1350 @ifset vms
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1353 @cindex Emacs
1354
1355 @noindent
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1358
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1363
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1367
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1372 prompt.
1373
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1377 @end ifset
1378
1379 @ifclear vms
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1384 @noindent
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs.  This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1392
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1396 for a program.
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1401 startup menu).
1402
1403 @menu
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1406 @end menu
1407
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1410 @noindent
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1419
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1422 programs.
1423
1424 @enumerate
1425 @item @emph{Creating a project}
1426
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1429 radio buttons:
1430
1431 @itemize @bullet
1432 @item
1433 @code{Start with default project in directory}
1434
1435 @item
1436 @code{Create new project with wizard}
1437
1438 @item
1439 @code{Open existing project}
1440 @end itemize
1441
1442 @noindent
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear.  In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1465
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1470
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}.  This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1475
1476 @item @emph{Creating and saving the source file}
1477
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1480
1481 @itemize @bullet
1482 @item
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1485
1486 @item
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1490 @end itemize
1491
1492 @noindent
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1497
1498 @smallexample @c ada
1499 @group
1500 with Ada.Text_IO; use Ada.Text_IO;
1501 procedure Hello is
1502 begin
1503   Put_Line("Hello from GPS!");
1504 end Hello;
1505 @end group
1506 @end smallexample
1507
1508 @noindent
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1510 @file{hello.adb}.
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1513
1514 @item @emph{Updating the project file}
1515
1516 You need to add the new source file to the project.
1517 To do this, select
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1520 @code{Add} button.
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1523 Click @code{OK}.
1524
1525 @item @emph{Building and running the program}
1526
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1533 message.
1534
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1539
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1545 @end enumerate
1546
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1549 @noindent
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1552
1553 @enumerate
1554 @item @emph{Opening a project}
1555
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1558 earlier example.
1559
1560 @item @emph{Creating a source file}
1561
1562 Select @code{File}, then @code{New}, and type in the following program:
1563
1564 @smallexample @c ada
1565 @group
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568    Line : String (1..80);
1569    N    : Natural;
1570 begin
1571    Put_Line("Type a line of text at each prompt; an empty line to exit");
1572    loop
1573       Put(": ");
1574       Get_Line (Line, N);
1575       Put_Line (Line (1..N) );
1576       exit when N=0;
1577    end loop;
1578 end Example;
1579 @end group
1580 @end smallexample
1581
1582 @noindent
1583 Select @code{File}, then @code{Save as}, and enter the file name
1584 @file{example.adb}.
1585
1586 @item @emph{Updating the project file}
1587
1588 Add @code{Example} as a new main unit for the project:
1589 @enumerate a
1590 @item
1591 Select @code{Project}, then @code{Edit Project Properties}.
1592
1593 @item
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1596 click @code{Open}.
1597 You will see the file name appear in the list of main units
1598
1599 @item
1600 Click @code{OK}
1601 @end enumerate
1602
1603 @item @emph{Building/running the executable}
1604
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1607
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1611
1612 @item @emph{Debugging the program}
1613
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1616 a new project.
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1619
1620 @enumerate a
1621 @item @emph{Initializing}
1622
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1624
1625 @item @emph{Setting a breakpoint}
1626
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1633
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1636
1637 @item @emph{Starting program execution}
1638
1639 Select @code{Debug}, then @code{Run}.  When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1645
1646 @item @emph{Examining a variable}
1647
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1653
1654 @item @emph{Assigning a new value to a variable}
1655
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1659 @code{OK}.
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1664
1665 @item @emph{Single stepping}
1666
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1673
1674 @item @emph{Removing a breakpoint}
1675
1676 Toggle the breakpoint icon at line 10.
1677
1678 @item @emph{Resuming execution from a breakpoint}
1679
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1686 @end enumerate
1687 @end enumerate
1688 @end ifclear
1689
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1694
1695 @menu
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1706 @ifclear vms
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1709 @end ifclear
1710 * Comparison between GNAT and Conventional Ada Library Models::
1711 @ifset vms
1712 * Placement of temporary files::
1713 @end ifset
1714 @end menu
1715
1716 @noindent
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1727
1728 @node Source Representation
1729 @section Source Representation
1730 @cindex Latin-1
1731
1732 @noindent
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1739
1740 @table @code
1741 @item VT
1742 @findex VT
1743 Vertical tab, @code{16#0B#}
1744
1745 @item HT
1746 @findex HT
1747 Horizontal tab, @code{16#09#}
1748
1749 @item CR
1750 @findex CR
1751 Carriage return, @code{16#0D#}
1752
1753 @item LF
1754 @findex LF
1755 Line feed, @code{16#0A#}
1756
1757 @item FF
1758 @findex FF
1759 Form feed, @code{16#0C#}
1760 @end table
1761
1762 @noindent
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1768
1769 @cindex End of source file
1770 @cindex Source file, end
1771 @findex SUB
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1777
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1784
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1787
1788 @noindent
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1792 @menu
1793 * Latin-1::
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1796 @end menu
1797
1798 @node Latin-1
1799 @subsection Latin-1
1800 @cindex Latin-1
1801
1802 @noindent
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1809
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1817
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1820
1821 @noindent
1822 GNAT also supports several other 8-bit coding schemes:
1823
1824 @table @asis
1825 @item ISO 8859-2 (Latin-2)
1826 @cindex Latin-2
1827 @cindex ISO 8859-2
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-3 (Latin-3)
1832 @cindex Latin-3
1833 @cindex ISO 8859-3
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-4 (Latin-4)
1838 @cindex Latin-4
1839 @cindex ISO 8859-4
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-5 (Cyrillic)
1844 @cindex ISO 8859-5
1845 @cindex Cyrillic
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1848
1849 @item ISO 8859-15 (Latin-9)
1850 @cindex ISO 8859-15
1851 @cindex Latin-9
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1854
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1862
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1869
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1876
1877 @item No Upper-Half
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1880 @end table
1881
1882 @noindent
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1887
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1890
1891 @noindent
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1895
1896 @table @asis
1897
1898 @item Hex Coding
1899 In this encoding, a wide character is represented by the following five
1900 character sequence:
1901
1902 @smallexample
1903 ESC a b c d
1904 @end smallexample
1905
1906 @noindent
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1910 @code{16#A345#}.
1911 This scheme is compatible with use of the full Wide_Character set.
1912
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1920 external coding.
1921
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1925 @code{16#ab#} and
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1931
1932 @item EUC Coding
1933 @cindex EUC Coding
1934 A wide character is represented by a two-character sequence
1935 @code{16#ab#} and
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1940
1941 @item UTF-8 Coding
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1946 @smallexample
1947 @iftex
1948 @leftskip=.7cm
1949 @end iftex
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1953
1954 @end smallexample
1955
1956 @noindent
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1966 character sequence:
1967
1968 @smallexample
1969 [ " a b c d " ]
1970 @end smallexample
1971
1972 @noindent
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1979
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1983
1984 @end table
1985
1986 @noindent
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1990
1991 @node File Naming Rules
1992 @section File Naming Rules
1993
1994 @noindent
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
1999
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2002 @ifset vms
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2004 @end ifset
2005 @ifclear vms
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2007 @end ifclear
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2013 @ifset vms
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2015 @end ifset
2016 @ifclear vms
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2018 @end ifclear
2019 respectively.
2020
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2024
2025 @table @file
2026 @item main.ads
2027 Main (spec)
2028 @item main.adb
2029 Main (body)
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2034 @item func-spec.ads
2035 Func.Spec (child package spec)
2036 @item func-spec.adb
2037 Func.Spec (child package body)
2038 @item main-sub.adb
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2042 @end table
2043
2044 @noindent
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2052
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2061
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2069
2070 @node Using Other File Names
2071 @section Using Other File Names
2072 @cindex File names
2073
2074 @noindent
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2079 the files it needs.
2080
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2087
2088 @smallexample @c ada
2089 @cartouche
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091   Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093   Body_File_Name => "myutilst.ada");
2094 @end cartouche
2095 @end smallexample
2096
2097 @noindent
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2103
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2111
2112 @ifclear vms
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2119
2120 @smallexample
2121 $ gcc -c -x ada peculiar_file_name.sim
2122 @end smallexample
2123 @end ifclear
2124
2125 @noindent
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2130 be omitted.
2131
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2135 @cindex File names
2136
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2142
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2148
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151    Spec_File_Name  => FILE_NAME_PATTERN
2152  @r{[},Casing          => CASING_SPEC@r{]}
2153  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156    Body_File_Name  => FILE_NAME_PATTERN
2157  @r{[},Casing          => CASING_SPEC@r{]}
2158  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2159
2160 pragma Source_File_Name (
2161    Subunit_File_Name  => FILE_NAME_PATTERN
2162  @r{[},Casing             => CASING_SPEC@r{]}
2163  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2164
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2167 @end smallexample
2168
2169 @noindent
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2178
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2182 file name.
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2187
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2193
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2200
2201 The file name translation works in the following steps:
2202
2203 @itemize @bullet
2204
2205 @item
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2208
2209 @item
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2214
2215 @item
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2219
2220 @end itemize
2221
2222 @noindent
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2227 two pragmas appear:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231   (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233   (Body_File_Name => "*.2.ada");
2234 @end smallexample
2235
2236 @noindent
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2239
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2245 @end smallexample
2246
2247 @noindent
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2256
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259   (Spec_File_Name => "*_.ADA",
2260    Dot_Replacement => "__",
2261    Casing = Uppercase);
2262 pragma Source_File_Name
2263   (Body_File_Name => "*.ADA",
2264    Dot_Replacement => "__",
2265    Casing = Uppercase);
2266 pragma Source_File_Name
2267   (Subunit_File_Name => "*.SEP",
2268    Dot_Replacement => "__",
2269    Casing = Uppercase);
2270 @end smallexample
2271
2272 @node Generating Object Files
2273 @section Generating Object Files
2274
2275 @noindent
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2280
2281 @itemize @bullet
2282 @item
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2285
2286 @item
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2291
2292 @item
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2296
2297 @item
2298 @cindex Subunits
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2301 subunits.
2302
2303 @item
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2307
2308 @item
2309 @cindex Generics
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2315 @end itemize
2316
2317 @noindent
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2321 @file{.o} as usual.
2322
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2329
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2334
2335 @node Source Dependencies
2336 @section Source Dependencies
2337
2338 @noindent
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2343 recompiled.
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2346
2347 @itemize @bullet
2348 @item
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2354
2355 @item
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2358 unit.
2359
2360 @item
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2364
2365 @item
2366 @findex Inline
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2374
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates  inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2380
2381 When using a gcc-based back end (in practice this means using any version
2382 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2383 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2384 Historically front end inlining was more extensive than the gcc back end
2385 inlining, but that is no longer the case.
2386
2387 @item
2388 If an object file @file{O} depends on the proper body of a subunit through
2389 inlining or instantiation, it depends on the parent unit of the subunit.
2390 This means that any modification of the parent unit or one of its subunits
2391 affects the compilation of @file{O}.
2392
2393 @item
2394 The object file for a parent unit depends on all its subunit body files.
2395
2396 @item
2397 The previous two rules meant that for purposes of computing dependencies and
2398 recompilation, a body and all its subunits are treated as an indivisible whole.
2399
2400 @noindent
2401 These rules are applied transitively: if unit @code{A} @code{with}'s
2402 unit @code{B}, whose elaboration calls an inlined procedure in package
2403 @code{C}, the object file for unit @code{A} will depend on the body of
2404 @code{C}, in file @file{c.adb}.
2405
2406 The set of dependent files described by these rules includes all the
2407 files on which the unit is semantically dependent, as dictated by the
2408 Ada language standard. However, it is a superset of what the
2409 standard describes, because it includes generic, inline, and subunit
2410 dependencies.
2411
2412 An object file must be recreated by recompiling the corresponding source
2413 file if any of the source files on which it depends are modified. For
2414 example, if the @code{make} utility is used to control compilation,
2415 the rule for an Ada object file must mention all the source files on
2416 which the object file depends, according to the above definition.
2417 The determination of the necessary
2418 recompilations is done automatically when one uses @command{gnatmake}.
2419 @end itemize
2420
2421 @node The Ada Library Information Files
2422 @section The Ada Library Information Files
2423 @cindex Ada Library Information files
2424 @cindex @file{ALI} files
2425
2426 @noindent
2427 Each compilation actually generates two output files. The first of these
2428 is the normal object file that has a @file{.o} extension. The second is a
2429 text file containing full dependency information. It has the same
2430 name as the source file, but an @file{.ali} extension.
2431 This file is known as the Ada Library Information (@file{ALI}) file.
2432 The following information is contained in the @file{ALI} file.
2433
2434 @itemize @bullet
2435 @item
2436 Version information (indicates which version of GNAT was used to compile
2437 the unit(s) in question)
2438
2439 @item
2440 Main program information (including priority and time slice settings,
2441 as well as the wide character encoding used during compilation).
2442
2443 @item
2444 List of arguments used in the @command{gcc} command for the compilation
2445
2446 @item
2447 Attributes of the unit, including configuration pragmas used, an indication
2448 of whether the compilation was successful, exception model used etc.
2449
2450 @item
2451 A list of relevant restrictions applying to the unit (used for consistency)
2452 checking.
2453
2454 @item
2455 Categorization information (e.g.@: use of pragma @code{Pure}).
2456
2457 @item
2458 Information on all @code{with}'ed units, including presence of
2459 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460
2461 @item
2462 Information from any @code{Linker_Options} pragmas used in the unit
2463
2464 @item
2465 Information on the use of @code{Body_Version} or @code{Version}
2466 attributes in the unit.
2467
2468 @item
2469 Dependency information. This is a list of files, together with
2470 time stamp and checksum information. These are files on which
2471 the unit depends in the sense that recompilation is required
2472 if any of these units are modified.
2473
2474 @item
2475 Cross-reference data. Contains information on all entities referenced
2476 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2477 provide cross-reference information.
2478
2479 @end itemize
2480
2481 @noindent
2482 For a full detailed description of the format of the @file{ALI} file,
2483 see the source of the body of unit @code{Lib.Writ}, contained in file
2484 @file{lib-writ.adb} in the GNAT compiler sources.
2485
2486 @node Binding an Ada Program
2487 @section Binding an Ada Program
2488
2489 @noindent
2490 When using languages such as C and C++, once the source files have been
2491 compiled the only remaining step in building an executable program
2492 is linking the object modules together. This means that it is possible to
2493 link an inconsistent version of a program, in which two units have
2494 included different versions of the same header.
2495
2496 The rules of Ada do not permit such an inconsistent program to be built.
2497 For example, if two clients have different versions of the same package,
2498 it is illegal to build a program containing these two clients.
2499 These rules are enforced by the GNAT binder, which also determines an
2500 elaboration order consistent with the Ada rules.
2501
2502 The GNAT binder is run after all the object files for a program have
2503 been created. It is given the name of the main program unit, and from
2504 this it determines the set of units required by the program, by reading the
2505 corresponding ALI files. It generates error messages if the program is
2506 inconsistent or if no valid order of elaboration exists.
2507
2508 If no errors are detected, the binder produces a main program, in Ada by
2509 default, that contains calls to the elaboration procedures of those
2510 compilation unit that require them, followed by
2511 a call to the main program. This Ada program is compiled to generate the
2512 object file for the main program. The name of
2513 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2514 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 main program unit.
2516
2517 Finally, the linker is used to build the resulting executable program,
2518 using the object from the main program from the bind step as well as the
2519 object files for the Ada units of the program.
2520
2521 @node Mixed Language Programming
2522 @section Mixed Language Programming
2523 @cindex Mixed Language Programming
2524
2525 @noindent
2526 This section describes how to develop a mixed-language program,
2527 specifically one that comprises units in both Ada and C.
2528
2529 @menu
2530 * Interfacing to C::
2531 * Calling Conventions::
2532 @end menu
2533
2534 @node Interfacing to C
2535 @subsection Interfacing to C
2536 @noindent
2537 Interfacing Ada with a foreign language such as C involves using
2538 compiler directives to import and/or export entity definitions in each
2539 language---using @code{extern} statements in C, for instance, and the
2540 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2541 A full treatment of these topics is provided in Appendix B, section 1
2542 of the Ada Reference Manual.
2543
2544 There are two ways to build a program using GNAT that contains some Ada
2545 sources and some foreign language sources, depending on whether or not
2546 the main subprogram is written in Ada.  Here is a source example with
2547 the main subprogram in Ada:
2548
2549 @smallexample
2550 /* file1.c */
2551 #include <stdio.h>
2552
2553 void print_num (int num)
2554 @{
2555   printf ("num is %d.\n", num);
2556   return;
2557 @}
2558
2559 /* file2.c */
2560
2561 /* num_from_Ada is declared in my_main.adb */
2562 extern int num_from_Ada;
2563
2564 int get_num (void)
2565 @{
2566   return num_from_Ada;
2567 @}
2568 @end smallexample
2569
2570 @smallexample @c ada
2571 --  my_main.adb
2572 procedure My_Main is
2573
2574    --  Declare then export an Integer entity called num_from_Ada
2575    My_Num : Integer := 10;
2576    pragma Export (C, My_Num, "num_from_Ada");
2577
2578    --  Declare an Ada function spec for Get_Num, then use
2579    --  C function get_num for the implementation.
2580    function Get_Num return Integer;
2581    pragma Import (C, Get_Num, "get_num");
2582
2583    --  Declare an Ada procedure spec for Print_Num, then use
2584    --  C function print_num for the implementation.
2585    procedure Print_Num (Num : Integer);
2586    pragma Import (C, Print_Num, "print_num");
2587
2588 begin
2589    Print_Num (Get_Num);
2590 end My_Main;
2591 @end smallexample
2592
2593 @enumerate
2594 @item
2595 To build this example, first compile the foreign language files to
2596 generate object files:
2597 @smallexample
2598 ^gcc -c file1.c^gcc -c FILE1.C^
2599 ^gcc -c file2.c^gcc -c FILE2.C^
2600 @end smallexample
2601
2602 @item
2603 Then, compile the Ada units to produce a set of object files and ALI
2604 files:
2605 @smallexample
2606 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 @end smallexample
2608
2609 @item
2610 Run the Ada binder on the Ada main program:
2611 @smallexample
2612 gnatbind my_main.ali
2613 @end smallexample
2614
2615 @item
2616 Link the Ada main program, the Ada objects and the other language
2617 objects:
2618 @smallexample
2619 gnatlink my_main.ali file1.o file2.o
2620 @end smallexample
2621 @end enumerate
2622
2623 The last three steps can be grouped in a single command:
2624 @smallexample
2625 gnatmake my_main.adb -largs file1.o file2.o
2626 @end smallexample
2627
2628 @cindex Binder output file
2629 @noindent
2630 If the main program is in a language other than Ada, then you may have
2631 more than one entry point into the Ada subsystem. You must use a special
2632 binder option to generate callable routines that initialize and
2633 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2634 Calls to the initialization and finalization routines must be inserted
2635 in the main program, or some other appropriate point in the code. The
2636 call to initialize the Ada units must occur before the first Ada
2637 subprogram is called, and the call to finalize the Ada units must occur
2638 after the last Ada subprogram returns. The binder will place the
2639 initialization and finalization subprograms into the
2640 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2641 sources.  To illustrate, we have the following example:
2642
2643 @smallexample
2644 /* main.c */
2645 extern void adainit (void);
2646 extern void adafinal (void);
2647 extern int add (int, int);
2648 extern int sub (int, int);
2649
2650 int main (int argc, char *argv[])
2651 @{
2652   int a = 21, b = 7;
2653
2654   adainit();
2655
2656   /* Should print "21 + 7 = 28" */
2657   printf ("%d + %d = %d\n", a, b, add (a, b));
2658   /* Should print "21 - 7 = 14" */
2659   printf ("%d - %d = %d\n", a, b, sub (a, b));
2660
2661   adafinal();
2662 @}
2663 @end smallexample
2664
2665 @smallexample @c ada
2666 --  unit1.ads
2667 package Unit1 is
2668    function Add (A, B : Integer) return Integer;
2669    pragma Export (C, Add, "add");
2670 end Unit1;
2671
2672 --  unit1.adb
2673 package body Unit1 is
2674    function Add (A, B : Integer) return Integer is
2675    begin
2676       return A + B;
2677    end Add;
2678 end Unit1;
2679
2680 --  unit2.ads
2681 package Unit2 is
2682    function Sub (A, B : Integer) return Integer;
2683    pragma Export (C, Sub, "sub");
2684 end Unit2;
2685
2686 --  unit2.adb
2687 package body Unit2 is
2688    function Sub (A, B : Integer) return Integer is
2689    begin
2690       return A - B;
2691    end Sub;
2692 end Unit2;
2693 @end smallexample
2694
2695 @enumerate
2696 @item
2697 The build procedure for this application is similar to the last
2698 example's.  First, compile the foreign language files to generate object
2699 files:
2700 @smallexample
2701 ^gcc -c main.c^gcc -c main.c^
2702 @end smallexample
2703
2704 @item
2705 Next, compile the Ada units to produce a set of object files and ALI
2706 files:
2707 @smallexample
2708 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 @end smallexample
2711
2712 @item
2713 Run the Ada binder on every generated ALI file.  Make sure to use the
2714 @option{-n} option to specify a foreign main program:
2715 @smallexample
2716 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 @end smallexample
2718
2719 @item
2720 Link the Ada main program, the Ada objects and the foreign language
2721 objects. You need only list the last ALI file here:
2722 @smallexample
2723 gnatlink unit2.ali main.o -o exec_file
2724 @end smallexample
2725
2726 This procedure yields a binary executable called @file{exec_file}.
2727 @end enumerate
2728
2729 @noindent
2730 Depending on the circumstances (for example when your non-Ada main object
2731 does not provide symbol @code{main}), you may also need to instruct the
2732 GNAT linker not to include the standard startup objects by passing the
2733 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2734
2735 @node Calling Conventions
2736 @subsection Calling Conventions
2737 @cindex Foreign Languages
2738 @cindex Calling Conventions
2739 GNAT follows standard calling sequence conventions and will thus interface
2740 to any other language that also follows these conventions. The following
2741 Convention identifiers are recognized by GNAT:
2742
2743 @table @code
2744 @cindex Interfacing to Ada
2745 @cindex Other Ada compilers
2746 @cindex Convention Ada
2747 @item Ada
2748 This indicates that the standard Ada calling sequence will be
2749 used and all Ada data items may be passed without any limitations in the
2750 case where GNAT is used to generate both the caller and callee. It is also
2751 possible to mix GNAT generated code and code generated by another Ada
2752 compiler. In this case, the data types should be restricted to simple
2753 cases, including primitive types. Whether complex data types can be passed
2754 depends on the situation. Probably it is safe to pass simple arrays, such
2755 as arrays of integers or floats. Records may or may not work, depending
2756 on whether both compilers lay them out identically. Complex structures
2757 involving variant records, access parameters, tasks, or protected types,
2758 are unlikely to be able to be passed.
2759
2760 Note that in the case of GNAT running
2761 on a platform that supports HP Ada 83, a higher degree of compatibility
2762 can be guaranteed, and in particular records are layed out in an identical
2763 manner in the two compilers. Note also that if output from two different
2764 compilers is mixed, the program is responsible for dealing with elaboration
2765 issues. Probably the safest approach is to write the main program in the
2766 version of Ada other than GNAT, so that it takes care of its own elaboration
2767 requirements, and then call the GNAT-generated adainit procedure to ensure
2768 elaboration of the GNAT components. Consult the documentation of the other
2769 Ada compiler for further details on elaboration.
2770
2771 However, it is not possible to mix the tasking run time of GNAT and
2772 HP Ada 83, All the tasking operations must either be entirely within
2773 GNAT compiled sections of the program, or entirely within HP Ada 83
2774 compiled sections of the program.
2775
2776 @cindex Interfacing to Assembly
2777 @cindex Convention Assembler
2778 @item Assembler
2779 Specifies assembler as the convention. In practice this has the
2780 same effect as convention Ada (but is not equivalent in the sense of being
2781 considered the same convention).
2782
2783 @cindex Convention Asm
2784 @findex Asm
2785 @item Asm
2786 Equivalent to Assembler.
2787
2788 @cindex Interfacing to COBOL
2789 @cindex Convention COBOL
2790 @findex COBOL
2791 @item COBOL
2792 Data will be passed according to the conventions described
2793 in section B.4 of the Ada Reference Manual.
2794
2795 @findex C
2796 @cindex Interfacing to C
2797 @cindex Convention C
2798 @item C
2799 Data will be passed according to the conventions described
2800 in section B.3 of the Ada Reference Manual.
2801
2802 A note on interfacing to a C ``varargs'' function:
2803 @findex C varargs function
2804 @cindex Interfacing to C varargs function
2805 @cindex varargs function interfaces
2806
2807 @itemize @bullet
2808 @item
2809 In C, @code{varargs} allows a function to take a variable number of
2810 arguments. There is no direct equivalent in this to Ada. One
2811 approach that can be used is to create a C wrapper for each
2812 different profile and then interface to this C wrapper. For
2813 example, to print an @code{int} value using @code{printf},
2814 create a C function @code{printfi} that takes two arguments, a
2815 pointer to a string and an int, and calls @code{printf}.
2816 Then in the Ada program, use pragma @code{Import} to
2817 interface to @code{printfi}.
2818
2819 @item
2820 It may work on some platforms to directly interface to
2821 a @code{varargs} function by providing a specific Ada profile
2822 for a particular call. However, this does not work on
2823 all platforms, since there is no guarantee that the
2824 calling sequence for a two argument normal C function
2825 is the same as for calling a @code{varargs} C function with
2826 the same two arguments.
2827 @end itemize
2828
2829 @cindex Convention Default
2830 @findex Default
2831 @item Default
2832 Equivalent to C.
2833
2834 @cindex Convention External
2835 @findex External
2836 @item External
2837 Equivalent to C.
2838
2839 @ifclear vms
2840 @findex C++
2841 @cindex Interfacing to C++
2842 @cindex Convention C++
2843 @item C_Plus_Plus (or CPP)
2844 This stands for C++. For most purposes this is identical to C.
2845 See the separate description of the specialized GNAT pragmas relating to
2846 C++ interfacing for further details.
2847 @end ifclear
2848
2849 @findex Fortran
2850 @cindex Interfacing to Fortran
2851 @cindex Convention Fortran
2852 @item Fortran
2853 Data will be passed according to the conventions described
2854 in section B.5 of the Ada Reference Manual.
2855
2856 @item Intrinsic
2857 This applies to an intrinsic operation, as defined in the Ada
2858 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2859 this means that the body of the subprogram is provided by the compiler itself,
2860 usually by means of an efficient code sequence, and that the user does not
2861 supply an explicit body for it. In an application program, the pragma may
2862 be applied to the following sets of names:
2863
2864 @itemize @bullet
2865 @item
2866 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2867 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2868 two formal parameters. The
2869 first one must be a signed integer type or a modular type with a binary
2870 modulus, and the second parameter must be of type Natural.
2871 The return type must be the same as the type of the first argument. The size
2872 of this type can only be 8, 16, 32, or 64.
2873
2874 @item
2875 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2876 The corresponding operator declaration must have parameters and result type
2877 that have the same root numeric type (for example, all three are long_float
2878 types). This simplifies the definition of operations that use type checking
2879 to perform dimensional checks:
2880
2881 @smallexample @c ada
2882 type Distance is new Long_Float;
2883 type Time     is new Long_Float;
2884 type Velocity is new Long_Float;
2885 function "/" (D : Distance; T : Time)
2886   return Velocity;
2887 pragma Import (Intrinsic, "/");
2888 @end smallexample
2889
2890 @noindent
2891 This common idiom is often programmed with a generic definition and an
2892 explicit body. The pragma makes it simpler to introduce such declarations.
2893 It incurs no overhead in compilation time or code size, because it is
2894 implemented as a single machine instruction.
2895
2896 @item
2897 General subprogram entities, to bind an Ada subprogram declaration to
2898 a compiler builtin by name with back-ends where such interfaces are
2899 available. A typical example is the set of ``__builtin'' functions
2900 exposed by the GCC back-end, as in the following example:
2901
2902 @smallexample @c ada
2903    function builtin_sqrt (F : Float) return Float;
2904    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 @end smallexample
2906
2907 Most of the GCC builtins are accessible this way, and as for other
2908 import conventions (e.g. C), it is the user's responsibility to ensure
2909 that the Ada subprogram profile matches the underlying builtin
2910 expectations.
2911 @end itemize
2912
2913 @noindent
2914
2915 @ifset unw
2916 @findex Stdcall
2917 @cindex Convention Stdcall
2918 @item Stdcall
2919 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2920 and specifies that the @code{Stdcall} calling sequence will be used,
2921 as defined by the NT API. Nevertheless, to ease building
2922 cross-platform bindings this convention will be handled as a @code{C} calling
2923 convention on non-Windows platforms.
2924
2925 @findex DLL
2926 @cindex Convention DLL
2927 @item DLL
2928 This is equivalent to @code{Stdcall}.
2929
2930 @findex Win32
2931 @cindex Convention Win32
2932 @item Win32
2933 This is equivalent to @code{Stdcall}.
2934 @end ifset
2935
2936 @findex Stubbed
2937 @cindex Convention Stubbed
2938 @item Stubbed
2939 This is a special convention that indicates that the compiler
2940 should provide a stub body that raises @code{Program_Error}.
2941 @end table
2942
2943 @noindent
2944 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2945 that can be used to parametrize conventions and allow additional synonyms
2946 to be specified. For example if you have legacy code in which the convention
2947 identifier Fortran77 was used for Fortran, you can use the configuration
2948 pragma:
2949
2950 @smallexample @c ada
2951 pragma Convention_Identifier (Fortran77, Fortran);
2952 @end smallexample
2953
2954 @noindent
2955 And from now on the identifier Fortran77 may be used as a convention
2956 identifier (for example in an @code{Import} pragma) with the same
2957 meaning as Fortran.
2958
2959 @ifclear vms
2960 @node Building Mixed Ada & C++ Programs
2961 @section Building Mixed Ada and C++ Programs
2962
2963 @noindent
2964 A programmer inexperienced with mixed-language development may find that
2965 building an application containing both Ada and C++ code can be a
2966 challenge.  This section gives a few
2967 hints that should make this task easier. The first section addresses
2968 the differences between interfacing with C and interfacing with C++.
2969 The second section
2970 looks into the delicate problem of linking the complete application from
2971 its Ada and C++ parts. The last section gives some hints on how the GNAT
2972 run-time library can be adapted in order to allow inter-language dispatching
2973 with a new C++ compiler.
2974
2975 @menu
2976 * Interfacing to C++::
2977 * Linking a Mixed C++ & Ada Program::
2978 * A Simple Example::
2979 * Interfacing with C++ constructors::
2980 * Interfacing with C++ at the Class Level::
2981 @end menu
2982
2983 @node Interfacing to C++
2984 @subsection Interfacing to C++
2985
2986 @noindent
2987 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2988 generating code that is compatible with the G++ Application Binary
2989 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2990
2991 @noindent
2992 Interfacing can be done at 3 levels: simple data, subprograms, and
2993 classes. In the first two cases, GNAT offers a specific @code{Convention
2994 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2995 Usually, C++ mangles the names of subprograms. To generate proper mangled
2996 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2997 This problem can also be addressed manually in two ways:
2998
2999 @itemize @bullet
3000 @item
3001 by modifying the C++ code in order to force a C convention using
3002 the @code{extern "C"} syntax.
3003
3004 @item
3005 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3006 Link_Name argument of the pragma import.
3007 @end itemize
3008
3009 @noindent
3010 Interfacing at the class level can be achieved by using the GNAT specific
3011 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3012 gnat_rm, GNAT Reference Manual}, for additional information.
3013
3014 @node Linking a Mixed C++ & Ada Program
3015 @subsection Linking a Mixed C++ & Ada Program
3016
3017 @noindent
3018 Usually the linker of the C++ development system must be used to link
3019 mixed applications because most C++ systems will resolve elaboration
3020 issues (such as calling constructors on global class instances)
3021 transparently during the link phase. GNAT has been adapted to ease the
3022 use of a foreign linker for the last phase. Three cases can be
3023 considered:
3024 @enumerate
3025
3026 @item
3027 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3028 The C++ linker can simply be called by using the C++ specific driver
3029 called @code{g++}.
3030
3031 Note that if the C++ code uses inline functions, you will need to
3032 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3033 order to provide an existing function implementation that the Ada code can
3034 link with.
3035
3036 @smallexample
3037 $ g++ -c -fkeep-inline-functions file1.C
3038 $ g++ -c -fkeep-inline-functions file2.C
3039 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3040 @end smallexample
3041
3042 @item
3043 Using GNAT and G++ from two different GCC installations: If both
3044 compilers are on the @env{PATH}, the previous method may be used. It is
3045 important to note that environment variables such as
3046 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3047 @env{GCC_ROOT} will affect both compilers
3048 at the same time and may make one of the two compilers operate
3049 improperly if set during invocation of the wrong compiler.  It is also
3050 very important that the linker uses the proper @file{libgcc.a} GCC
3051 library -- that is, the one from the C++ compiler installation. The
3052 implicit link command as suggested in the @command{gnatmake} command
3053 from the former example can be replaced by an explicit link command with
3054 the full-verbosity option in order to verify which library is used:
3055 @smallexample
3056 $ gnatbind ada_unit
3057 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3058 @end smallexample
3059 If there is a problem due to interfering environment variables, it can
3060 be worked around by using an intermediate script. The following example
3061 shows the proper script to use when GNAT has not been installed at its
3062 default location and g++ has been installed at its default location:
3063
3064 @smallexample
3065 $ cat ./my_script
3066 #!/bin/sh
3067 unset BINUTILS_ROOT
3068 unset GCC_ROOT
3069 c++ $*
3070 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3071 @end smallexample
3072
3073 @item
3074 Using a non-GNU C++ compiler: The commands previously described can be
3075 used to insure that the C++ linker is used. Nonetheless, you need to add
3076 a few more parameters to the link command line, depending on the exception
3077 mechanism used.
3078
3079 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3080 to the libgcc libraries are required:
3081
3082 @smallexample
3083 $ cat ./my_script
3084 #!/bin/sh
3085 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3086 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3087 @end smallexample
3088
3089 Where CC is the name of the non-GNU C++ compiler.
3090
3091 If the @code{zero cost} exception mechanism is used, and the platform
3092 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3093 paths to more objects are required:
3094
3095 @smallexample
3096 $ cat ./my_script
3097 #!/bin/sh
3098 CC `gcc -print-file-name=crtbegin.o` $* \
3099 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3100 `gcc -print-file-name=crtend.o`
3101 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3102 @end smallexample
3103
3104 If the @code{zero cost} exception mechanism is used, and the platform
3105 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3106 Tru64 or AIX), the simple approach described above will not work and
3107 a pre-linking phase using GNAT will be necessary.
3108
3109 @end enumerate
3110
3111 Another alternative is to use the @command{gprbuild} multi-language builder
3112 which has a large knowledge base and knows how to link Ada and C++ code
3113 together automatically in most cases.
3114
3115 @node A Simple Example
3116 @subsection  A Simple Example
3117 @noindent
3118 The following example, provided as part of the GNAT examples, shows how
3119 to achieve procedural interfacing between Ada and C++ in both
3120 directions. The C++ class A has two methods. The first method is exported
3121 to Ada by the means of an extern C wrapper function. The second method
3122 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3123 a limited record with a layout comparable to the C++ class. The Ada
3124 subprogram, in turn, calls the C++ method. So, starting from the C++
3125 main program, the process passes back and forth between the two
3126 languages.
3127
3128 @noindent
3129 Here are the compilation commands:
3130 @smallexample
3131 $ gnatmake -c simple_cpp_interface
3132 $ g++ -c cpp_main.C
3133 $ g++ -c ex7.C
3134 $ gnatbind -n simple_cpp_interface
3135 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3136       -lstdc++ ex7.o cpp_main.o
3137 @end smallexample
3138
3139 @noindent
3140 Here are the corresponding sources:
3141 @smallexample
3142
3143 //cpp_main.C
3144
3145 #include "ex7.h"
3146
3147 extern "C" @{
3148   void adainit (void);
3149   void adafinal (void);
3150   void method1 (A *t);
3151 @}
3152
3153 void method1 (A *t)
3154 @{
3155   t->method1 ();
3156 @}
3157
3158 int main ()
3159 @{
3160   A obj;
3161   adainit ();
3162   obj.method2 (3030);
3163   adafinal ();
3164 @}
3165
3166 //ex7.h
3167
3168 class Origin @{
3169  public:
3170   int o_value;
3171 @};
3172 class A : public Origin @{
3173  public:
3174   void method1 (void);
3175   void method2 (int v);
3176   A();
3177   int   a_value;
3178 @};
3179
3180 //ex7.C
3181
3182 #include "ex7.h"
3183 #include <stdio.h>
3184
3185 extern "C" @{ void ada_method2 (A *t, int v);@}
3186
3187 void A::method1 (void)
3188 @{
3189   a_value = 2020;
3190   printf ("in A::method1, a_value = %d \n",a_value);
3191
3192 @}
3193
3194 void A::method2 (int v)
3195 @{
3196    ada_method2 (this, v);
3197    printf ("in A::method2, a_value = %d \n",a_value);
3198
3199 @}
3200
3201 A::A(void)
3202 @{
3203    a_value = 1010;
3204   printf ("in A::A, a_value = %d \n",a_value);
3205 @}
3206 @end smallexample
3207
3208 @smallexample @c ada
3209 -- Ada sources
3210 package body Simple_Cpp_Interface is
3211
3212    procedure Ada_Method2 (This : in out A; V : Integer) is
3213    begin
3214       Method1 (This);
3215       This.A_Value := V;
3216    end Ada_Method2;
3217
3218 end Simple_Cpp_Interface;
3219
3220 with System;
3221 package Simple_Cpp_Interface is
3222    type A is limited
3223       record
3224          Vptr    : System.Address;
3225          O_Value : Integer;
3226          A_Value : Integer;
3227       end record;
3228    pragma Convention (C, A);
3229
3230    procedure Method1 (This : in out A);
3231    pragma Import (C, Method1);
3232
3233    procedure Ada_Method2 (This : in out A; V : Integer);
3234    pragma Export (C, Ada_Method2);
3235
3236 end Simple_Cpp_Interface;
3237 @end smallexample
3238
3239 @node Interfacing with C++ constructors
3240 @subsection Interfacing with C++ constructors
3241 @noindent
3242
3243 In order to interface with C++ constructors GNAT provides the
3244 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3245 gnat_rm, GNAT Reference Manual}, for additional information).
3246 In this section we present some common uses of C++ constructors
3247 in mixed-languages programs in GNAT.
3248
3249 Let us assume that we need to interface with the following
3250 C++ class:
3251
3252 @smallexample
3253 @b{class} Root @{
3254 @b{public}:
3255   int  a_value;
3256   int  b_value;
3257   @b{virtual} int Get_Value ();
3258   Root();              // Default constructor
3259   Root(int v);         // 1st non-default constructor
3260   Root(int v, int w);  // 2nd non-default constructor
3261 @};
3262 @end smallexample
3263
3264 For this purpose we can write the following package spec (further
3265 information on how to build this spec is available in
3266 @ref{Interfacing with C++ at the Class Level} and
3267 @ref{Generating Ada Bindings for C and C++ headers}).
3268
3269 @smallexample @c ada
3270 with Interfaces.C; use Interfaces.C;
3271 package Pkg_Root is
3272   type Root is tagged limited record
3273      A_Value : int;
3274      B_Value : int;
3275   end record;
3276   pragma Import (CPP, Root);
3277
3278   function Get_Value (Obj : Root) return int;
3279   pragma Import (CPP, Get_Value);
3280
3281   function Constructor return Root;
3282   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3283
3284   function Constructor (v : Integer) return Root;
3285   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3286
3287   function Constructor (v, w : Integer) return Root;
3288   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3289 end Pkg_Root;
3290 @end smallexample
3291
3292 On the Ada side the constructor is represented by a function (whose
3293 name is arbitrary) that returns the classwide type corresponding to
3294 the imported C++ class. Although the constructor is described as a
3295 function, it is typically a procedure with an extra implicit argument
3296 (the object being initialized) at the implementation level. GNAT
3297 issues the appropriate call, whatever it is, to get the object
3298 properly initialized.
3299
3300 Constructors can only appear in the following contexts:
3301
3302 @itemize @bullet
3303 @item
3304 On the right side of an initialization of an object of type @var{T}.
3305 @item
3306 On the right side of an initialization of a record component of type @var{T}.
3307 @item
3308 In an Ada 2005 limited aggregate.
3309 @item
3310 In an Ada 2005 nested limited aggregate.
3311 @item
3312 In an Ada 2005 limited aggregate that initializes an object built in
3313 place by an extended return statement.
3314 @end itemize
3315
3316 @noindent
3317 In a declaration of an object whose type is a class imported from C++,
3318 either the default C++ constructor is implicitly called by GNAT, or
3319 else the required C++ constructor must be explicitly called in the
3320 expression that initializes the object. For example:
3321
3322 @smallexample @c ada
3323   Obj1 : Root;
3324   Obj2 : Root := Constructor;
3325   Obj3 : Root := Constructor (v => 10);
3326   Obj4 : Root := Constructor (30, 40);
3327 @end smallexample
3328
3329 The first two declarations are equivalent: in both cases the default C++
3330 constructor is invoked (in the former case the call to the constructor is
3331 implicit, and in the latter case the call is explicit in the object
3332 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3333 that takes an integer argument, and @code{Obj4} is initialized by the
3334 non-default C++ constructor that takes two integers.
3335
3336 Let us derive the imported C++ class in the Ada side. For example:
3337
3338 @smallexample @c ada
3339   type DT is new Root with record
3340      C_Value : Natural := 2009;
3341   end record;
3342 @end smallexample
3343
3344 In this case the components DT inherited from the C++ side must be
3345 initialized by a C++ constructor, and the additional Ada components
3346 of type DT are initialized by GNAT. The initialization of such an
3347 object is done either by default, or by means of a function returning
3348 an aggregate of type DT, or by means of an extension aggregate.
3349
3350 @smallexample @c ada
3351   Obj5 : DT;
3352   Obj6 : DT := Function_Returning_DT (50);
3353   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3354 @end smallexample
3355
3356 The declaration of @code{Obj5} invokes the default constructors: the
3357 C++ default constructor of the parent type takes care of the initialization
3358 of the components inherited from Root, and GNAT takes care of the default
3359 initialization of the additional Ada components of type DT (that is,
3360 @code{C_Value} is initialized to value 2009). The order of invocation of
3361 the constructors is consistent with the order of elaboration required by
3362 Ada and C++. That is, the constructor of the parent type is always called
3363 before the constructor of the derived type.
3364
3365 Let us now consider a record that has components whose type is imported
3366 from C++. For example:
3367
3368 @smallexample @c ada
3369   type Rec1 is limited record
3370      Data1 : Root := Constructor (10);
3371      Value : Natural := 1000;
3372   end record;
3373
3374   type Rec2 (D : Integer := 20) is limited record
3375      Rec   : Rec1;
3376      Data2 : Root := Constructor (D, 30);
3377   end record;
3378 @end smallexample
3379
3380 The initialization of an object of type @code{Rec2} will call the
3381 non-default C++ constructors specified for the imported components.
3382 For example:
3383
3384 @smallexample @c ada
3385   Obj8 : Rec2 (40);
3386 @end smallexample
3387
3388 Using Ada 2005 we can use limited aggregates to initialize an object
3389 invoking C++ constructors that differ from those specified in the type
3390 declarations. For example:
3391
3392 @smallexample @c ada
3393   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3394                           others => <>),
3395                   others => <>);
3396 @end smallexample
3397
3398 The above declaration uses an Ada 2005 limited aggregate to
3399 initialize @code{Obj9}, and the C++ constructor that has two integer
3400 arguments is invoked to initialize the @code{Data1} component instead
3401 of the constructor specified in the declaration of type @code{Rec1}. In
3402 Ada 2005 the box in the aggregate indicates that unspecified components
3403 are initialized using the expression (if any) available in the component
3404 declaration. That is, in this case discriminant @code{D} is initialized
3405 to value @code{20}, @code{Value} is initialized to value 1000, and the
3406 non-default C++ constructor that handles two integers takes care of
3407 initializing component @code{Data2} with values @code{20,30}.
3408
3409 In Ada 2005 we can use the extended return statement to build the Ada
3410 equivalent to C++ non-default constructors. For example:
3411
3412 @smallexample @c ada
3413   function Constructor (V : Integer) return Rec2 is
3414   begin
3415      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3416                                    others => <>),
3417                            others => <>) do
3418         --  Further actions required for construction of
3419         --  objects of type Rec2
3420         ...
3421      end record;
3422   end Constructor;
3423 @end smallexample
3424
3425 In this example the extended return statement construct is used to
3426 build in place the returned object whose components are initialized
3427 by means of a limited aggregate. Any further action associated with
3428 the constructor can be placed inside the construct.
3429
3430 @node Interfacing with C++ at the Class Level
3431 @subsection Interfacing with C++ at the Class Level
3432 @noindent
3433 In this section we demonstrate the GNAT features for interfacing with
3434 C++ by means of an example making use of Ada 2005 abstract interface
3435 types. This example consists of a classification of animals; classes
3436 have been used to model our main classification of animals, and
3437 interfaces provide support for the management of secondary
3438 classifications. We first demonstrate a case in which the types and
3439 constructors are defined on the C++ side and imported from the Ada
3440 side, and latter the reverse case.
3441
3442 The root of our derivation will be the @code{Animal} class, with a
3443 single private attribute (the @code{Age} of the animal) and two public
3444 primitives to set and get the value of this attribute.
3445
3446 @smallexample
3447 @b{class} Animal @{
3448  @b{public}:
3449    @b{virtual} void Set_Age (int New_Age);
3450    @b{virtual} int Age ();
3451  @b{private}:
3452    int Age_Count;
3453 @};
3454 @end smallexample
3455
3456 Abstract interface types are defined in C++ by means of classes with pure
3457 virtual functions and no data members. In our example we will use two
3458 interfaces that provide support for the common management of @code{Carnivore}
3459 and @code{Domestic} animals:
3460
3461 @smallexample
3462 @b{class} Carnivore @{
3463 @b{public}:
3464    @b{virtual} int Number_Of_Teeth () = 0;
3465 @};
3466
3467 @b{class} Domestic @{
3468 @b{public}:
3469    @b{virtual void} Set_Owner (char* Name) = 0;
3470 @};
3471 @end smallexample
3472
3473 Using these declarations, we can now say that a @code{Dog} is an animal that is
3474 both Carnivore and Domestic, that is:
3475
3476 @smallexample
3477 @b{class} Dog : Animal, Carnivore, Domestic @{
3478  @b{public}:
3479    @b{virtual} int  Number_Of_Teeth ();
3480    @b{virtual} void Set_Owner (char* Name);
3481
3482    Dog(); // Constructor
3483  @b{private}:
3484    int  Tooth_Count;
3485    char *Owner;
3486 @};
3487 @end smallexample
3488
3489 In the following examples we will assume that the previous declarations are
3490 located in a file named @code{animals.h}. The following package demonstrates
3491 how to import these C++ declarations from the Ada side:
3492
3493 @smallexample @c ada
3494 with Interfaces.C.Strings; use Interfaces.C.Strings;
3495 package Animals is
3496   type Carnivore is interface;
3497   pragma Convention (C_Plus_Plus, Carnivore);
3498   function Number_Of_Teeth (X : Carnivore)
3499      return Natural is abstract;
3500
3501   type Domestic is interface;
3502   pragma Convention (C_Plus_Plus, Set_Owner);
3503   procedure Set_Owner
3504     (X    : in out Domestic;
3505      Name : Chars_Ptr) is abstract;
3506
3507   type Animal is tagged record
3508     Age : Natural := 0;
3509   end record;
3510   pragma Import (C_Plus_Plus, Animal);
3511
3512   procedure Set_Age (X : in out Animal; Age : Integer);
3513   pragma Import (C_Plus_Plus, Set_Age);
3514
3515   function Age (X : Animal) return Integer;
3516   pragma Import (C_Plus_Plus, Age);
3517
3518   type Dog is new Animal and Carnivore and Domestic with record
3519     Tooth_Count : Natural;
3520     Owner       : String (1 .. 30);
3521   end record;
3522   pragma Import (C_Plus_Plus, Dog);
3523
3524   function Number_Of_Teeth (A : Dog) return Integer;
3525   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3526
3527   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3528   pragma Import (C_Plus_Plus, Set_Owner);
3529
3530   function New_Dog return Dog;
3531   pragma CPP_Constructor (New_Dog);
3532   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3533 end Animals;
3534 @end smallexample
3535
3536 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3537 interfacing with these C++ classes is easy. The only requirement is that all
3538 the primitives and components must be declared exactly in the same order in
3539 the two languages.
3540
3541 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3542 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3543 the arguments to the called primitives will be the same as for C++. For the
3544 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3545 to indicate that they have been defined on the C++ side; this is required
3546 because the dispatch table associated with these tagged types will be built
3547 in the C++ side and therefore will not contain the predefined Ada primitives
3548 which Ada would otherwise expect.
3549
3550 As the reader can see there is no need to indicate the C++ mangled names
3551 associated with each subprogram because it is assumed that all the calls to
3552 these primitives will be dispatching calls. The only exception is the
3553 constructor, which must be registered with the compiler by means of
3554 @code{pragma CPP_Constructor} and needs to provide its associated C++
3555 mangled name because the Ada compiler generates direct calls to it.
3556
3557 With the above packages we can now declare objects of type Dog on the Ada side
3558 and dispatch calls to the corresponding subprograms on the C++ side. We can
3559 also extend the tagged type Dog with further fields and primitives, and
3560 override some of its C++ primitives on the Ada side. For example, here we have
3561 a type derivation defined on the Ada side that inherits all the dispatching
3562 primitives of the ancestor from the C++ side.
3563
3564 @smallexample
3565 @b{with} Animals; @b{use} Animals;
3566 @b{package} Vaccinated_Animals @b{is}
3567   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3568   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3569 @b{end} Vaccinated_Animals;
3570 @end smallexample
3571
3572 It is important to note that, because of the ABI compatibility, the programmer
3573 does not need to add any further information to indicate either the object
3574 layout or the dispatch table entry associated with each dispatching operation.
3575
3576 Now let us define all the types and constructors on the Ada side and export
3577 them to C++, using the same hierarchy of our previous example:
3578
3579 @smallexample @c ada
3580 with Interfaces.C.Strings;
3581 use Interfaces.C.Strings;
3582 package Animals is
3583   type Carnivore is interface;
3584   pragma Convention (C_Plus_Plus, Carnivore);
3585   function Number_Of_Teeth (X : Carnivore)
3586      return Natural is abstract;
3587
3588   type Domestic is interface;
3589   pragma Convention (C_Plus_Plus, Set_Owner);
3590   procedure Set_Owner
3591     (X    : in out Domestic;
3592      Name : Chars_Ptr) is abstract;
3593
3594   type Animal is tagged record
3595     Age : Natural := 0;
3596   end record;
3597   pragma Convention (C_Plus_Plus, Animal);
3598
3599   procedure Set_Age (X : in out Animal; Age : Integer);
3600   pragma Export (C_Plus_Plus, Set_Age);
3601
3602   function Age (X : Animal) return Integer;
3603   pragma Export (C_Plus_Plus, Age);
3604
3605   type Dog is new Animal and Carnivore and Domestic with record
3606     Tooth_Count : Natural;
3607     Owner       : String (1 .. 30);
3608   end record;
3609   pragma Convention (C_Plus_Plus, Dog);
3610
3611   function Number_Of_Teeth (A : Dog) return Integer;
3612   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3613
3614   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3615   pragma Export (C_Plus_Plus, Set_Owner);
3616
3617   function New_Dog return Dog'Class;
3618   pragma Export (C_Plus_Plus, New_Dog);
3619 end Animals;
3620 @end smallexample
3621
3622 Compared with our previous example the only difference is the use of
3623 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3624 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3625 nothing else to be done; as explained above, the only requirement is that all
3626 the primitives and components are declared in exactly the same order.
3627
3628 For completeness, let us see a brief C++ main program that uses the
3629 declarations available in @code{animals.h} (presented in our first example) to
3630 import and use the declarations from the Ada side, properly initializing and
3631 finalizing the Ada run-time system along the way:
3632
3633 @smallexample
3634 @b{#include} "animals.h"
3635 @b{#include} <iostream>
3636 @b{using namespace} std;
3637
3638 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3639 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3640 void Check_Animal (Animal *obj)       @{@dots{}@}
3641 void Check_Dog (Dog *obj)             @{@dots{}@}
3642
3643 @b{extern} "C" @{
3644   void adainit (void);
3645   void adafinal (void);
3646   Dog* new_dog ();
3647 @}
3648
3649 void test ()
3650 @{
3651   Dog *obj = new_dog();  // Ada constructor
3652   Check_Carnivore (obj); // Check secondary DT
3653   Check_Domestic (obj);  // Check secondary DT
3654   Check_Animal (obj);    // Check primary DT
3655   Check_Dog (obj);       // Check primary DT
3656 @}
3657
3658 int main ()
3659 @{
3660   adainit ();  test();  adafinal ();
3661   return 0;
3662 @}
3663 @end smallexample
3664
3665 @node Comparison between GNAT and C/C++ Compilation Models
3666 @section Comparison between GNAT and C/C++ Compilation Models
3667
3668 @noindent
3669 The GNAT model of compilation is close to the C and C++ models. You can
3670 think of Ada specs as corresponding to header files in C. As in C, you
3671 don't need to compile specs; they are compiled when they are used. The
3672 Ada @code{with} is similar in effect to the @code{#include} of a C
3673 header.
3674
3675 One notable difference is that, in Ada, you may compile specs separately
3676 to check them for semantic and syntactic accuracy. This is not always
3677 possible with C headers because they are fragments of programs that have
3678 less specific syntactic or semantic rules.
3679
3680 The other major difference is the requirement for running the binder,
3681 which performs two important functions. First, it checks for
3682 consistency. In C or C++, the only defense against assembling
3683 inconsistent programs lies outside the compiler, in a makefile, for
3684 example. The binder satisfies the Ada requirement that it be impossible
3685 to construct an inconsistent program when the compiler is used in normal
3686 mode.
3687
3688 @cindex Elaboration order control
3689 The other important function of the binder is to deal with elaboration
3690 issues. There are also elaboration issues in C++ that are handled
3691 automatically. This automatic handling has the advantage of being
3692 simpler to use, but the C++ programmer has no control over elaboration.
3693 Where @code{gnatbind} might complain there was no valid order of
3694 elaboration, a C++ compiler would simply construct a program that
3695 malfunctioned at run time.
3696 @end ifclear
3697
3698 @node Comparison between GNAT and Conventional Ada Library Models
3699 @section Comparison between GNAT and Conventional Ada Library Models
3700
3701 @noindent
3702 This section is intended for Ada programmers who have
3703 used an Ada compiler implementing the traditional Ada library
3704 model, as described in the Ada Reference Manual.
3705
3706 @cindex GNAT library
3707 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3708 source files themselves acts as the library. Compiling Ada programs does
3709 not generate any centralized information, but rather an object file and
3710 a ALI file, which are of interest only to the binder and linker.
3711 In a traditional system, the compiler reads information not only from
3712 the source file being compiled, but also from the centralized library.
3713 This means that the effect of a compilation depends on what has been
3714 previously compiled. In particular:
3715
3716 @itemize @bullet
3717 @item
3718 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3719 to the version of the unit most recently compiled into the library.
3720
3721 @item
3722 Inlining is effective only if the necessary body has already been
3723 compiled into the library.
3724
3725 @item
3726 Compiling a unit may obsolete other units in the library.
3727 @end itemize
3728
3729 @noindent
3730 In GNAT, compiling one unit never affects the compilation of any other
3731 units because the compiler reads only source files. Only changes to source
3732 files can affect the results of a compilation. In particular:
3733
3734 @itemize @bullet
3735 @item
3736 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3737 to the source version of the unit that is currently accessible to the
3738 compiler.
3739
3740 @item
3741 @cindex Inlining
3742 Inlining requires the appropriate source files for the package or
3743 subprogram bodies to be available to the compiler. Inlining is always
3744 effective, independent of the order in which units are complied.
3745
3746 @item
3747 Compiling a unit never affects any other compilations. The editing of
3748 sources may cause previous compilations to be out of date if they
3749 depended on the source file being modified.
3750 @end itemize
3751
3752 @noindent
3753 The most important result of these differences is that order of compilation
3754 is never significant in GNAT. There is no situation in which one is
3755 required to do one compilation before another. What shows up as order of
3756 compilation requirements in the traditional Ada library becomes, in
3757 GNAT, simple source dependencies; in other words, there is only a set
3758 of rules saying what source files must be present when a file is
3759 compiled.
3760
3761 @ifset vms
3762 @node Placement of temporary files
3763 @section Placement of temporary files
3764 @cindex Temporary files (user control over placement)
3765
3766 @noindent
3767 GNAT creates temporary files in the directory designated by the environment
3768 variable @env{TMPDIR}.
3769 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3770 for detailed information on how environment variables are resolved.
3771 For most users the easiest way to make use of this feature is to simply
3772 define @env{TMPDIR} as a job level logical name).
3773 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3774 for compiler temporary files, then you can include something like the
3775 following command in your @file{LOGIN.COM} file:
3776
3777 @smallexample
3778 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3779 @end smallexample
3780
3781 @noindent
3782 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3783 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3784 designated by @env{TEMP}.
3785 If none of these environment variables are defined then GNAT uses the
3786 directory designated by the logical name @code{SYS$SCRATCH:}
3787 (by default the user's home directory). If all else fails
3788 GNAT uses the current directory for temporary files.
3789 @end ifset
3790
3791 @c *************************
3792 @node Compiling Using gcc
3793 @chapter Compiling Using @command{gcc}
3794
3795 @noindent
3796 This chapter discusses how to compile Ada programs using the @command{gcc}
3797 command. It also describes the set of switches
3798 that can be used to control the behavior of the compiler.
3799 @menu
3800 * Compiling Programs::
3801 * Switches for gcc::
3802 * Search Paths and the Run-Time Library (RTL)::
3803 * Order of Compilation Issues::
3804 * Examples::
3805 @end menu
3806
3807 @node Compiling Programs
3808 @section Compiling Programs
3809
3810 @noindent
3811 The first step in creating an executable program is to compile the units
3812 of the program using the @command{gcc} command. You must compile the
3813 following files:
3814
3815 @itemize @bullet
3816 @item
3817 the body file (@file{.adb}) for a library level subprogram or generic
3818 subprogram
3819
3820 @item
3821 the spec file (@file{.ads}) for a library level package or generic
3822 package that has no body
3823
3824 @item
3825 the body file (@file{.adb}) for a library level package
3826 or generic package that has a body
3827
3828 @end itemize
3829
3830 @noindent
3831 You need @emph{not} compile the following files
3832
3833 @itemize @bullet
3834
3835 @item
3836 the spec of a library unit which has a body
3837
3838 @item
3839 subunits
3840 @end itemize
3841
3842 @noindent
3843 because they are compiled as part of compiling related units. GNAT
3844 package specs
3845 when the corresponding body is compiled, and subunits when the parent is
3846 compiled.
3847
3848 @cindex cannot generate code
3849 If you attempt to compile any of these files, you will get one of the
3850 following error messages (where @var{fff} is the name of the file you compiled):
3851
3852 @smallexample
3853 cannot generate code for file @var{fff} (package spec)
3854 to check package spec, use -gnatc
3855
3856 cannot generate code for file @var{fff} (missing subunits)
3857 to check parent unit, use -gnatc
3858
3859 cannot generate code for file @var{fff} (subprogram spec)
3860 to check subprogram spec, use -gnatc
3861
3862 cannot generate code for file @var{fff} (subunit)
3863 to check subunit, use -gnatc
3864 @end smallexample
3865
3866 @noindent
3867 As indicated by the above error messages, if you want to submit
3868 one of these files to the compiler to check for correct semantics
3869 without generating code, then use the @option{-gnatc} switch.
3870
3871 The basic command for compiling a file containing an Ada unit is
3872
3873 @smallexample
3874 $ gcc -c @ovar{switches} @file{file name}
3875 @end smallexample
3876
3877 @noindent
3878 where @var{file name} is the name of the Ada file (usually
3879 having an extension
3880 @file{.ads} for a spec or @file{.adb} for a body).
3881 @ifclear vms
3882 You specify the
3883 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3884 @end ifclear
3885 The result of a successful compilation is an object file, which has the
3886 same name as the source file but an extension of @file{.o} and an Ada
3887 Library Information (ALI) file, which also has the same name as the
3888 source file, but with @file{.ali} as the extension. GNAT creates these
3889 two output files in the current directory, but you may specify a source
3890 file in any directory using an absolute or relative path specification
3891 containing the directory information.
3892
3893 @findex gnat1
3894 @command{gcc} is actually a driver program that looks at the extensions of
3895 the file arguments and loads the appropriate compiler. For example, the
3896 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3897 These programs are in directories known to the driver program (in some
3898 configurations via environment variables you set), but need not be in
3899 your path. The @command{gcc} driver also calls the assembler and any other
3900 utilities needed to complete the generation of the required object
3901 files.
3902
3903 It is possible to supply several file names on the same @command{gcc}
3904 command. This causes @command{gcc} to call the appropriate compiler for
3905 each file. For example, the following command lists three separate
3906 files to be compiled:
3907
3908 @smallexample
3909 $ gcc -c x.adb y.adb z.c
3910 @end smallexample
3911
3912 @noindent
3913 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3914 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3915 The compiler generates three object files @file{x.o}, @file{y.o} and
3916 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3917 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3918 @ifclear vms
3919 except for
3920 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3921 @end ifclear
3922
3923 @node Switches for gcc
3924 @section Switches for @command{gcc}
3925
3926 @noindent
3927 The @command{gcc} command accepts switches that control the
3928 compilation process. These switches are fully described in this section.
3929 First we briefly list all the switches, in alphabetical order, then we
3930 describe the switches in more detail in functionally grouped sections.
3931
3932 More switches exist for GCC than those documented here, especially
3933 for specific targets. However, their use is not recommended as
3934 they may change code generation in ways that are incompatible with
3935 the Ada run-time library, or can cause inconsistencies between
3936 compilation units.
3937
3938 @menu
3939 * Output and Error Message Control::
3940 * Warning Message Control::
3941 * Debugging and Assertion Control::
3942 * Validity Checking::
3943 * Style Checking::
3944 * Run-Time Checks::
3945 * Using gcc for Syntax Checking::
3946 * Using gcc for Semantic Checking::
3947 * Compiling Different Versions of Ada::
3948 * Character Set Control::
3949 * File Naming Control::
3950 * Subprogram Inlining Control::
3951 * Auxiliary Output Control::
3952 * Debugging Control::
3953 * Exception Handling Control::
3954 * Units to Sources Mapping Files::
3955 * Integrated Preprocessing::
3956 * Code Generation Control::
3957 @ifset vms
3958 * Return Codes::
3959 @end ifset
3960 @end menu
3961
3962 @table @option
3963 @c !sort!
3964 @ifclear vms
3965 @cindex @option{-b} (@command{gcc})
3966 @item -b @var{target}
3967 Compile your program to run on @var{target}, which is the name of a
3968 system configuration. You must have a GNAT cross-compiler built if
3969 @var{target} is not the same as your host system.
3970
3971 @item -B@var{dir}
3972 @cindex @option{-B} (@command{gcc})
3973 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3974 from @var{dir} instead of the default location. Only use this switch
3975 when multiple versions of the GNAT compiler are available.
3976 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3977 GNU Compiler Collection (GCC)}, for further details. You would normally
3978 use the @option{-b} or @option{-V} switch instead.
3979
3980 @item -c
3981 @cindex @option{-c} (@command{gcc})
3982 Compile. Always use this switch when compiling Ada programs.
3983
3984 Note: for some other languages when using @command{gcc}, notably in
3985 the case of C and C++, it is possible to use
3986 use @command{gcc} without a @option{-c} switch to
3987 compile and link in one step. In the case of GNAT, you
3988 cannot use this approach, because the binder must be run
3989 and @command{gcc} cannot be used to run the GNAT binder.
3990 @end ifclear
3991
3992 @item -fno-inline
3993 @cindex @option{-fno-inline} (@command{gcc})
3994 Suppresses all back-end inlining, even if other optimization or inlining
3995 switches are set.
3996 This includes suppression of inlining that results
3997 from the use of the pragma @code{Inline_Always}.
3998 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3999 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4000 effect if this switch is present.
4001
4002 @item -fno-inline-functions
4003 @cindex @option{-fno-inline-functions} (@command{gcc})
4004 Suppresses automatic inlining of simple subprograms, which is enabled
4005 if @option{-O3} is used.
4006
4007 @item -fno-inline-small-functions
4008 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4009 Suppresses automatic inlining of small subprograms, which is enabled
4010 if @option{-O2} is used.
4011
4012 @item -fno-inline-functions-called-once
4013 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4014 Suppresses inlining of subprograms local to the unit and called once
4015 from within it, which is enabled if @option{-O1} is used.
4016
4017 @item -fno-ivopts
4018 @cindex @option{-fno-ivopts} (@command{gcc})
4019 Suppresses high-level loop induction variable optimizations, which are
4020 enabled if @option{-O1} is used. These optimizations are generally
4021 profitable but, for some specific cases of loops with numerous uses
4022 of the iteration variable that follow a common pattern, they may end
4023 up destroying the regularity that could be exploited at a lower level
4024 and thus producing inferior code.
4025
4026 @item -fno-strict-aliasing
4027 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4028 Causes the compiler to avoid assumptions regarding non-aliasing
4029 of objects of different types. See
4030 @ref{Optimization and Strict Aliasing} for details.
4031
4032 @item -fstack-check
4033 @cindex @option{-fstack-check} (@command{gcc})
4034 Activates stack checking.
4035 See @ref{Stack Overflow Checking} for details.
4036
4037 @item -fstack-usage
4038 @cindex @option{-fstack-usage} (@command{gcc})
4039 Makes the compiler output stack usage information for the program, on a
4040 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4041
4042 @item -fcallgraph-info@r{[}=su@r{]}
4043 @cindex @option{-fcallgraph-info} (@command{gcc})
4044 Makes the compiler output callgraph information for the program, on a
4045 per-file basis.  The information is generated in the VCG format.  It can
4046 be decorated with stack-usage per-node information.
4047
4048 @item ^-g^/DEBUG^
4049 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4050 Generate debugging information. This information is stored in the object
4051 file and copied from there to the final executable file by the linker,
4052 where it can be read by the debugger. You must use the
4053 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4054
4055 @item -gnat83
4056 @cindex @option{-gnat83} (@command{gcc})
4057 Enforce Ada 83 restrictions.
4058
4059 @item -gnat95
4060 @cindex @option{-gnat95} (@command{gcc})
4061 Enforce Ada 95 restrictions.
4062
4063 @item -gnat05
4064 @cindex @option{-gnat05} (@command{gcc})
4065 Allow full Ada 2005 features.
4066
4067 @item -gnata
4068 @cindex @option{-gnata} (@command{gcc})
4069 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4070 activated. Note that these pragmas can also be controlled using the
4071 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4072 It also activates pragmas @code{Check}, @code{Precondition}, and
4073 @code{Postcondition}. Note that these pragmas can also be controlled
4074 using the configuration pragma @code{Check_Policy}.
4075
4076 @item -gnatA
4077 @cindex @option{-gnatA} (@command{gcc})
4078 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4079 it will be ignored.
4080
4081 @item -gnatb
4082 @cindex @option{-gnatb} (@command{gcc})
4083 Generate brief messages to @file{stderr} even if verbose mode set.
4084
4085 @item -gnatB
4086 @cindex @option{-gnatB} (@command{gcc})
4087 Assume no invalid (bad) values except for 'Valid attribute use.
4088
4089 @item -gnatc
4090 @cindex @option{-gnatc} (@command{gcc})
4091 Check syntax and semantics only (no code generation attempted).
4092
4093 @item -gnatd
4094 @cindex @option{-gnatd} (@command{gcc})
4095 Specify debug options for the compiler. The string of characters after
4096 the @option{-gnatd} specify the specific debug options. The possible
4097 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4098 compiler source file @file{debug.adb} for details of the implemented
4099 debug options. Certain debug options are relevant to applications
4100 programmers, and these are documented at appropriate points in this
4101 users guide.
4102
4103 @ifclear vms
4104 @item -gnatD
4105 @cindex @option{-gnatD[nn]} (@command{gcc})
4106 @end ifclear
4107 @ifset vms
4108 @item /XDEBUG /LXDEBUG=nnn
4109 @end ifset
4110 Create expanded source files for source level debugging. This switch
4111 also suppress generation of cross-reference information
4112 (see @option{-gnatx}).
4113
4114 @item -gnatec=@var{path}
4115 @cindex @option{-gnatec} (@command{gcc})
4116 Specify a configuration pragma file
4117 @ifclear vms
4118 (the equal sign is optional)
4119 @end ifclear
4120 (@pxref{The Configuration Pragmas Files}).
4121
4122 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4123 @cindex @option{-gnateD} (@command{gcc})
4124 Defines a symbol, associated with @var{value}, for preprocessing.
4125 (@pxref{Integrated Preprocessing}).
4126
4127 @item -gnatef
4128 @cindex @option{-gnatef} (@command{gcc})
4129 Display full source path name in brief error messages.
4130
4131 @item -gnateG
4132 @cindex @option{-gnateG} (@command{gcc})
4133 Save result of preprocessing in a text file.
4134
4135 @item -gnatem=@var{path}
4136 @cindex @option{-gnatem} (@command{gcc})
4137 Specify a mapping file
4138 @ifclear vms
4139 (the equal sign is optional)
4140 @end ifclear
4141 (@pxref{Units to Sources Mapping Files}).
4142
4143 @item -gnatep=@var{file}
4144 @cindex @option{-gnatep} (@command{gcc})
4145 Specify a preprocessing data file
4146 @ifclear vms
4147 (the equal sign is optional)
4148 @end ifclear
4149 (@pxref{Integrated Preprocessing}).
4150
4151 @item -gnatE
4152 @cindex @option{-gnatE} (@command{gcc})
4153 Full dynamic elaboration checks.
4154
4155 @item -gnatf
4156 @cindex @option{-gnatf} (@command{gcc})
4157 Full errors. Multiple errors per line, all undefined references, do not
4158 attempt to suppress cascaded errors.
4159
4160 @item -gnatF
4161 @cindex @option{-gnatF} (@command{gcc})
4162 Externals names are folded to all uppercase.
4163
4164 @item ^-gnatg^/GNAT_INTERNAL^
4165 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4166 Internal GNAT implementation mode. This should not be used for
4167 applications programs, it is intended only for use by the compiler
4168 and its run-time library. For documentation, see the GNAT sources.
4169 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4170 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4171 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4172 so that all standard warnings and all standard style options are turned on.
4173 All warnings and style error messages are treated as errors.
4174
4175 @ifclear vms
4176 @item -gnatG=nn
4177 @cindex @option{-gnatG[nn]} (@command{gcc})
4178 @end ifclear
4179 @ifset vms
4180 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4181 @end ifset
4182 List generated expanded code in source form.
4183
4184 @item ^-gnath^/HELP^
4185 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4186 Output usage information. The output is written to @file{stdout}.
4187
4188 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4189 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4190 Identifier character set
4191 @ifclear vms
4192 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4193 @end ifclear
4194 For details of the possible selections for @var{c},
4195 see @ref{Character Set Control}.
4196
4197 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4198 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4199 Ignore representation clauses. When this switch is used,
4200 representation clauses are treated as comments. This is useful
4201 when initially porting code where you want to ignore rep clause
4202 problems, and also for compiling foreign code (particularly
4203 for use with ASIS). The representation clauses that are ignored
4204 are: enumeration_representation_clause, record_representation_clause,
4205 and attribute_definition_clause for the following attributes:
4206 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4207 Object_Size, Size, Small, Stream_Size, and Value_Size.
4208 Note that this option should be used only for compiling -- the
4209 code is likely to malfunction at run time.
4210
4211 @item -gnatjnn
4212 @cindex @option{-gnatjnn} (@command{gcc})
4213 Reformat error messages to fit on nn character lines
4214
4215 @item -gnatk=@var{n}
4216 @cindex @option{-gnatk} (@command{gcc})
4217 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4218
4219 @item -gnatl
4220 @cindex @option{-gnatl} (@command{gcc})
4221 Output full source listing with embedded error messages.
4222
4223 @item -gnatL
4224 @cindex @option{-gnatL} (@command{gcc})
4225 Used in conjunction with -gnatG or -gnatD to intersperse original
4226 source lines (as comment lines with line numbers) in the expanded
4227 source output.
4228
4229 @item -gnatm=@var{n}
4230 @cindex @option{-gnatm} (@command{gcc})
4231 Limit number of detected error or warning messages to @var{n}
4232 where @var{n} is in the range 1..999999. The default setting if
4233 no switch is given is 9999. If the number of warnings reaches this
4234 limit, then a message is output and further warnings are suppressed,
4235 but the compilation is continued. If the number of error messages
4236 reaches this limit, then a message is output and the compilation
4237 is abandoned. The equal sign here is optional. A value of zero
4238 means that no limit applies.
4239
4240 @item -gnatn
4241 @cindex @option{-gnatn} (@command{gcc})
4242 Activate inlining for subprograms for which
4243 pragma @code{inline} is specified. This inlining is performed
4244 by the GCC back-end.
4245
4246 @item -gnatN
4247 @cindex @option{-gnatN} (@command{gcc})
4248 Activate front end inlining for subprograms for which
4249 pragma @code{Inline} is specified. This inlining is performed
4250 by the front end and will be visible in the
4251 @option{-gnatG} output.
4252
4253 When using a gcc-based back end (in practice this means using any version
4254 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4255 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4256 Historically front end inlining was more extensive than the gcc back end
4257 inlining, but that is no longer the case.
4258
4259 @item -gnato
4260 @cindex @option{-gnato} (@command{gcc})
4261 Enable numeric overflow checking (which is not normally enabled by
4262 default). Note that division by zero is a separate check that is not
4263 controlled by this switch (division by zero checking is on by default).
4264
4265 @item -gnatp
4266 @cindex @option{-gnatp} (@command{gcc})
4267 Suppress all checks. See @ref{Run-Time Checks} for details.
4268
4269 @item -gnatP
4270 @cindex @option{-gnatP} (@command{gcc})
4271 Enable polling. This is required on some systems (notably Windows NT) to
4272 obtain asynchronous abort and asynchronous transfer of control capability.
4273 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4274 details.
4275
4276 @item -gnatq
4277 @cindex @option{-gnatq} (@command{gcc})
4278 Don't quit. Try semantics, even if parse errors.
4279
4280 @item -gnatQ
4281 @cindex @option{-gnatQ} (@command{gcc})
4282 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4283
4284 @item -gnatr
4285 @cindex @option{-gnatr} (@command{gcc})
4286 Treat pragma Restrictions as Restriction_Warnings.
4287
4288 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4289 @cindex @option{-gnatR} (@command{gcc})
4290 Output representation information for declared types and objects.
4291
4292 @item -gnats
4293 @cindex @option{-gnats} (@command{gcc})
4294 Syntax check only.
4295
4296 @item -gnatS
4297 @cindex @option{-gnatS} (@command{gcc})
4298 Print package Standard.
4299
4300 @item -gnatt
4301 @cindex @option{-gnatt} (@command{gcc})
4302 Generate tree output file.
4303
4304 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4305 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4306 All compiler tables start at @var{nnn} times usual starting size.
4307
4308 @item -gnatu
4309 @cindex @option{-gnatu} (@command{gcc})
4310 List units for this compilation.
4311
4312 @item -gnatU
4313 @cindex @option{-gnatU} (@command{gcc})
4314 Tag all error messages with the unique string ``error:''
4315
4316 @item -gnatv
4317 @cindex @option{-gnatv} (@command{gcc})
4318 Verbose mode. Full error output with source lines to @file{stdout}.
4319
4320 @item -gnatV
4321 @cindex @option{-gnatV} (@command{gcc})
4322 Control level of validity checking. See separate section describing
4323 this feature.
4324
4325 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4326 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4327 Warning mode where
4328 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4329 the exact warnings that
4330 are enabled or disabled (@pxref{Warning Message Control}).
4331
4332 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4333 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4334 Wide character encoding method
4335 @ifclear vms
4336 (@var{e}=n/h/u/s/e/8).
4337 @end ifclear
4338 @ifset vms
4339 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4340 @end ifset
4341
4342 @item -gnatx
4343 @cindex @option{-gnatx} (@command{gcc})
4344 Suppress generation of cross-reference information.
4345
4346 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4347 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4348 Enable built-in style checks (@pxref{Style Checking}).
4349
4350 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4351 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4352 Distribution stub generation and compilation
4353 @ifclear vms
4354 (@var{m}=r/c for receiver/caller stubs).
4355 @end ifclear
4356 @ifset vms
4357 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4358 to be generated and compiled).
4359 @end ifset
4360
4361 @item ^-I^/SEARCH=^@var{dir}
4362 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4363 @cindex RTL
4364 Direct GNAT to search the @var{dir} directory for source files needed by
4365 the current compilation
4366 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4367
4368 @item ^-I-^/NOCURRENT_DIRECTORY^
4369 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4370 @cindex RTL
4371 Except for the source file named in the command line, do not look for source
4372 files in the directory containing the source file named in the command line
4373 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4374
4375 @ifclear vms
4376 @item -mbig-switch
4377 @cindex @option{-mbig-switch} (@command{gcc})
4378 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4379 This standard gcc switch causes the compiler to use larger offsets in its
4380 jump table representation for @code{case} statements.
4381 This may result in less efficient code, but is sometimes necessary
4382 (for example on HP-UX targets)
4383 @cindex HP-UX and @option{-mbig-switch} option
4384 in order to compile large and/or nested @code{case} statements.
4385
4386 @item -o @var{file}
4387 @cindex @option{-o} (@command{gcc})
4388 This switch is used in @command{gcc} to redirect the generated object file
4389 and its associated ALI file. Beware of this switch with GNAT, because it may
4390 cause the object file and ALI file to have different names which in turn
4391 may confuse the binder and the linker.
4392 @end ifclear
4393
4394 @item -nostdinc
4395 @cindex @option{-nostdinc} (@command{gcc})
4396 Inhibit the search of the default location for the GNAT Run Time
4397 Library (RTL) source files.
4398
4399 @item -nostdlib
4400 @cindex @option{-nostdlib} (@command{gcc})
4401 Inhibit the search of the default location for the GNAT Run Time
4402 Library (RTL) ALI files.
4403
4404 @ifclear vms
4405 @item -O@ovar{n}
4406 @cindex @option{-O} (@command{gcc})
4407 @var{n} controls the optimization level.
4408
4409 @table @asis
4410 @item n = 0
4411 No optimization, the default setting if no @option{-O} appears
4412
4413 @item n = 1
4414 Normal optimization, the default if you specify @option{-O} without
4415 an operand. A good compromise between code quality and compilation
4416 time.
4417
4418 @item n = 2
4419 Extensive optimization, may improve execution time, possibly at the cost of
4420 substantially increased compilation time.
4421
4422 @item n = 3
4423 Same as @option{-O2}, and also includes inline expansion for small subprograms
4424 in the same unit.
4425
4426 @item n = s
4427 Optimize space usage
4428 @end table
4429
4430 @noindent
4431 See also @ref{Optimization Levels}.
4432 @end ifclear
4433
4434 @ifset vms
4435 @item  /NOOPTIMIZE
4436 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4437 Equivalent to @option{/OPTIMIZE=NONE}.
4438 This is the default behavior in the absence of an @option{/OPTIMIZE}
4439 qualifier.
4440
4441 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4442 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4443 Selects the level of optimization for your program. The supported
4444 keywords are as follows:
4445 @table @code
4446 @item   ALL
4447 Perform most optimizations, including those that
4448 are expensive.
4449 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4450 without keyword options.
4451
4452 @item   NONE
4453 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4454
4455 @item SOME
4456 Perform some optimizations, but omit ones that are costly.
4457
4458 @item   DEVELOPMENT
4459 Same as @code{SOME}.
4460
4461 @item INLINING
4462 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4463 automatic inlining of small subprograms within a unit
4464
4465 @item   UNROLL_LOOPS
4466 Try to unroll loops. This keyword may be specified together with
4467 any keyword above other than @code{NONE}. Loop unrolling
4468 usually, but not always, improves the performance of programs.
4469
4470 @item SPACE
4471 Optimize space usage
4472 @end table
4473
4474 @noindent
4475 See also @ref{Optimization Levels}.
4476 @end ifset
4477
4478 @ifclear vms
4479 @item -pass-exit-codes
4480 @cindex @option{-pass-exit-codes} (@command{gcc})
4481 Catch exit codes from the compiler and use the most meaningful as
4482 exit status.
4483 @end ifclear
4484
4485 @item --RTS=@var{rts-path}
4486 @cindex @option{--RTS} (@command{gcc})
4487 Specifies the default location of the runtime library. Same meaning as the
4488 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4489
4490 @item ^-S^/ASM^
4491 @cindex @option{^-S^/ASM^} (@command{gcc})
4492 ^Used in place of @option{-c} to^Used to^
4493 cause the assembler source file to be
4494 generated, using @file{^.s^.S^} as the extension,
4495 instead of the object file.
4496 This may be useful if you need to examine the generated assembly code.
4497
4498 @item ^-fverbose-asm^/VERBOSE_ASM^
4499 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4500 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4501 to cause the generated assembly code file to be annotated with variable
4502 names, making it significantly easier to follow.
4503
4504 @item ^-v^/VERBOSE^
4505 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4506 Show commands generated by the @command{gcc} driver. Normally used only for
4507 debugging purposes or if you need to be sure what version of the
4508 compiler you are executing.
4509
4510 @ifclear vms
4511 @item -V @var{ver}
4512 @cindex @option{-V} (@command{gcc})
4513 Execute @var{ver} version of the compiler. This is the @command{gcc}
4514 version, not the GNAT version.
4515 @end ifclear
4516
4517 @item ^-w^/NO_BACK_END_WARNINGS^
4518 @cindex @option{-w} (@command{gcc})
4519 Turn off warnings generated by the back end of the compiler. Use of
4520 this switch also causes the default for front end warnings to be set
4521 to suppress (as though @option{-gnatws} had appeared at the start of
4522 the options).
4523
4524 @end table
4525
4526 @ifclear vms
4527 @c Combining qualifiers does not work on VMS
4528 You may combine a sequence of GNAT switches into a single switch. For
4529 example, the combined switch
4530
4531 @cindex Combining GNAT switches
4532 @smallexample
4533 -gnatofi3
4534 @end smallexample
4535
4536 @noindent
4537 is equivalent to specifying the following sequence of switches:
4538
4539 @smallexample
4540 -gnato -gnatf -gnati3
4541 @end smallexample
4542 @end ifclear
4543
4544 @noindent
4545 The following restrictions apply to the combination of switches
4546 in this manner:
4547
4548 @itemize @bullet
4549 @item
4550 The switch @option{-gnatc} if combined with other switches must come
4551 first in the string.
4552
4553 @item
4554 The switch @option{-gnats} if combined with other switches must come
4555 first in the string.
4556
4557 @item
4558 The switches
4559 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4560 may not be combined with any other switches.
4561
4562 @ifclear vms
4563 @item
4564 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4565 switch), then all further characters in the switch are interpreted
4566 as style modifiers (see description of @option{-gnaty}).
4567
4568 @item
4569 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4570 switch), then all further characters in the switch are interpreted
4571 as debug flags (see description of @option{-gnatd}).
4572
4573 @item
4574 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4575 switch), then all further characters in the switch are interpreted
4576 as warning mode modifiers (see description of @option{-gnatw}).
4577
4578 @item
4579 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4580 switch), then all further characters in the switch are interpreted
4581 as validity checking options (see description of @option{-gnatV}).
4582 @end ifclear
4583 @end itemize
4584
4585 @node Output and Error Message Control
4586 @subsection Output and Error Message Control
4587 @findex stderr
4588
4589 @noindent
4590 The standard default format for error messages is called ``brief format''.
4591 Brief format messages are written to @file{stderr} (the standard error
4592 file) and have the following form:
4593
4594 @smallexample
4595 e.adb:3:04: Incorrect spelling of keyword "function"
4596 e.adb:4:20: ";" should be "is"
4597 @end smallexample
4598
4599 @noindent
4600 The first integer after the file name is the line number in the file,
4601 and the second integer is the column number within the line.
4602 @ifclear vms
4603 @code{GPS} can parse the error messages
4604 and point to the referenced character.
4605 @end ifclear
4606 The following switches provide control over the error message
4607 format:
4608
4609 @table @option
4610 @c !sort!
4611 @item -gnatv
4612 @cindex @option{-gnatv} (@command{gcc})
4613 @findex stdout
4614 @ifclear vms
4615 The v stands for verbose.
4616 @end ifclear
4617 The effect of this setting is to write long-format error
4618 messages to @file{stdout} (the standard output file.
4619 The same program compiled with the
4620 @option{-gnatv} switch would generate:
4621
4622 @smallexample
4623 @cartouche
4624 3. funcion X (Q : Integer)
4625    |
4626 >>> Incorrect spelling of keyword "function"
4627 4. return Integer;
4628                  |
4629 >>> ";" should be "is"
4630 @end cartouche
4631 @end smallexample
4632
4633 @noindent
4634 The vertical bar indicates the location of the error, and the @samp{>>>}
4635 prefix can be used to search for error messages. When this switch is
4636 used the only source lines output are those with errors.
4637
4638 @item -gnatl
4639 @cindex @option{-gnatl} (@command{gcc})
4640 @ifclear vms
4641 The @code{l} stands for list.
4642 @end ifclear
4643 This switch causes a full listing of
4644 the file to be generated. In the case where a body is
4645 compiled, the corresponding spec is also listed, along
4646 with any subunits. Typical output from compiling a package
4647 body @file{p.adb} might look like:
4648
4649 @smallexample @c ada
4650 @cartouche
4651  Compiling: p.adb
4652
4653      1. package body p is
4654      2.    procedure a;
4655      3.    procedure a is separate;
4656      4. begin
4657      5.    null
4658                |
4659         >>> missing ";"
4660
4661      6. end;
4662
4663 Compiling: p.ads
4664
4665      1. package p is
4666      2.    pragma Elaborate_Body
4667                                 |
4668         >>> missing ";"
4669
4670      3. end p;
4671
4672 Compiling: p-a.adb
4673
4674      1. separate p
4675                 |
4676         >>> missing "("
4677
4678      2. procedure a is
4679      3. begin
4680      4.    null
4681                |
4682         >>> missing ";"
4683
4684      5. end;
4685 @end cartouche
4686 @end smallexample
4687
4688 @noindent
4689 @findex stderr
4690 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4691 standard output is redirected, a brief summary is written to
4692 @file{stderr} (standard error) giving the number of error messages and
4693 warning messages generated.
4694
4695 @item -^gnatl^OUTPUT_FILE^=file
4696 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4697 This has the same effect as @option{-gnatl} except that the output is
4698 written to a file instead of to standard output. If the given name
4699 @file{fname} does not start with a period, then it is the full name
4700 of the file to be written. If @file{fname} is an extension, it is
4701 appended to the name of the file being compiled. For example, if
4702 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4703 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4704
4705 @item -gnatU
4706 @cindex @option{-gnatU} (@command{gcc})
4707 This switch forces all error messages to be preceded by the unique
4708 string ``error:''. This means that error messages take a few more
4709 characters in space, but allows easy searching for and identification
4710 of error messages.
4711
4712 @item -gnatb
4713 @cindex @option{-gnatb} (@command{gcc})
4714 @ifclear vms
4715 The @code{b} stands for brief.
4716 @end ifclear
4717 This switch causes GNAT to generate the
4718 brief format error messages to @file{stderr} (the standard error
4719 file) as well as the verbose
4720 format message or full listing (which as usual is written to
4721 @file{stdout} (the standard output file).
4722
4723 @item -gnatm=@var{n}
4724 @cindex @option{-gnatm} (@command{gcc})
4725 @ifclear vms
4726 The @code{m} stands for maximum.
4727 @end ifclear
4728 @var{n} is a decimal integer in the
4729 range of 1 to 999999 and limits the number of error or warning
4730 messages to be generated. For example, using
4731 @option{-gnatm2} might yield
4732
4733 @smallexample
4734 e.adb:3:04: Incorrect spelling of keyword "function"
4735 e.adb:5:35: missing ".."
4736 fatal error: maximum number of errors detected
4737 compilation abandoned
4738 @end smallexample
4739
4740 @noindent
4741 The default setting if
4742 no switch is given is 9999. If the number of warnings reaches this
4743 limit, then a message is output and further warnings are suppressed,
4744 but the compilation is continued. If the number of error messages
4745 reaches this limit, then a message is output and the compilation
4746 is abandoned. A value of zero means that no limit applies.
4747
4748 @noindent
4749 Note that the equal sign is optional, so the switches
4750 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4751
4752 @item -gnatf
4753 @cindex @option{-gnatf} (@command{gcc})
4754 @cindex Error messages, suppressing
4755 @ifclear vms
4756 The @code{f} stands for full.
4757 @end ifclear
4758 Normally, the compiler suppresses error messages that are likely to be
4759 redundant. This switch causes all error
4760 messages to be generated. In particular, in the case of
4761 references to undefined variables. If a given variable is referenced
4762 several times, the normal format of messages is
4763 @smallexample
4764 e.adb:7:07: "V" is undefined (more references follow)
4765 @end smallexample
4766
4767 @noindent
4768 where the parenthetical comment warns that there are additional
4769 references to the variable @code{V}. Compiling the same program with the
4770 @option{-gnatf} switch yields
4771
4772 @smallexample
4773 e.adb:7:07: "V" is undefined
4774 e.adb:8:07: "V" is undefined
4775 e.adb:8:12: "V" is undefined
4776 e.adb:8:16: "V" is undefined
4777 e.adb:9:07: "V" is undefined
4778 e.adb:9:12: "V" is undefined
4779 @end smallexample
4780
4781 @noindent
4782 The @option{-gnatf} switch also generates additional information for
4783 some error messages.  Some examples are:
4784
4785 @itemize @bullet
4786 @item
4787 Details on possibly non-portable unchecked conversion
4788 @item
4789 List possible interpretations for ambiguous calls
4790 @item
4791 Additional details on incorrect parameters
4792 @end itemize
4793
4794 @item -gnatjnn
4795 @cindex @option{-gnatjnn} (@command{gcc})
4796 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4797 with continuation lines are treated as though the continuation lines were
4798 separate messages (and so a warning with two continuation lines counts as
4799 three warnings, and is listed as three separate messages).
4800
4801 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4802 messages are output in a different manner. A message and all its continuation
4803 lines are treated as a unit, and count as only one warning or message in the
4804 statistics totals. Furthermore, the message is reformatted so that no line
4805 is longer than nn characters.
4806
4807 @item -gnatq
4808 @cindex @option{-gnatq} (@command{gcc})
4809 @ifclear vms
4810 The @code{q} stands for quit (really ``don't quit'').
4811 @end ifclear
4812 In normal operation mode, the compiler first parses the program and
4813 determines if there are any syntax errors. If there are, appropriate
4814 error messages are generated and compilation is immediately terminated.
4815 This switch tells
4816 GNAT to continue with semantic analysis even if syntax errors have been
4817 found. This may enable the detection of more errors in a single run. On
4818 the other hand, the semantic analyzer is more likely to encounter some
4819 internal fatal error when given a syntactically invalid tree.
4820
4821 @item -gnatQ
4822 @cindex @option{-gnatQ} (@command{gcc})
4823 In normal operation mode, the @file{ALI} file is not generated if any
4824 illegalities are detected in the program. The use of @option{-gnatQ} forces
4825 generation of the @file{ALI} file. This file is marked as being in
4826 error, so it cannot be used for binding purposes, but it does contain
4827 reasonably complete cross-reference information, and thus may be useful
4828 for use by tools (e.g., semantic browsing tools or integrated development
4829 environments) that are driven from the @file{ALI} file. This switch
4830 implies @option{-gnatq}, since the semantic phase must be run to get a
4831 meaningful ALI file.
4832
4833 In addition, if @option{-gnatt} is also specified, then the tree file is
4834 generated even if there are illegalities. It may be useful in this case
4835 to also specify @option{-gnatq} to ensure that full semantic processing
4836 occurs. The resulting tree file can be processed by ASIS, for the purpose
4837 of providing partial information about illegal units, but if the error
4838 causes the tree to be badly malformed, then ASIS may crash during the
4839 analysis.
4840
4841 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4842 being in error, @command{gnatmake} will attempt to recompile the source when it
4843 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4844
4845 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4846 since ALI files are never generated if @option{-gnats} is set.
4847
4848 @end table
4849
4850 @node Warning Message Control
4851 @subsection Warning Message Control
4852 @cindex Warning messages
4853 @noindent
4854 In addition to error messages, which correspond to illegalities as defined
4855 in the Ada Reference Manual, the compiler detects two kinds of warning
4856 situations.
4857
4858 First, the compiler considers some constructs suspicious and generates a
4859 warning message to alert you to a possible error. Second, if the
4860 compiler detects a situation that is sure to raise an exception at
4861 run time, it generates a warning message. The following shows an example
4862 of warning messages:
4863 @smallexample
4864 e.adb:4:24: warning: creation of object may raise Storage_Error
4865 e.adb:10:17: warning: static value out of range
4866 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4867 @end smallexample
4868
4869 @noindent
4870 GNAT considers a large number of situations as appropriate
4871 for the generation of warning messages. As always, warnings are not
4872 definite indications of errors. For example, if you do an out-of-range
4873 assignment with the deliberate intention of raising a
4874 @code{Constraint_Error} exception, then the warning that may be
4875 issued does not indicate an error. Some of the situations for which GNAT
4876 issues warnings (at least some of the time) are given in the following
4877 list. This list is not complete, and new warnings are often added to
4878 subsequent versions of GNAT. The list is intended to give a general idea
4879 of the kinds of warnings that are generated.
4880
4881 @itemize @bullet
4882 @item
4883 Possible infinitely recursive calls
4884
4885 @item
4886 Out-of-range values being assigned
4887
4888 @item
4889 Possible order of elaboration problems
4890
4891 @item
4892 Assertions (pragma Assert) that are sure to fail
4893
4894 @item
4895 Unreachable code
4896
4897 @item
4898 Address clauses with possibly unaligned values, or where an attempt is
4899 made to overlay a smaller variable with a larger one.
4900
4901 @item
4902 Fixed-point type declarations with a null range
4903
4904 @item
4905 Direct_IO or Sequential_IO instantiated with a type that has access values
4906
4907 @item
4908 Variables that are never assigned a value
4909
4910 @item
4911 Variables that are referenced before being initialized
4912
4913 @item
4914 Task entries with no corresponding @code{accept} statement
4915
4916 @item
4917 Duplicate accepts for the same task entry in a @code{select}
4918
4919 @item
4920 Objects that take too much storage
4921
4922 @item
4923 Unchecked conversion between types of differing sizes
4924
4925 @item
4926 Missing @code{return} statement along some execution path in a function
4927
4928 @item
4929 Incorrect (unrecognized) pragmas
4930
4931 @item
4932 Incorrect external names
4933
4934 @item
4935 Allocation from empty storage pool
4936
4937 @item
4938 Potentially blocking operation in protected type
4939
4940 @item
4941 Suspicious parenthesization of expressions
4942
4943 @item
4944 Mismatching bounds in an aggregate
4945
4946 @item
4947 Attempt to return local value by reference
4948
4949 @item
4950 Premature instantiation of a generic body
4951
4952 @item
4953 Attempt to pack aliased components
4954
4955 @item
4956 Out of bounds array subscripts
4957
4958 @item
4959 Wrong length on string assignment
4960
4961 @item
4962 Violations of style rules if style checking is enabled
4963
4964 @item
4965 Unused @code{with} clauses
4966
4967 @item
4968 @code{Bit_Order} usage that does not have any effect
4969
4970 @item
4971 @code{Standard.Duration} used to resolve universal fixed expression
4972
4973 @item
4974 Dereference of possibly null value
4975
4976 @item
4977 Declaration that is likely to cause storage error
4978
4979 @item
4980 Internal GNAT unit @code{with}'ed by application unit
4981
4982 @item
4983 Values known to be out of range at compile time
4984
4985 @item
4986 Unreferenced labels and variables
4987
4988 @item
4989 Address overlays that could clobber memory
4990
4991 @item
4992 Unexpected initialization when address clause present
4993
4994 @item
4995 Bad alignment for address clause
4996
4997 @item
4998 Useless type conversions
4999
5000 @item
5001 Redundant assignment statements and other redundant constructs
5002
5003 @item
5004 Useless exception handlers
5005
5006 @item
5007 Accidental hiding of name by child unit
5008
5009 @item
5010 Access before elaboration detected at compile time
5011
5012 @item
5013 A range in a @code{for} loop that is known to be null or might be null
5014
5015 @end itemize
5016
5017 @noindent
5018 The following section lists compiler switches that are available
5019 to control the handling of warning messages. It is also possible
5020 to exercise much finer control over what warnings are issued and
5021 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5022 gnat_rm, GNAT Reference manual}.
5023
5024 @table @option
5025 @c !sort!
5026 @item -gnatwa
5027 @emph{Activate all optional errors.}
5028 @cindex @option{-gnatwa} (@command{gcc})
5029 This switch activates most optional warning messages, see remaining list
5030 in this section for details on optional warning messages that can be
5031 individually controlled.  The warnings that are not turned on by this
5032 switch are
5033 @option{-gnatwd} (implicit dereferencing),
5034 @option{-gnatwh} (hiding),
5035 @option{-gnatwl} (elaboration warnings),
5036 @option{-gnatw.o} (warn on values set by out parameters ignored)
5037 and @option{-gnatwt} (tracking of deleted conditional code).
5038 All other optional warnings are turned on.
5039
5040 @item -gnatwA
5041 @emph{Suppress all optional errors.}
5042 @cindex @option{-gnatwA} (@command{gcc})
5043 This switch suppresses all optional warning messages, see remaining list
5044 in this section for details on optional warning messages that can be
5045 individually controlled.
5046
5047 @item -gnatw.a
5048 @emph{Activate warnings on failing assertions.}
5049 @cindex @option{-gnatw.a} (@command{gcc})
5050 @cindex Assert failures
5051 This switch activates warnings for assertions where the compiler can tell at
5052 compile time that the assertion will fail. Note that this warning is given
5053 even if assertions are disabled. The default is that such warnings are
5054 generated.
5055
5056 @item -gnatw.A
5057 @emph{Suppress warnings on failing assertions.}
5058 @cindex @option{-gnatw.A} (@command{gcc})
5059 @cindex Assert failures
5060 This switch suppresses warnings for assertions where the compiler can tell at
5061 compile time that the assertion will fail.
5062
5063 @item -gnatwb
5064 @emph{Activate warnings on bad fixed values.}
5065 @cindex @option{-gnatwb} (@command{gcc})
5066 @cindex Bad fixed values
5067 @cindex Fixed-point Small value
5068 @cindex Small value
5069 This switch activates warnings for static fixed-point expressions whose
5070 value is not an exact multiple of Small. Such values are implementation
5071 dependent, since an implementation is free to choose either of the multiples
5072 that surround the value. GNAT always chooses the closer one, but this is not
5073 required behavior, and it is better to specify a value that is an exact
5074 multiple, ensuring predictable execution. The default is that such warnings
5075 are not generated.
5076
5077 @item -gnatwB
5078 @emph{Suppress warnings on bad fixed values.}
5079 @cindex @option{-gnatwB} (@command{gcc})
5080 This switch suppresses warnings for static fixed-point expressions whose
5081 value is not an exact multiple of Small.
5082
5083 @item -gnatw.b
5084 @emph{Activate warnings on biased representation.}
5085 @cindex @option{-gnatw.b} (@command{gcc})
5086 @cindex Biased representation
5087 This switch activates warnings when a size clause, value size clause, component
5088 clause, or component size clause forces the use of biased representation for an
5089 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5090 to represent 10/11). The default is that such warnings are generated.
5091
5092 @item -gnatw.B
5093 @emph{Suppress warnings on biased representation.}
5094 @cindex @option{-gnatwB} (@command{gcc})
5095 This switch suppresses warnings for representation clauses that force the use
5096 of biased representation.
5097
5098 @item -gnatwc
5099 @emph{Activate warnings on conditionals.}
5100 @cindex @option{-gnatwc} (@command{gcc})
5101 @cindex Conditionals, constant
5102 This switch activates warnings for conditional expressions used in
5103 tests that are known to be True or False at compile time. The default
5104 is that such warnings are not generated.
5105 Note that this warning does
5106 not get issued for the use of boolean variables or constants whose
5107 values are known at compile time, since this is a standard technique
5108 for conditional compilation in Ada, and this would generate too many
5109 false positive warnings.
5110
5111 This warning option also activates a special test for comparisons using
5112 the operators ``>='' and`` <=''.
5113 If the compiler can tell that only the equality condition is possible,
5114 then it will warn that the ``>'' or ``<'' part of the test
5115 is useless and that the operator could be replaced by ``=''.
5116 An example would be comparing a @code{Natural} variable <= 0.
5117
5118 This warning option also generates warnings if
5119 one or both tests is optimized away in a membership test for integer
5120 values if the result can be determined at compile time. Range tests on
5121 enumeration types are not included, since it is common for such tests
5122 to include an end point.
5123
5124 This warning can also be turned on using @option{-gnatwa}.
5125
5126 @item -gnatwC
5127 @emph{Suppress warnings on conditionals.}
5128 @cindex @option{-gnatwC} (@command{gcc})
5129 This switch suppresses warnings for conditional expressions used in
5130 tests that are known to be True or False at compile time.
5131
5132 @item -gnatw.c
5133 @emph{Activate warnings on missing component clauses.}
5134 @cindex @option{-gnatw.c} (@command{gcc})
5135 @cindex Component clause, missing
5136 This switch activates warnings for record components where a record
5137 representation clause is present and has component clauses for the
5138 majority, but not all, of the components. A warning is given for each
5139 component for which no component clause is present.
5140
5141 This warning can also be turned on using @option{-gnatwa}.
5142
5143 @item -gnatw.C
5144 @emph{Suppress warnings on missing component clauses.}
5145 @cindex @option{-gnatwC} (@command{gcc})
5146 This switch suppresses warnings for record components that are
5147 missing a component clause in the situation described above.
5148
5149 @item -gnatwd
5150 @emph{Activate warnings on implicit dereferencing.}
5151 @cindex @option{-gnatwd} (@command{gcc})
5152 If this switch is set, then the use of a prefix of an access type
5153 in an indexed component, slice, or selected component without an
5154 explicit @code{.all} will generate a warning. With this warning
5155 enabled, access checks occur only at points where an explicit
5156 @code{.all} appears in the source code (assuming no warnings are
5157 generated as a result of this switch). The default is that such
5158 warnings are not generated.
5159 Note that @option{-gnatwa} does not affect the setting of
5160 this warning option.
5161
5162 @item -gnatwD
5163 @emph{Suppress warnings on implicit dereferencing.}
5164 @cindex @option{-gnatwD} (@command{gcc})
5165 @cindex Implicit dereferencing
5166 @cindex Dereferencing, implicit
5167 This switch suppresses warnings for implicit dereferences in
5168 indexed components, slices, and selected components.
5169
5170 @item -gnatwe
5171 @emph{Treat warnings as errors.}
5172 @cindex @option{-gnatwe} (@command{gcc})
5173 @cindex Warnings, treat as error
5174 This switch causes warning messages to be treated as errors.
5175 The warning string still appears, but the warning messages are counted
5176 as errors, and prevent the generation of an object file.
5177
5178 @item -gnatw.e
5179 @emph{Activate every optional warning}
5180 @cindex @option{-gnatw.e} (@command{gcc})
5181 @cindex Warnings, activate every optional warning
5182 This switch activates all optional warnings, including those which
5183 are not activated by @code{-gnatwa}.
5184
5185 @item -gnatwf
5186 @emph{Activate warnings on unreferenced formals.}
5187 @cindex @option{-gnatwf} (@command{gcc})
5188 @cindex Formals, unreferenced
5189 This switch causes a warning to be generated if a formal parameter
5190 is not referenced in the body of the subprogram. This warning can
5191 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5192 default is that these warnings are not generated.
5193
5194 @item -gnatwF
5195 @emph{Suppress warnings on unreferenced formals.}
5196 @cindex @option{-gnatwF} (@command{gcc})
5197 This switch suppresses warnings for unreferenced formal
5198 parameters. Note that the
5199 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5200 effect of warning on unreferenced entities other than subprogram
5201 formals.
5202
5203 @item -gnatwg
5204 @emph{Activate warnings on unrecognized pragmas.}
5205 @cindex @option{-gnatwg} (@command{gcc})
5206 @cindex Pragmas, unrecognized
5207 This switch causes a warning to be generated if an unrecognized
5208 pragma is encountered. Apart from issuing this warning, the
5209 pragma is ignored and has no effect. This warning can
5210 also be turned on using @option{-gnatwa}. The default
5211 is that such warnings are issued (satisfying the Ada Reference
5212 Manual requirement that such warnings appear).
5213
5214 @item -gnatwG
5215 @emph{Suppress warnings on unrecognized pragmas.}
5216 @cindex @option{-gnatwG} (@command{gcc})
5217 This switch suppresses warnings for unrecognized pragmas.
5218
5219 @item -gnatwh
5220 @emph{Activate warnings on hiding.}
5221 @cindex @option{-gnatwh} (@command{gcc})
5222 @cindex Hiding of Declarations
5223 This switch activates warnings on hiding declarations.
5224 A declaration is considered hiding
5225 if it is for a non-overloadable entity, and it declares an entity with the
5226 same name as some other entity that is directly or use-visible. The default
5227 is that such warnings are not generated.
5228 Note that @option{-gnatwa} does not affect the setting of this warning option.
5229
5230 @item -gnatwH
5231 @emph{Suppress warnings on hiding.}
5232 @cindex @option{-gnatwH} (@command{gcc})
5233 This switch suppresses warnings on hiding declarations.
5234
5235 @item -gnatwi
5236 @emph{Activate warnings on implementation units.}
5237 @cindex @option{-gnatwi} (@command{gcc})
5238 This switch activates warnings for a @code{with} of an internal GNAT
5239 implementation unit, defined as any unit from the @code{Ada},
5240 @code{Interfaces}, @code{GNAT},
5241 ^^@code{DEC},^ or @code{System}
5242 hierarchies that is not
5243 documented in either the Ada Reference Manual or the GNAT
5244 Programmer's Reference Manual. Such units are intended only
5245 for internal implementation purposes and should not be @code{with}'ed
5246 by user programs. The default is that such warnings are generated
5247 This warning can also be turned on using @option{-gnatwa}.
5248
5249 @item -gnatwI
5250 @emph{Disable warnings on implementation units.}
5251 @cindex @option{-gnatwI} (@command{gcc})
5252 This switch disables warnings for a @code{with} of an internal GNAT
5253 implementation unit.
5254
5255 @item -gnatwj
5256 @emph{Activate warnings on obsolescent features (Annex J).}
5257 @cindex @option{-gnatwj} (@command{gcc})
5258 @cindex Features, obsolescent
5259 @cindex Obsolescent features
5260 If this warning option is activated, then warnings are generated for
5261 calls to subprograms marked with @code{pragma Obsolescent} and
5262 for use of features in Annex J of the Ada Reference Manual. In the
5263 case of Annex J, not all features are flagged. In particular use
5264 of the renamed packages (like @code{Text_IO}) and use of package
5265 @code{ASCII} are not flagged, since these are very common and
5266 would generate many annoying positive warnings. The default is that
5267 such warnings are not generated. This warning is also turned on by
5268 the use of @option{-gnatwa}.
5269
5270 In addition to the above cases, warnings are also generated for
5271 GNAT features that have been provided in past versions but which
5272 have been superseded (typically by features in the new Ada standard).
5273 For example, @code{pragma Ravenscar} will be flagged since its
5274 function is replaced by @code{pragma Profile(Ravenscar)}.
5275
5276 Note that this warning option functions differently from the
5277 restriction @code{No_Obsolescent_Features} in two respects.
5278 First, the restriction applies only to annex J features.
5279 Second, the restriction does flag uses of package @code{ASCII}.
5280
5281 @item -gnatwJ
5282 @emph{Suppress warnings on obsolescent features (Annex J).}
5283 @cindex @option{-gnatwJ} (@command{gcc})
5284 This switch disables warnings on use of obsolescent features.
5285
5286 @item -gnatwk
5287 @emph{Activate warnings on variables that could be constants.}
5288 @cindex @option{-gnatwk} (@command{gcc})
5289 This switch activates warnings for variables that are initialized but
5290 never modified, and then could be declared constants. The default is that
5291 such warnings are not given.
5292 This warning can also be turned on using @option{-gnatwa}.
5293
5294 @item -gnatwK
5295 @emph{Suppress warnings on variables that could be constants.}
5296 @cindex @option{-gnatwK} (@command{gcc})
5297 This switch disables warnings on variables that could be declared constants.
5298
5299 @item -gnatwl
5300 @emph{Activate warnings for elaboration pragmas.}
5301 @cindex @option{-gnatwl} (@command{gcc})
5302 @cindex Elaboration, warnings
5303 This switch activates warnings on missing
5304 @code{Elaborate_All} and @code{Elaborate} pragmas.
5305 See the section in this guide on elaboration checking for details on
5306 when such pragmas should be used. In dynamic elaboration mode, this switch
5307 generations warnings about the need to add elaboration pragmas. Note however,
5308 that if you blindly follow these warnings, and add @code{Elaborate_All}
5309 warnings wherever they are recommended, you basically end up with the
5310 equivalent of the static elaboration model, which may not be what you want for
5311 legacy code for which the static model does not work.
5312
5313 For the static model, the messages generated are labeled "info:" (for
5314 information messages). They are not warnings to add elaboration pragmas,
5315 merely informational messages showing what implicit elaboration pragmas
5316 have been added, for use in analyzing elaboration circularity problems.
5317
5318 Warnings are also generated if you
5319 are using the static mode of elaboration, and a @code{pragma Elaborate}
5320 is encountered. The default is that such warnings
5321 are not generated.
5322 This warning is not automatically turned on by the use of @option{-gnatwa}.
5323
5324 @item -gnatwL
5325 @emph{Suppress warnings for elaboration pragmas.}
5326 @cindex @option{-gnatwL} (@command{gcc})
5327 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5328 See the section in this guide on elaboration checking for details on
5329 when such pragmas should be used.
5330
5331 @item -gnatwm
5332 @emph{Activate warnings on modified but unreferenced variables.}
5333 @cindex @option{-gnatwm} (@command{gcc})
5334 This switch activates warnings for variables that are assigned (using
5335 an initialization value or with one or more assignment statements) but
5336 whose value is never read. The warning is suppressed for volatile
5337 variables and also for variables that are renamings of other variables
5338 or for which an address clause is given.
5339 This warning can also be turned on using @option{-gnatwa}.
5340 The default is that these warnings are not given.
5341
5342 @item -gnatwM
5343 @emph{Disable warnings on modified but unreferenced variables.}
5344 @cindex @option{-gnatwM} (@command{gcc})
5345 This switch disables warnings for variables that are assigned or
5346 initialized, but never read.
5347
5348 @item -gnatw.m
5349 @emph{Activate warnings on suspicious modulus values.}
5350 @cindex @option{-gnatw.m} (@command{gcc})
5351 This switch activates warnings for modulus values that seem suspicious.
5352 The cases caught are where the size is the same as the modulus (e.g.
5353 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5354 with no size clause. The guess in both cases is that 2**x was intended
5355 rather than x. The default is that these warnings are given.
5356
5357 @item -gnatw.M
5358 @emph{Disable warnings on suspicious modulus values.}
5359 @cindex @option{-gnatw.M} (@command{gcc})
5360 This switch disables warnings for suspicious modulus values.
5361
5362 @item -gnatwn
5363 @emph{Set normal warnings mode.}
5364 @cindex @option{-gnatwn} (@command{gcc})
5365 This switch sets normal warning mode, in which enabled warnings are
5366 issued and treated as warnings rather than errors. This is the default
5367 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5368 an explicit @option{-gnatws} or
5369 @option{-gnatwe}. It also cancels the effect of the
5370 implicit @option{-gnatwe} that is activated by the
5371 use of @option{-gnatg}.
5372
5373 @item -gnatwo
5374 @emph{Activate warnings on address clause overlays.}
5375 @cindex @option{-gnatwo} (@command{gcc})
5376 @cindex Address Clauses, warnings
5377 This switch activates warnings for possibly unintended initialization
5378 effects of defining address clauses that cause one variable to overlap
5379 another. The default is that such warnings are generated.
5380 This warning can also be turned on using @option{-gnatwa}.
5381
5382 @item -gnatwO
5383 @emph{Suppress warnings on address clause overlays.}
5384 @cindex @option{-gnatwO} (@command{gcc})
5385 This switch suppresses warnings on possibly unintended initialization
5386 effects of defining address clauses that cause one variable to overlap
5387 another.
5388
5389 @item -gnatw.o
5390 @emph{Activate warnings on modified but unreferenced out parameters.}
5391 @cindex @option{-gnatw.o} (@command{gcc})
5392 This switch activates warnings for variables that are modified by using
5393 them as actuals for a call to a procedure with an out mode formal, where
5394 the resulting assigned value is never read. It is applicable in the case
5395 where there is more than one out mode formal. If there is only one out
5396 mode formal, the warning is issued by default (controlled by -gnatwu).
5397 The warning is suppressed for volatile
5398 variables and also for variables that are renamings of other variables
5399 or for which an address clause is given.
5400 The default is that these warnings are not given. Note that this warning
5401 is not included in -gnatwa, it must be activated explicitly.
5402
5403 @item -gnatw.O
5404 @emph{Disable warnings on modified but unreferenced out parameters.}
5405 @cindex @option{-gnatw.O} (@command{gcc})
5406 This switch suppresses warnings for variables that are modified by using
5407 them as actuals for a call to a procedure with an out mode formal, where
5408 the resulting assigned value is never read.
5409
5410 @item -gnatwp
5411 @emph{Activate warnings on ineffective pragma Inlines.}
5412 @cindex @option{-gnatwp} (@command{gcc})
5413 @cindex Inlining, warnings
5414 This switch activates warnings for failure of front end inlining
5415 (activated by @option{-gnatN}) to inline a particular call. There are
5416 many reasons for not being able to inline a call, including most
5417 commonly that the call is too complex to inline. The default is
5418 that such warnings are not given.
5419 This warning can also be turned on using @option{-gnatwa}.
5420 Warnings on ineffective inlining by the gcc back-end can be activated
5421 separately, using the gcc switch -Winline.
5422
5423 @item -gnatwP
5424 @emph{Suppress warnings on ineffective pragma Inlines.}
5425 @cindex @option{-gnatwP} (@command{gcc})
5426 This switch suppresses warnings on ineffective pragma Inlines. If the
5427 inlining mechanism cannot inline a call, it will simply ignore the
5428 request silently.
5429
5430 @item -gnatw.p
5431 @emph{Activate warnings on parameter ordering.}
5432 @cindex @option{-gnatw.p} (@command{gcc})
5433 @cindex Parameter order, warnings
5434 This switch activates warnings for cases of suspicious parameter
5435 ordering when the list of arguments are all simple identifiers that
5436 match the names of the formals, but are in a different order. The
5437 warning is suppressed if any use of named parameter notation is used,
5438 so this is the appropriate way to suppress a false positive (and
5439 serves to emphasize that the "misordering" is deliberate). The
5440 default is
5441 that such warnings are not given.
5442 This warning can also be turned on using @option{-gnatwa}.
5443
5444 @item -gnatw.P
5445 @emph{Suppress warnings on parameter ordering.}
5446 @cindex @option{-gnatw.P} (@command{gcc})
5447 This switch suppresses warnings on cases of suspicious parameter
5448 ordering.
5449
5450 @item -gnatwq
5451 @emph{Activate warnings on questionable missing parentheses.}
5452 @cindex @option{-gnatwq} (@command{gcc})
5453 @cindex Parentheses, warnings
5454 This switch activates warnings for cases where parentheses are not used and
5455 the result is potential ambiguity from a readers point of view. For example
5456 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5457 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5458 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5459 follow the rule of always parenthesizing to make the association clear, and
5460 this warning switch warns if such parentheses are not present. The default
5461 is that these warnings are given.
5462 This warning can also be turned on using @option{-gnatwa}.
5463
5464 @item -gnatwQ
5465 @emph{Suppress warnings on questionable missing parentheses.}
5466 @cindex @option{-gnatwQ} (@command{gcc})
5467 This switch suppresses warnings for cases where the association is not
5468 clear and the use of parentheses is preferred.
5469
5470 @item -gnatwr
5471 @emph{Activate warnings on redundant constructs.}
5472 @cindex @option{-gnatwr} (@command{gcc})
5473 This switch activates warnings for redundant constructs. The following
5474 is the current list of constructs regarded as redundant:
5475
5476 @itemize @bullet
5477 @item
5478 Assignment of an item to itself.
5479 @item
5480 Type conversion that converts an expression to its own type.
5481 @item
5482 Use of the attribute @code{Base} where @code{typ'Base} is the same
5483 as @code{typ}.
5484 @item
5485 Use of pragma @code{Pack} when all components are placed by a record
5486 representation clause.
5487 @item
5488 Exception handler containing only a reraise statement (raise with no
5489 operand) which has no effect.
5490 @item
5491 Use of the operator abs on an operand that is known at compile time
5492 to be non-negative
5493 @item
5494 Comparison of boolean expressions to an explicit True value.
5495 @end itemize
5496
5497 This warning can also be turned on using @option{-gnatwa}.
5498 The default is that warnings for redundant constructs are not given.
5499
5500 @item -gnatwR
5501 @emph{Suppress warnings on redundant constructs.}
5502 @cindex @option{-gnatwR} (@command{gcc})
5503 This switch suppresses warnings for redundant constructs.
5504
5505 @item -gnatw.r
5506 @emph{Activate warnings for object renaming function.}
5507 @cindex @option{-gnatw.r} (@command{gcc})
5508 This switch activates warnings for an object renaming that renames a
5509 function call, which is equivalent to a constant declaration (as
5510 opposed to renaming the function itself).  The default is that these
5511 warnings are given.  This warning can also be turned on using
5512 @option{-gnatwa}.
5513
5514 @item -gnatw.R
5515 @emph{Suppress warnings for object renaming function.}
5516 @cindex @option{-gnatwT} (@command{gcc})
5517 This switch suppresses warnings for object renaming function.
5518
5519 @item -gnatws
5520 @emph{Suppress all warnings.}
5521 @cindex @option{-gnatws} (@command{gcc})
5522 This switch completely suppresses the
5523 output of all warning messages from the GNAT front end.
5524 Note that it does not suppress warnings from the @command{gcc} back end.
5525 To suppress these back end warnings as well, use the switch @option{-w}
5526 in addition to @option{-gnatws}.
5527
5528 @item -gnatwt
5529 @emph{Activate warnings for tracking of deleted conditional code.}
5530 @cindex @option{-gnatwt} (@command{gcc})
5531 @cindex Deactivated code, warnings
5532 @cindex Deleted code, warnings
5533 This switch activates warnings for tracking of code in conditionals (IF and
5534 CASE statements) that is detected to be dead code which cannot be executed, and
5535 which is removed by the front end. This warning is off by default, and is not
5536 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5537 useful for detecting deactivated code in certified applications.
5538
5539 @item -gnatwT
5540 @emph{Suppress warnings for tracking of deleted conditional code.}
5541 @cindex @option{-gnatwT} (@command{gcc})
5542 This switch suppresses warnings for tracking of deleted conditional code.
5543
5544 @item -gnatwu
5545 @emph{Activate warnings on unused entities.}
5546 @cindex @option{-gnatwu} (@command{gcc})
5547 This switch activates warnings to be generated for entities that
5548 are declared but not referenced, and for units that are @code{with}'ed
5549 and not
5550 referenced. In the case of packages, a warning is also generated if
5551 no entities in the package are referenced. This means that if the package
5552 is referenced but the only references are in @code{use}
5553 clauses or @code{renames}
5554 declarations, a warning is still generated. A warning is also generated
5555 for a generic package that is @code{with}'ed but never instantiated.
5556 In the case where a package or subprogram body is compiled, and there
5557 is a @code{with} on the corresponding spec
5558 that is only referenced in the body,
5559 a warning is also generated, noting that the
5560 @code{with} can be moved to the body. The default is that
5561 such warnings are not generated.
5562 This switch also activates warnings on unreferenced formals
5563 (it includes the effect of @option{-gnatwf}).
5564 This warning can also be turned on using @option{-gnatwa}.
5565
5566 @item -gnatwU
5567 @emph{Suppress warnings on unused entities.}
5568 @cindex @option{-gnatwU} (@command{gcc})
5569 This switch suppresses warnings for unused entities and packages.
5570 It also turns off warnings on unreferenced formals (and thus includes
5571 the effect of @option{-gnatwF}).
5572
5573 @item -gnatwv
5574 @emph{Activate warnings on unassigned variables.}
5575 @cindex @option{-gnatwv} (@command{gcc})
5576 @cindex Unassigned variable warnings
5577 This switch activates warnings for access to variables which
5578 may not be properly initialized. The default is that
5579 such warnings are generated.
5580 This warning can also be turned on using @option{-gnatwa}.
5581
5582 @item -gnatwV
5583 @emph{Suppress warnings on unassigned variables.}
5584 @cindex @option{-gnatwV} (@command{gcc})
5585 This switch suppresses warnings for access to variables which
5586 may not be properly initialized.
5587 For variables of a composite type, the warning can also be suppressed in
5588 Ada 2005 by using a default initialization with a box. For example, if
5589 Table is an array of records whose components are only partially uninitialized,
5590 then the following code:
5591
5592 @smallexample @c ada
5593    Tab : Table := (others => <>);
5594 @end smallexample
5595
5596 will suppress warnings on subsequent statements that access components
5597 of variable Tab.
5598
5599 @item -gnatww
5600 @emph{Activate warnings on wrong low bound assumption.}
5601 @cindex @option{-gnatww} (@command{gcc})
5602 @cindex String indexing warnings
5603 This switch activates warnings for indexing an unconstrained string parameter
5604 with a literal or S'Length. This is a case where the code is assuming that the
5605 low bound is one, which is in general not true (for example when a slice is
5606 passed). The default is that such warnings are generated.
5607 This warning can also be turned on using @option{-gnatwa}.
5608
5609 @item -gnatwW
5610 @emph{Suppress warnings on wrong low bound assumption.}
5611 @cindex @option{-gnatwW} (@command{gcc})
5612 This switch suppresses warnings for indexing an unconstrained string parameter
5613 with a literal or S'Length. Note that this warning can also be suppressed
5614 in a particular case by adding an
5615 assertion that the lower bound is 1,
5616 as shown in the following example.
5617
5618 @smallexample @c ada
5619    procedure K (S : String) is
5620       pragma Assert (S'First = 1);
5621       @dots{}
5622 @end smallexample
5623
5624 @item -gnatw.w
5625 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5626 @cindex @option{-gnatw.w} (@command{gcc})
5627 @cindex Warnings Off control
5628 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5629 where either the pragma is entirely useless (because it suppresses no
5630 warnings), or it could be replaced by @code{pragma Unreferenced} or
5631 @code{pragma Unmodified}.The default is that these warnings are not given.
5632 Note that this warning is not included in -gnatwa, it must be
5633 activated explicitly.
5634
5635 @item -gnatw.W
5636 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5637 @cindex @option{-gnatw.W} (@command{gcc})
5638 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5639
5640 @item -gnatwx
5641 @emph{Activate warnings on Export/Import pragmas.}
5642 @cindex @option{-gnatwx} (@command{gcc})
5643 @cindex Export/Import pragma warnings
5644 This switch activates warnings on Export/Import pragmas when
5645 the compiler detects a possible conflict between the Ada and
5646 foreign language calling sequences. For example, the use of
5647 default parameters in a convention C procedure is dubious
5648 because the C compiler cannot supply the proper default, so
5649 a warning is issued. The default is that such warnings are
5650 generated.
5651 This warning can also be turned on using @option{-gnatwa}.
5652
5653 @item -gnatwX
5654 @emph{Suppress warnings on Export/Import pragmas.}
5655 @cindex @option{-gnatwX} (@command{gcc})
5656 This switch suppresses warnings on Export/Import pragmas.
5657 The sense of this is that you are telling the compiler that
5658 you know what you are doing in writing the pragma, and it
5659 should not complain at you.
5660
5661 @item -gnatw.x
5662 @emph{Activate warnings for No_Exception_Propagation mode.}
5663 @cindex @option{-gnatwm} (@command{gcc})
5664 This switch activates warnings for exception usage when pragma Restrictions
5665 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5666 explicit exception raises which are not covered by a local handler, and for
5667 exception handlers which do not cover a local raise. The default is that these
5668 warnings are not given.
5669
5670 @item -gnatw.X
5671 @emph{Disable warnings for No_Exception_Propagation mode.}
5672 This switch disables warnings for exception usage when pragma Restrictions
5673 (No_Exception_Propagation) is in effect.
5674
5675 @item -gnatwy
5676 @emph{Activate warnings for Ada 2005 compatibility issues.}
5677 @cindex @option{-gnatwy} (@command{gcc})
5678 @cindex Ada 2005 compatibility issues warnings
5679 For the most part Ada 2005 is upwards compatible with Ada 95,
5680 but there are some exceptions (for example the fact that
5681 @code{interface} is now a reserved word in Ada 2005). This
5682 switch activates several warnings to help in identifying
5683 and correcting such incompatibilities. The default is that
5684 these warnings are generated. Note that at one point Ada 2005
5685 was called Ada 0Y, hence the choice of character.
5686 This warning can also be turned on using @option{-gnatwa}.
5687
5688 @item -gnatwY
5689 @emph{Disable warnings for Ada 2005 compatibility issues.}
5690 @cindex @option{-gnatwY} (@command{gcc})
5691 @cindex Ada 2005 compatibility issues warnings
5692 This switch suppresses several warnings intended to help in identifying
5693 incompatibilities between Ada 95 and Ada 2005.
5694
5695 @item -gnatwz
5696 @emph{Activate warnings on unchecked conversions.}
5697 @cindex @option{-gnatwz} (@command{gcc})
5698 @cindex Unchecked_Conversion warnings
5699 This switch activates warnings for unchecked conversions
5700 where the types are known at compile time to have different
5701 sizes. The default
5702 is that such warnings are generated. Warnings are also
5703 generated for subprogram pointers with different conventions,
5704 and, on VMS only, for data pointers with different conventions.
5705 This warning can also be turned on using @option{-gnatwa}.
5706
5707 @item -gnatwZ
5708 @emph{Suppress warnings on unchecked conversions.}
5709 @cindex @option{-gnatwZ} (@command{gcc})
5710 This switch suppresses warnings for unchecked conversions
5711 where the types are known at compile time to have different
5712 sizes or conventions.
5713
5714 @item ^-Wunused^WARNINGS=UNUSED^
5715 @cindex @option{-Wunused}
5716 The warnings controlled by the @option{-gnatw} switch are generated by
5717 the front end of the compiler. The @option{GCC} back end can provide
5718 additional warnings and they are controlled by the @option{-W} switch.
5719 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5720 warnings for entities that are declared but not referenced.
5721
5722 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5723 @cindex @option{-Wuninitialized}
5724 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5725 the back end warning for uninitialized variables. This switch must be
5726 used in conjunction with an optimization level greater than zero.
5727
5728 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5729 @cindex @option{-Wall}
5730 This switch enables all the above warnings from the @option{GCC} back end.
5731 The code generator detects a number of warning situations that are missed
5732 by the @option{GNAT} front end, and this switch can be used to activate them.
5733 The use of this switch also sets the default front end warning mode to
5734 @option{-gnatwa}, that is, most front end warnings activated as well.
5735
5736 @item ^-w^/NO_BACK_END_WARNINGS^
5737 @cindex @option{-w}
5738 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5739 The use of this switch also sets the default front end warning mode to
5740 @option{-gnatws}, that is, front end warnings suppressed as well.
5741
5742 @end table
5743
5744 @noindent
5745 @ifclear vms
5746 A string of warning parameters can be used in the same parameter. For example:
5747
5748 @smallexample
5749 -gnatwaLe
5750 @end smallexample
5751
5752 @noindent
5753 will turn on all optional warnings except for elaboration pragma warnings,
5754 and also specify that warnings should be treated as errors.
5755 @end ifclear
5756 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5757
5758 @table @option
5759 @c !sort!
5760 @item -gnatwC
5761 @item -gnatwD
5762 @item -gnatwF
5763 @item -gnatwg
5764 @item -gnatwH
5765 @item -gnatwi
5766 @item -gnatwJ
5767 @item -gnatwK
5768 @item -gnatwL
5769 @item -gnatwM
5770 @item -gnatwn
5771 @item -gnatwo
5772 @item -gnatwP
5773 @item -gnatwR
5774 @item -gnatwU
5775 @item -gnatwv
5776 @item -gnatwz
5777 @item -gnatwx
5778
5779 @end table
5780
5781 @node Debugging and Assertion Control
5782 @subsection Debugging and Assertion Control
5783
5784 @table @option
5785 @item -gnata
5786 @cindex @option{-gnata} (@command{gcc})
5787 @findex Assert
5788 @findex Debug
5789 @cindex Assertions
5790
5791 @noindent
5792 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5793 are ignored. This switch, where @samp{a} stands for assert, causes
5794 @code{Assert} and @code{Debug} pragmas to be activated.
5795
5796 The pragmas have the form:
5797
5798 @smallexample
5799 @cartouche
5800    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5801                       @var{static-string-expression}@r{]})
5802    @b{pragma} Debug (@var{procedure call})
5803 @end cartouche
5804 @end smallexample
5805
5806 @noindent
5807 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5808 If the result is @code{True}, the pragma has no effect (other than
5809 possible side effects from evaluating the expression). If the result is
5810 @code{False}, the exception @code{Assert_Failure} declared in the package
5811 @code{System.Assertions} is
5812 raised (passing @var{static-string-expression}, if present, as the
5813 message associated with the exception). If no string expression is
5814 given the default is a string giving the file name and line number
5815 of the pragma.
5816
5817 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5818 @code{pragma Debug} may appear within a declaration sequence, allowing
5819 debugging procedures to be called between declarations.
5820
5821 @ifset vms
5822 @item /DEBUG@r{[}=debug-level@r{]}
5823 @itemx  /NODEBUG
5824 Specifies how much debugging information is to be included in
5825 the resulting object file where 'debug-level' is one of the following:
5826 @table @code
5827 @item   TRACEBACK
5828 Include both debugger symbol records and traceback
5829 the object file.
5830 This is the default setting.
5831 @item   ALL
5832 Include both debugger symbol records and traceback in
5833 object file.
5834 @item   NONE
5835 Excludes both debugger symbol records and traceback
5836 the object file. Same as /NODEBUG.
5837 @item   SYMBOLS
5838 Includes only debugger symbol records in the object
5839 file. Note that this doesn't include traceback information.
5840 @end table
5841 @end ifset
5842 @end table
5843
5844 @node Validity Checking
5845 @subsection Validity Checking
5846 @findex Validity Checking
5847
5848 @noindent
5849 The Ada Reference Manual has specific requirements for checking
5850 for invalid values. In particular, RM 13.9.1 requires that the
5851 evaluation of invalid values (for example from unchecked conversions),
5852 not result in erroneous execution. In GNAT, the result of such an
5853 evaluation in normal default mode is to either use the value
5854 unmodified, or to raise Constraint_Error in those cases where use
5855 of the unmodified value would cause erroneous execution. The cases
5856 where unmodified values might lead to erroneous execution are case
5857 statements (where a wild jump might result from an invalid value),
5858 and subscripts on the left hand side (where memory corruption could
5859 occur as a result of an invalid value).
5860
5861 The @option{-gnatB} switch tells the compiler to assume that all
5862 values are valid (that is, within their declared subtype range)
5863 except in the context of a use of the Valid attribute. This means
5864 the compiler can generate more efficient code, since the range
5865 of values is better known at compile time.
5866
5867 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5868 checking mode.
5869 @ifclear vms
5870 The @code{x} argument is a string of letters that
5871 indicate validity checks that are performed or not performed in addition
5872 to the default checks described above.
5873 @end ifclear
5874 @ifset vms
5875 The options allowed for this qualifier
5876 indicate validity checks that are performed or not performed in addition
5877 to the default checks described above.
5878 @end ifset
5879
5880 @table @option
5881 @c !sort!
5882 @item -gnatVa
5883 @emph{All validity checks.}
5884 @cindex @option{-gnatVa} (@command{gcc})
5885 All validity checks are turned on.
5886 @ifclear vms
5887 That is, @option{-gnatVa} is
5888 equivalent to @option{gnatVcdfimorst}.
5889 @end ifclear
5890
5891 @item -gnatVc
5892 @emph{Validity checks for copies.}
5893 @cindex @option{-gnatVc} (@command{gcc})
5894 The right hand side of assignments, and the initializing values of
5895 object declarations are validity checked.
5896
5897 @item -gnatVd
5898 @emph{Default (RM) validity checks.}
5899 @cindex @option{-gnatVd} (@command{gcc})
5900 Some validity checks are done by default following normal Ada semantics
5901 (RM 13.9.1 (9-11)).
5902 A check is done in case statements that the expression is within the range
5903 of the subtype. If it is not, Constraint_Error is raised.
5904 For assignments to array components, a check is done that the expression used
5905 as index is within the range. If it is not, Constraint_Error is raised.
5906 Both these validity checks may be turned off using switch @option{-gnatVD}.
5907 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5908 switch @option{-gnatVd} will leave the checks turned on.
5909 Switch @option{-gnatVD} should be used only if you are sure that all such
5910 expressions have valid values. If you use this switch and invalid values
5911 are present, then the program is erroneous, and wild jumps or memory
5912 overwriting may occur.
5913
5914 @item -gnatVe
5915 @emph{Validity checks for elementary components.}
5916 @cindex @option{-gnatVe} (@command{gcc})
5917 In the absence of this switch, assignments to record or array components are
5918 not validity checked, even if validity checks for assignments generally
5919 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5920 require valid data, but assignment of individual components does. So for
5921 example, there is a difference between copying the elements of an array with a
5922 slice assignment, compared to assigning element by element in a loop. This
5923 switch allows you to turn off validity checking for components, even when they
5924 are assigned component by component.
5925
5926 @item -gnatVf
5927 @emph{Validity checks for floating-point values.}
5928 @cindex @option{-gnatVf} (@command{gcc})
5929 In the absence of this switch, validity checking occurs only for discrete
5930 values. If @option{-gnatVf} is specified, then validity checking also applies
5931 for floating-point values, and NaNs and infinities are considered invalid,
5932 as well as out of range values for constrained types. Note that this means
5933 that standard IEEE infinity mode is not allowed. The exact contexts
5934 in which floating-point values are checked depends on the setting of other
5935 options. For example,
5936 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5937 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5938 (the order does not matter) specifies that floating-point parameters of mode
5939 @code{in} should be validity checked.
5940
5941 @item -gnatVi
5942 @emph{Validity checks for @code{in} mode parameters}
5943 @cindex @option{-gnatVi} (@command{gcc})
5944 Arguments for parameters of mode @code{in} are validity checked in function
5945 and procedure calls at the point of call.
5946
5947 @item -gnatVm
5948 @emph{Validity checks for @code{in out} mode parameters.}
5949 @cindex @option{-gnatVm} (@command{gcc})
5950 Arguments for parameters of mode @code{in out} are validity checked in
5951 procedure calls at the point of call. The @code{'m'} here stands for
5952 modify, since this concerns parameters that can be modified by the call.
5953 Note that there is no specific option to test @code{out} parameters,
5954 but any reference within the subprogram will be tested in the usual
5955 manner, and if an invalid value is copied back, any reference to it
5956 will be subject to validity checking.
5957
5958 @item -gnatVn
5959 @emph{No validity checks.}
5960 @cindex @option{-gnatVn} (@command{gcc})
5961 This switch turns off all validity checking, including the default checking
5962 for case statements and left hand side subscripts. Note that the use of
5963 the switch @option{-gnatp} suppresses all run-time checks, including
5964 validity checks, and thus implies @option{-gnatVn}. When this switch
5965 is used, it cancels any other @option{-gnatV} previously issued.
5966
5967 @item -gnatVo
5968 @emph{Validity checks for operator and attribute operands.}
5969 @cindex @option{-gnatVo} (@command{gcc})
5970 Arguments for predefined operators and attributes are validity checked.
5971 This includes all operators in package @code{Standard},
5972 the shift operators defined as intrinsic in package @code{Interfaces}
5973 and operands for attributes such as @code{Pos}. Checks are also made
5974 on individual component values for composite comparisons, and on the
5975 expressions in type conversions and qualified expressions. Checks are
5976 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5977
5978 @item -gnatVp
5979 @emph{Validity checks for parameters.}
5980 @cindex @option{-gnatVp} (@command{gcc})
5981 This controls the treatment of parameters within a subprogram (as opposed
5982 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5983 of parameters on a call. If either of these call options is used, then
5984 normally an assumption is made within a subprogram that the input arguments
5985 have been validity checking at the point of call, and do not need checking
5986 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5987 is not made, and parameters are not assumed to be valid, so their validity
5988 will be checked (or rechecked) within the subprogram.
5989
5990 @item -gnatVr
5991 @emph{Validity checks for function returns.}
5992 @cindex @option{-gnatVr} (@command{gcc})
5993 The expression in @code{return} statements in functions is validity
5994 checked.
5995
5996 @item -gnatVs
5997 @emph{Validity checks for subscripts.}
5998 @cindex @option{-gnatVs} (@command{gcc})
5999 All subscripts expressions are checked for validity, whether they appear
6000 on the right side or left side (in default mode only left side subscripts
6001 are validity checked).
6002
6003 @item -gnatVt
6004 @emph{Validity checks for tests.}
6005 @cindex @option{-gnatVt} (@command{gcc})
6006 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6007 statements are checked, as well as guard expressions in entry calls.
6008
6009 @end table
6010
6011 @noindent
6012 The @option{-gnatV} switch may be followed by
6013 ^a string of letters^a list of options^
6014 to turn on a series of validity checking options.
6015 For example,
6016 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6017 specifies that in addition to the default validity checking, copies and
6018 function return expressions are to be validity checked.
6019 In order to make it easier
6020 to specify the desired combination of effects,
6021 @ifclear vms
6022 the upper case letters @code{CDFIMORST} may
6023 be used to turn off the corresponding lower case option.
6024 @end ifclear
6025 @ifset vms
6026 the prefix @code{NO} on an option turns off the corresponding validity
6027 checking:
6028 @itemize @bullet
6029 @item @code{NOCOPIES}
6030 @item @code{NODEFAULT}
6031 @item @code{NOFLOATS}
6032 @item @code{NOIN_PARAMS}
6033 @item @code{NOMOD_PARAMS}
6034 @item @code{NOOPERANDS}
6035 @item @code{NORETURNS}
6036 @item @code{NOSUBSCRIPTS}
6037 @item @code{NOTESTS}
6038 @end itemize
6039 @end ifset
6040 Thus
6041 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6042 turns on all validity checking options except for
6043 checking of @code{@b{in out}} procedure arguments.
6044
6045 The specification of additional validity checking generates extra code (and
6046 in the case of @option{-gnatVa} the code expansion can be substantial).
6047 However, these additional checks can be very useful in detecting
6048 uninitialized variables, incorrect use of unchecked conversion, and other
6049 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6050 is useful in conjunction with the extra validity checking, since this
6051 ensures that wherever possible uninitialized variables have invalid values.
6052
6053 See also the pragma @code{Validity_Checks} which allows modification of
6054 the validity checking mode at the program source level, and also allows for
6055 temporary disabling of validity checks.
6056
6057 @node Style Checking
6058 @subsection Style Checking
6059 @findex Style checking
6060
6061 @noindent
6062 The @option{-gnaty^x^(option,option,@dots{})^} switch
6063 @cindex @option{-gnaty} (@command{gcc})
6064 causes the compiler to
6065 enforce specified style rules. A limited set of style rules has been used
6066 in writing the GNAT sources themselves. This switch allows user programs
6067 to activate all or some of these checks. If the source program fails a
6068 specified style check, an appropriate warning message is given, preceded by
6069 the character sequence ``(style)''.
6070 @ifset vms
6071 @code{(option,option,@dots{})} is a sequence of keywords
6072 @end ifset
6073 @ifclear vms
6074 The string @var{x} is a sequence of letters or digits
6075 @end ifclear
6076 indicating the particular style
6077 checks to be performed. The following checks are defined:
6078
6079 @table @option
6080 @c !sort!
6081 @item 0-9
6082 @emph{Specify indentation level.}
6083 If a digit from 1-9 appears
6084 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6085 then proper indentation is checked, with the digit indicating the
6086 indentation level required. A value of zero turns off this style check.
6087 The general style of required indentation is as specified by
6088 the examples in the Ada Reference Manual. Full line comments must be
6089 aligned with the @code{--} starting on a column that is a multiple of
6090 the alignment level, or they may be aligned the same way as the following
6091 non-blank line (this is useful when full line comments appear in the middle
6092 of a statement.
6093
6094 @item ^a^ATTRIBUTE^
6095 @emph{Check attribute casing.}
6096 Attribute names, including the case of keywords such as @code{digits}
6097 used as attributes names, must be written in mixed case, that is, the
6098 initial letter and any letter following an underscore must be uppercase.
6099 All other letters must be lowercase.
6100
6101 @item ^A^ARRAY_INDEXES^
6102 @emph{Use of array index numbers in array attributes.}
6103 When using the array attributes First, Last, Range,
6104 or Length, the index number must be omitted for one-dimensional arrays
6105 and is required for multi-dimensional arrays.
6106
6107 @item ^b^BLANKS^
6108 @emph{Blanks not allowed at statement end.}
6109 Trailing blanks are not allowed at the end of statements. The purpose of this
6110 rule, together with h (no horizontal tabs), is to enforce a canonical format
6111 for the use of blanks to separate source tokens.
6112
6113 @item ^c^COMMENTS^
6114 @emph{Check comments.}
6115 Comments must meet the following set of rules:
6116
6117 @itemize @bullet
6118
6119 @item
6120 The ``@code{--}'' that starts the column must either start in column one,
6121 or else at least one blank must precede this sequence.
6122
6123 @item
6124 Comments that follow other tokens on a line must have at least one blank
6125 following the ``@code{--}'' at the start of the comment.
6126
6127 @item
6128 Full line comments must have two blanks following the ``@code{--}'' that
6129 starts the comment, with the following exceptions.
6130
6131 @item
6132 A line consisting only of the ``@code{--}'' characters, possibly preceded
6133 by blanks is permitted.
6134
6135 @item
6136 A comment starting with ``@code{--x}'' where @code{x} is a special character
6137 is permitted.
6138 This allows proper processing of the output generated by specialized tools
6139 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6140 annotation
6141 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6142 special character is defined as being in one of the ASCII ranges
6143 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6144 Note that this usage is not permitted
6145 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6146
6147 @item
6148 A line consisting entirely of minus signs, possibly preceded by blanks, is
6149 permitted. This allows the construction of box comments where lines of minus
6150 signs are used to form the top and bottom of the box.
6151
6152 @item
6153 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6154 least one blank follows the initial ``@code{--}''. Together with the preceding
6155 rule, this allows the construction of box comments, as shown in the following
6156 example:
6157 @smallexample
6158 ---------------------------
6159 -- This is a box comment --
6160 -- with two text lines.  --
6161 ---------------------------
6162 @end smallexample
6163 @end itemize
6164
6165 @item ^d^DOS_LINE_ENDINGS^
6166 @emph{Check no DOS line terminators present.}
6167 All lines must be terminated by a single ASCII.LF
6168 character (in particular the DOS line terminator sequence CR/LF is not
6169 allowed).
6170
6171 @item ^e^END^
6172 @emph{Check end/exit labels.}
6173 Optional labels on @code{end} statements ending subprograms and on
6174 @code{exit} statements exiting named loops, are required to be present.
6175
6176 @item ^f^VTABS^
6177 @emph{No form feeds or vertical tabs.}
6178 Neither form feeds nor vertical tab characters are permitted
6179 in the source text.
6180
6181 @item ^g^GNAT^
6182 @emph{GNAT style mode}
6183 The set of style check switches is set to match that used by the GNAT sources.
6184 This may be useful when developing code that is eventually intended to be
6185 incorporated into GNAT. For further details, see GNAT sources.
6186
6187 @item ^h^HTABS^
6188 @emph{No horizontal tabs.}
6189 Horizontal tab characters are not permitted in the source text.
6190 Together with the b (no blanks at end of line) check, this
6191 enforces a canonical form for the use of blanks to separate
6192 source tokens.
6193
6194 @item ^i^IF_THEN^
6195 @emph{Check if-then layout.}
6196 The keyword @code{then} must appear either on the same
6197 line as corresponding @code{if}, or on a line on its own, lined
6198 up under the @code{if} with at least one non-blank line in between
6199 containing all or part of the condition to be tested.
6200
6201 @item ^I^IN_MODE^
6202 @emph{check mode IN keywords}
6203 Mode @code{in} (the default mode) is not
6204 allowed to be given explicitly. @code{in out} is fine,
6205 but not @code{in} on its own.
6206
6207 @item ^k^KEYWORD^
6208 @emph{Check keyword casing.}
6209 All keywords must be in lower case (with the exception of keywords
6210 such as @code{digits} used as attribute names to which this check
6211 does not apply).
6212
6213 @item ^l^LAYOUT^
6214 @emph{Check layout.}
6215 Layout of statement and declaration constructs must follow the
6216 recommendations in the Ada Reference Manual, as indicated by the
6217 form of the syntax rules. For example an @code{else} keyword must
6218 be lined up with the corresponding @code{if} keyword.
6219
6220 There are two respects in which the style rule enforced by this check
6221 option are more liberal than those in the Ada Reference Manual. First
6222 in the case of record declarations, it is permissible to put the
6223 @code{record} keyword on the same line as the @code{type} keyword, and
6224 then the @code{end} in @code{end record} must line up under @code{type}.
6225 This is also permitted when the type declaration is split on two lines.
6226 For example, any of the following three layouts is acceptable:
6227
6228 @smallexample @c ada
6229 @cartouche
6230 type q is record
6231    a : integer;
6232    b : integer;
6233 end record;
6234
6235 type q is
6236    record
6237       a : integer;
6238       b : integer;
6239    end record;
6240
6241 type q is
6242    record
6243       a : integer;
6244       b : integer;
6245 end record;
6246
6247 @end cartouche
6248 @end smallexample
6249
6250 @noindent
6251 Second, in the case of a block statement, a permitted alternative
6252 is to put the block label on the same line as the @code{declare} or
6253 @code{begin} keyword, and then line the @code{end} keyword up under
6254 the block label. For example both the following are permitted:
6255
6256 @smallexample @c ada
6257 @cartouche
6258 Block : declare
6259    A : Integer := 3;
6260 begin
6261    Proc (A, A);
6262 end Block;
6263
6264 Block :
6265    declare
6266       A : Integer := 3;
6267    begin
6268       Proc (A, A);
6269    end Block;
6270 @end cartouche
6271 @end smallexample
6272
6273 @noindent
6274 The same alternative format is allowed for loops. For example, both of
6275 the following are permitted:
6276
6277 @smallexample @c ada
6278 @cartouche
6279 Clear : while J < 10 loop
6280    A (J) := 0;
6281 end loop Clear;
6282
6283 Clear :
6284    while J < 10 loop
6285       A (J) := 0;
6286    end loop Clear;
6287 @end cartouche
6288 @end smallexample
6289
6290 @item ^Lnnn^MAX_NESTING=nnn^
6291 @emph{Set maximum nesting level}
6292 The maximum level of nesting of constructs (including subprograms, loops,
6293 blocks, packages, and conditionals) may not exceed the given value
6294 @option{nnn}. A value of zero disconnects this style check.
6295
6296 @item ^m^LINE_LENGTH^
6297 @emph{Check maximum line length.}
6298 The length of source lines must not exceed 79 characters, including
6299 any trailing blanks. The value of 79 allows convenient display on an
6300 80 character wide device or window, allowing for possible special
6301 treatment of 80 character lines. Note that this count is of
6302 characters in the source text. This means that a tab character counts
6303 as one character in this count but a wide character sequence counts as
6304 a single character (however many bytes are needed in the encoding).
6305
6306 @item ^Mnnn^MAX_LENGTH=nnn^
6307 @emph{Set maximum line length.}
6308 The length of lines must not exceed the
6309 given value @option{nnn}. The maximum value that can be specified is 32767.
6310
6311 @item ^n^STANDARD_CASING^
6312 @emph{Check casing of entities in Standard.}
6313 Any identifier from Standard must be cased
6314 to match the presentation in the Ada Reference Manual (for example,
6315 @code{Integer} and @code{ASCII.NUL}).
6316
6317 @item ^N^NONE^
6318 @emph{Turn off all style checks}
6319 All style check options are turned off.
6320
6321 @item ^o^ORDERED_SUBPROGRAMS^
6322 @emph{Check order of subprogram bodies.}
6323 All subprogram bodies in a given scope
6324 (e.g.@: a package body) must be in alphabetical order. The ordering
6325 rule uses normal Ada rules for comparing strings, ignoring casing
6326 of letters, except that if there is a trailing numeric suffix, then
6327 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6328 before Junk10).
6329
6330 @item ^O^OVERRIDING_INDICATORS^
6331 @emph{Check that overriding subprograms are explicitly marked as such.}
6332 The declaration of a primitive operation of a type extension that overrides
6333 an inherited operation must carry an overriding indicator.
6334
6335 @item ^p^PRAGMA^
6336 @emph{Check pragma casing.}
6337 Pragma names must be written in mixed case, that is, the
6338 initial letter and any letter following an underscore must be uppercase.
6339 All other letters must be lowercase.
6340
6341 @item ^r^REFERENCES^
6342 @emph{Check references.}
6343 All identifier references must be cased in the same way as the
6344 corresponding declaration. No specific casing style is imposed on
6345 identifiers. The only requirement is for consistency of references
6346 with declarations.
6347
6348 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6349 @emph{Check no statements after THEN/ELSE.}
6350 No statements are allowed
6351 on the same line as a THEN or ELSE keyword following the
6352 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6353 and a special exception allows a pragma to appear after ELSE.
6354
6355 @item ^s^SPECS^
6356 @emph{Check separate specs.}
6357 Separate declarations (``specs'') are required for subprograms (a
6358 body is not allowed to serve as its own declaration). The only
6359 exception is that parameterless library level procedures are
6360 not required to have a separate declaration. This exception covers
6361 the most frequent form of main program procedures.
6362
6363 @item ^t^TOKEN^
6364 @emph{Check token spacing.}
6365 The following token spacing rules are enforced:
6366
6367 @itemize @bullet
6368
6369 @item
6370 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6371
6372 @item
6373 The token @code{=>} must be surrounded by spaces.
6374
6375 @item
6376 The token @code{<>} must be preceded by a space or a left parenthesis.
6377
6378 @item
6379 Binary operators other than @code{**} must be surrounded by spaces.
6380 There is no restriction on the layout of the @code{**} binary operator.
6381
6382 @item
6383 Colon must be surrounded by spaces.
6384
6385 @item
6386 Colon-equal (assignment, initialization) must be surrounded by spaces.
6387
6388 @item
6389 Comma must be the first non-blank character on the line, or be
6390 immediately preceded by a non-blank character, and must be followed
6391 by a space.
6392
6393 @item
6394 If the token preceding a left parenthesis ends with a letter or digit, then
6395 a space must separate the two tokens.
6396
6397 @item
6398 A right parenthesis must either be the first non-blank character on
6399 a line, or it must be preceded by a non-blank character.
6400
6401 @item
6402 A semicolon must not be preceded by a space, and must not be followed by
6403 a non-blank character.
6404
6405 @item
6406 A unary plus or minus may not be followed by a space.
6407
6408 @item
6409 A vertical bar must be surrounded by spaces.
6410 @end itemize
6411
6412 @item ^u^UNNECESSARY_BLANK_LINES^
6413 @emph{Check unnecessary blank lines.}
6414 Unnecessary blank lines are not allowed. A blank line is considered
6415 unnecessary if it appears at the end of the file, or if more than
6416 one blank line occurs in sequence.
6417
6418 @item ^x^XTRA_PARENS^
6419 @emph{Check extra parentheses.}
6420 Unnecessary extra level of parentheses (C-style) are not allowed
6421 around conditions in @code{if} statements, @code{while} statements and
6422 @code{exit} statements.
6423
6424 @item ^y^ALL_BUILTIN^
6425 @emph{Set all standard style check options}
6426 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6427 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6428 @option{-gnatyS}, @option{-gnatyLnnn},
6429 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6430
6431 @ifclear vms
6432 @item -
6433 @emph{Remove style check options}
6434 This causes any subsequent options in the string to act as canceling the
6435 corresponding style check option. To cancel maximum nesting level control,
6436 use @option{L} parameter witout any integer value after that, because any
6437 digit following @option{-} in the parameter string of the @option{-gnaty}
6438 option will be threated as canceling indentation check. The same is true
6439 for @option{M} parameter. @option{y} and @option{N} parameters are not
6440 allowed after @option{-}.
6441
6442 @item +
6443 This causes any subsequent options in the string to enable the corresponding
6444 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6445 if any.
6446 @end ifclear
6447
6448 @ifset vms
6449 @item NOxxx
6450 @emph{Removing style check options}
6451 If the name of a style check is preceded by @option{NO} then the corresponding
6452 style check is turned off. For example @option{NOCOMMENTS} turns off style
6453 checking for comments.
6454 @end ifset
6455 @end table
6456
6457 @noindent
6458 In the above rules, appearing in column one is always permitted, that is,
6459 counts as meeting either a requirement for a required preceding space,
6460 or as meeting a requirement for no preceding space.
6461
6462 Appearing at the end of a line is also always permitted, that is, counts
6463 as meeting either a requirement for a following space, or as meeting
6464 a requirement for no following space.
6465
6466 @noindent
6467 If any of these style rules is violated, a message is generated giving
6468 details on the violation. The initial characters of such messages are
6469 always ``@code{(style)}''. Note that these messages are treated as warning
6470 messages, so they normally do not prevent the generation of an object
6471 file. The @option{-gnatwe} switch can be used to treat warning messages,
6472 including style messages, as fatal errors.
6473
6474 The switch
6475 @ifclear vms
6476 @option{-gnaty} on its own (that is not
6477 followed by any letters or digits), then the effect is equivalent
6478 to the use of @option{-gnatyy}, as described above, that is all
6479 built-in standard style check options are enabled.
6480
6481 @end ifclear
6482 @ifset vms
6483 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6484 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6485 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6486 @end ifset
6487
6488
6489
6490 The switch
6491 @ifclear vms
6492 @option{-gnatyN}
6493 @end ifclear
6494 @ifset vms
6495 /STYLE_CHECKS=NONE
6496 @end ifset
6497 clears any previously set style checks.
6498
6499 @node Run-Time Checks
6500 @subsection Run-Time Checks
6501 @cindex Division by zero
6502 @cindex Access before elaboration
6503 @cindex Checks, division by zero
6504 @cindex Checks, access before elaboration
6505 @cindex Checks, stack overflow checking
6506
6507 @noindent
6508 By default, the following checks are suppressed: integer overflow
6509 checks, stack overflow checks, and checks for access before
6510 elaboration on subprogram calls. All other checks, including range
6511 checks and array bounds checks, are turned on by default. The
6512 following @command{gcc} switches refine this default behavior.
6513
6514 @table @option
6515 @c !sort!
6516 @item -gnatp
6517 @cindex @option{-gnatp} (@command{gcc})
6518 @cindex Suppressing checks
6519 @cindex Checks, suppressing
6520 @findex Suppress
6521 This switch causes the unit to be compiled
6522 as though @code{pragma Suppress (All_checks)}
6523 had been present in the source. Validity checks are also eliminated (in
6524 other words @option{-gnatp} also implies @option{-gnatVn}.
6525 Use this switch to improve the performance
6526 of the code at the expense of safety in the presence of invalid data or
6527 program bugs.
6528
6529 Note that when checks are suppressed, the compiler is allowed, but not
6530 required, to omit the checking code. If the run-time cost of the
6531 checking code is zero or near-zero, the compiler will generate it even
6532 if checks are suppressed. In particular, if the compiler can prove
6533 that a certain check will necessarily fail, it will generate code to
6534 do an unconditional ``raise'', even if checks are suppressed. The
6535 compiler warns in this case. Another case in which checks may not be
6536 eliminated is when they are embedded in certain run time routines such
6537 as math library routines.
6538
6539 Of course, run-time checks are omitted whenever the compiler can prove
6540 that they will not fail, whether or not checks are suppressed.
6541
6542 Note that if you suppress a check that would have failed, program
6543 execution is erroneous, which means the behavior is totally
6544 unpredictable. The program might crash, or print wrong answers, or
6545 do anything else. It might even do exactly what you wanted it to do
6546 (and then it might start failing mysteriously next week or next
6547 year). The compiler will generate code based on the assumption that
6548 the condition being checked is true, which can result in disaster if
6549 that assumption is wrong.
6550
6551 @item -gnato
6552 @cindex @option{-gnato} (@command{gcc})
6553 @cindex Overflow checks
6554 @cindex Check, overflow
6555 Enables overflow checking for integer operations.
6556 This causes GNAT to generate slower and larger executable
6557 programs by adding code to check for overflow (resulting in raising
6558 @code{Constraint_Error} as required by standard Ada
6559 semantics). These overflow checks correspond to situations in which
6560 the true value of the result of an operation may be outside the base
6561 range of the result type. The following example shows the distinction:
6562
6563 @smallexample @c ada
6564 X1 : Integer := "Integer'Last";
6565 X2 : Integer range 1 .. 5 := "5";
6566 X3 : Integer := "Integer'Last";
6567 X4 : Integer range 1 .. 5 := "5";
6568 F  : Float := "2.0E+20";
6569 @dots{}
6570 X1 := X1 + 1;
6571 X2 := X2 + 1;
6572 X3 := Integer (F);
6573 X4 := Integer (F);
6574 @end smallexample
6575
6576 @noindent
6577 Note that if explicit values are assigned at compile time, the
6578 compiler may be able to detect overflow at compile time, in which case
6579 no actual run-time checking code is required, and Constraint_Error
6580 will be raised unconditionally, with or without
6581 @option{-gnato}. That's why the assigned values in the above fragment
6582 are in quotes, the meaning is "assign a value not known to the
6583 compiler that happens to be equal to ...". The remaining discussion
6584 assumes that the compiler cannot detect the values at compile time.
6585
6586 Here the first addition results in a value that is outside the base range
6587 of Integer, and hence requires an overflow check for detection of the
6588 constraint error. Thus the first assignment to @code{X1} raises a
6589 @code{Constraint_Error} exception only if @option{-gnato} is set.
6590
6591 The second increment operation results in a violation of the explicit
6592 range constraint; such range checks are performed by default, and are
6593 unaffected by @option{-gnato}.
6594
6595 The two conversions of @code{F} both result in values that are outside
6596 the base range of type @code{Integer} and thus will raise
6597 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6598 The fact that the result of the second conversion is assigned to
6599 variable @code{X4} with a restricted range is irrelevant, since the problem
6600 is in the conversion, not the assignment.
6601
6602 Basically the rule is that in the default mode (@option{-gnato} not
6603 used), the generated code assures that all integer variables stay
6604 within their declared ranges, or within the base range if there is
6605 no declared range. This prevents any serious problems like indexes
6606 out of range for array operations.
6607
6608 What is not checked in default mode is an overflow that results in
6609 an in-range, but incorrect value. In the above example, the assignments
6610 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6611 range of the target variable, but the result is wrong in the sense that
6612 it is too large to be represented correctly. Typically the assignment
6613 to @code{X1} will result in wrap around to the largest negative number.
6614 The conversions of @code{F} will result in some @code{Integer} value
6615 and if that integer value is out of the @code{X4} range then the
6616 subsequent assignment would generate an exception.
6617
6618 @findex Machine_Overflows
6619 Note that the @option{-gnato} switch does not affect the code generated
6620 for any floating-point operations; it applies only to integer
6621 semantics).
6622 For floating-point, GNAT has the @code{Machine_Overflows}
6623 attribute set to @code{False} and the normal mode of operation is to
6624 generate IEEE NaN and infinite values on overflow or invalid operations
6625 (such as dividing 0.0 by 0.0).
6626
6627 The reason that we distinguish overflow checking from other kinds of
6628 range constraint checking is that a failure of an overflow check, unlike
6629 for example the failure of a range check, can result in an incorrect
6630 value, but cannot cause random memory destruction (like an out of range
6631 subscript), or a wild jump (from an out of range case value). Overflow
6632 checking is also quite expensive in time and space, since in general it
6633 requires the use of double length arithmetic.
6634
6635 Note again that @option{-gnato} is off by default, so overflow checking is
6636 not performed in default mode. This means that out of the box, with the
6637 default settings, GNAT does not do all the checks expected from the
6638 language description in the Ada Reference Manual. If you want all constraint
6639 checks to be performed, as described in this Manual, then you must
6640 explicitly use the -gnato switch either on the @command{gnatmake} or
6641 @command{gcc} command.
6642
6643 @item -gnatE
6644 @cindex @option{-gnatE} (@command{gcc})
6645 @cindex Elaboration checks
6646 @cindex Check, elaboration
6647 Enables dynamic checks for access-before-elaboration
6648 on subprogram calls and generic instantiations.
6649 Note that @option{-gnatE} is not necessary for safety, because in the
6650 default mode, GNAT ensures statically that the checks would not fail.
6651 For full details of the effect and use of this switch,
6652 @xref{Compiling Using gcc}.
6653
6654 @item -fstack-check
6655 @cindex @option{-fstack-check} (@command{gcc})
6656 @cindex Stack Overflow Checking
6657 @cindex Checks, stack overflow checking
6658 Activates stack overflow checking. For full details of the effect and use of
6659 this switch see @ref{Stack Overflow Checking}.
6660 @end table
6661
6662 @findex Unsuppress
6663 @noindent
6664 The setting of these switches only controls the default setting of the
6665 checks. You may modify them using either @code{Suppress} (to remove
6666 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6667 the program source.
6668
6669 @node Using gcc for Syntax Checking
6670 @subsection Using @command{gcc} for Syntax Checking
6671 @table @option
6672 @item -gnats
6673 @cindex @option{-gnats} (@command{gcc})
6674 @ifclear vms
6675
6676 @noindent
6677 The @code{s} stands for ``syntax''.
6678 @end ifclear
6679
6680 Run GNAT in syntax checking only mode. For
6681 example, the command
6682
6683 @smallexample
6684 $ gcc -c -gnats x.adb
6685 @end smallexample
6686
6687 @noindent
6688 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6689 series of files in a single command
6690 @ifclear vms
6691 , and can use wild cards to specify such a group of files.
6692 Note that you must specify the @option{-c} (compile
6693 only) flag in addition to the @option{-gnats} flag.
6694 @end ifclear
6695 .
6696 You may use other switches in conjunction with @option{-gnats}. In
6697 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6698 format of any generated error messages.
6699
6700 When the source file is empty or contains only empty lines and/or comments,
6701 the output is a warning:
6702
6703 @smallexample
6704 $ gcc -c -gnats -x ada toto.txt
6705 toto.txt:1:01: warning: empty file, contains no compilation units
6706 $
6707 @end smallexample
6708
6709 Otherwise, the output is simply the error messages, if any. No object file or
6710 ALI file is generated by a syntax-only compilation. Also, no units other
6711 than the one specified are accessed. For example, if a unit @code{X}
6712 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6713 check only mode does not access the source file containing unit
6714 @code{Y}.
6715
6716 @cindex Multiple units, syntax checking
6717 Normally, GNAT allows only a single unit in a source file. However, this
6718 restriction does not apply in syntax-check-only mode, and it is possible
6719 to check a file containing multiple compilation units concatenated
6720 together. This is primarily used by the @code{gnatchop} utility
6721 (@pxref{Renaming Files Using gnatchop}).
6722 @end table
6723
6724 @node Using gcc for Semantic Checking
6725 @subsection Using @command{gcc} for Semantic Checking
6726 @table @option
6727 @item -gnatc
6728 @cindex @option{-gnatc} (@command{gcc})
6729
6730 @ifclear vms
6731 @noindent
6732 The @code{c} stands for ``check''.
6733 @end ifclear
6734 Causes the compiler to operate in semantic check mode,
6735 with full checking for all illegalities specified in the
6736 Ada Reference Manual, but without generation of any object code
6737 (no object file is generated).
6738
6739 Because dependent files must be accessed, you must follow the GNAT
6740 semantic restrictions on file structuring to operate in this mode:
6741
6742 @itemize @bullet
6743 @item
6744 The needed source files must be accessible
6745 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6746
6747 @item
6748 Each file must contain only one compilation unit.
6749
6750 @item
6751 The file name and unit name must match (@pxref{File Naming Rules}).
6752 @end itemize
6753
6754 The output consists of error messages as appropriate. No object file is
6755 generated. An @file{ALI} file is generated for use in the context of
6756 cross-reference tools, but this file is marked as not being suitable
6757 for binding (since no object file is generated).
6758 The checking corresponds exactly to the notion of
6759 legality in the Ada Reference Manual.
6760
6761 Any unit can be compiled in semantics-checking-only mode, including
6762 units that would not normally be compiled (subunits,
6763 and specifications where a separate body is present).
6764 @end table
6765
6766 @node Compiling Different Versions of Ada
6767 @subsection Compiling Different Versions of Ada
6768
6769 @noindent
6770 The switches described in this section allow you to explicitly specify
6771 the version of the Ada language that your programs are written in.
6772 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6773 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6774 indicate Ada 83 compatibility mode.
6775
6776 @table @option
6777 @cindex Compatibility with Ada 83
6778
6779 @item -gnat83 (Ada 83 Compatibility Mode)
6780 @cindex @option{-gnat83} (@command{gcc})
6781 @cindex ACVC, Ada 83 tests
6782 @cindex Ada 83 mode
6783
6784 @noindent
6785 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6786 specifies that the program is to be compiled in Ada 83 mode. With
6787 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6788 semantics where this can be done easily.
6789 It is not possible to guarantee this switch does a perfect
6790 job; some subtle tests, such as are
6791 found in earlier ACVC tests (and that have been removed from the ACATS suite
6792 for Ada 95), might not compile correctly.
6793 Nevertheless, this switch may be useful in some circumstances, for example
6794 where, due to contractual reasons, existing code needs to be maintained
6795 using only Ada 83 features.
6796
6797 With few exceptions (most notably the need to use @code{<>} on
6798 @cindex Generic formal parameters
6799 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6800 reserved words, and the use of packages
6801 with optional bodies), it is not necessary to specify the
6802 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6803 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6804 a correct Ada 83 program is usually also a correct program
6805 in these later versions of the language standard.
6806 For further information, please refer to @ref{Compatibility and Porting Guide}.
6807
6808 @item -gnat95 (Ada 95 mode)
6809 @cindex @option{-gnat95} (@command{gcc})
6810 @cindex Ada 95 mode
6811
6812 @noindent
6813 This switch directs the compiler to implement the Ada 95 version of the
6814 language.
6815 Since Ada 95 is almost completely upwards
6816 compatible with Ada 83, Ada 83 programs may generally be compiled using
6817 this switch (see the description of the @option{-gnat83} switch for further
6818 information about Ada 83 mode).
6819 If an Ada 2005 program is compiled in Ada 95 mode,
6820 uses of the new Ada 2005 features will cause error
6821 messages or warnings.
6822
6823 This switch also can be used to cancel the effect of a previous
6824 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6825
6826 @item -gnat05 (Ada 2005 mode)
6827 @cindex @option{-gnat05} (@command{gcc})
6828 @cindex Ada 2005 mode
6829
6830 @noindent
6831 This switch directs the compiler to implement the Ada 2005 version of the
6832 language.
6833 Since Ada 2005 is almost completely upwards
6834 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6835 may generally be compiled using this switch (see the description of the
6836 @option{-gnat83} and @option{-gnat95} switches for further
6837 information).
6838
6839 For information about the approved ``Ada Issues'' that have been incorporated
6840 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6841 Included with GNAT releases is a file @file{features-ada0y} that describes
6842 the set of implemented Ada 2005 features.
6843 @end table
6844
6845
6846 @node Character Set Control
6847 @subsection Character Set Control
6848 @table @option
6849 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6850 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6851
6852 @noindent
6853 Normally GNAT recognizes the Latin-1 character set in source program
6854 identifiers, as described in the Ada Reference Manual.
6855 This switch causes
6856 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6857 single character ^^or word^ indicating the character set, as follows:
6858
6859 @table @code
6860 @item 1
6861 ISO 8859-1 (Latin-1) identifiers
6862
6863 @item 2
6864 ISO 8859-2 (Latin-2) letters allowed in identifiers
6865
6866 @item 3
6867 ISO 8859-3 (Latin-3) letters allowed in identifiers
6868
6869 @item 4
6870 ISO 8859-4 (Latin-4) letters allowed in identifiers
6871
6872 @item 5
6873 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6874
6875 @item 9
6876 ISO 8859-15 (Latin-9) letters allowed in identifiers
6877
6878 @item ^p^PC^
6879 IBM PC letters (code page 437) allowed in identifiers
6880
6881 @item ^8^PC850^
6882 IBM PC letters (code page 850) allowed in identifiers
6883
6884 @item ^f^FULL_UPPER^
6885 Full upper-half codes allowed in identifiers
6886
6887 @item ^n^NO_UPPER^
6888 No upper-half codes allowed in identifiers
6889
6890 @item ^w^WIDE^
6891 Wide-character codes (that is, codes greater than 255)
6892 allowed in identifiers
6893 @end table
6894
6895 @xref{Foreign Language Representation}, for full details on the
6896 implementation of these character sets.
6897
6898 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6899 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6900 Specify the method of encoding for wide characters.
6901 @var{e} is one of the following:
6902
6903 @table @code
6904
6905 @item ^h^HEX^
6906 Hex encoding (brackets coding also recognized)
6907
6908 @item ^u^UPPER^
6909 Upper half encoding (brackets encoding also recognized)
6910
6911 @item ^s^SHIFT_JIS^
6912 Shift/JIS encoding (brackets encoding also recognized)
6913
6914 @item ^e^EUC^
6915 EUC encoding (brackets encoding also recognized)
6916
6917 @item ^8^UTF8^
6918 UTF-8 encoding (brackets encoding also recognized)
6919
6920 @item ^b^BRACKETS^
6921 Brackets encoding only (default value)
6922 @end table
6923 For full details on these encoding
6924 methods see @ref{Wide Character Encodings}.
6925 Note that brackets coding is always accepted, even if one of the other
6926 options is specified, so for example @option{-gnatW8} specifies that both
6927 brackets and UTF-8 encodings will be recognized. The units that are
6928 with'ed directly or indirectly will be scanned using the specified
6929 representation scheme, and so if one of the non-brackets scheme is
6930 used, it must be used consistently throughout the program. However,
6931 since brackets encoding is always recognized, it may be conveniently
6932 used in standard libraries, allowing these libraries to be used with
6933 any of the available coding schemes.
6934 scheme.
6935
6936 If no @option{-gnatW?} parameter is present, then the default
6937 representation is normally Brackets encoding only. However, if the
6938 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6939 byte order mark or BOM for UTF-8), then these three characters are
6940 skipped and the default representation for the file is set to UTF-8.
6941
6942 Note that the wide character representation that is specified (explicitly
6943 or by default) for the main program also acts as the default encoding used
6944 for Wide_Text_IO files if not specifically overridden by a WCEM form
6945 parameter.
6946
6947 @end table
6948 @node File Naming Control
6949 @subsection File Naming Control
6950
6951 @table @option
6952 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6953 @cindex @option{-gnatk} (@command{gcc})
6954 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6955 1-999, indicates the maximum allowable length of a file name (not
6956 including the @file{.ads} or @file{.adb} extension). The default is not
6957 to enable file name krunching.
6958
6959 For the source file naming rules, @xref{File Naming Rules}.
6960 @end table
6961
6962 @node Subprogram Inlining Control
6963 @subsection Subprogram Inlining Control
6964
6965 @table @option
6966 @c !sort!
6967 @item -gnatn
6968 @cindex @option{-gnatn} (@command{gcc})
6969 @ifclear vms
6970 The @code{n} here is intended to suggest the first syllable of the
6971 word ``inline''.
6972 @end ifclear
6973 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6974 inlining to actually occur, optimization must be enabled. To enable
6975 inlining of subprograms specified by pragma @code{Inline},
6976 you must also specify this switch.
6977 In the absence of this switch, GNAT does not attempt
6978 inlining and does not need to access the bodies of
6979 subprograms for which @code{pragma Inline} is specified if they are not
6980 in the current unit.
6981
6982 If you specify this switch the compiler will access these bodies,
6983 creating an extra source dependency for the resulting object file, and
6984 where possible, the call will be inlined.
6985 For further details on when inlining is possible
6986 see @ref{Inlining of Subprograms}.
6987
6988 @item -gnatN
6989 @cindex @option{-gnatN} (@command{gcc})
6990 This switch activates front-end inlining which also
6991 generates additional dependencies.
6992
6993 When using a gcc-based back end (in practice this means using any version
6994 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6995 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6996 Historically front end inlining was more extensive than the gcc back end
6997 inlining, but that is no longer the case.
6998 @end table
6999
7000 @node Auxiliary Output Control
7001 @subsection Auxiliary Output Control
7002
7003 @table @option
7004 @item -gnatt
7005 @cindex @option{-gnatt} (@command{gcc})
7006 @cindex Writing internal trees
7007 @cindex Internal trees, writing to file
7008 Causes GNAT to write the internal tree for a unit to a file (with the
7009 extension @file{.adt}.
7010 This not normally required, but is used by separate analysis tools.
7011 Typically
7012 these tools do the necessary compilations automatically, so you should
7013 not have to specify this switch in normal operation.
7014 Note that the combination of switches @option{-gnatct}
7015 generates a tree in the form required by ASIS applications.
7016
7017 @item -gnatu
7018 @cindex @option{-gnatu} (@command{gcc})
7019 Print a list of units required by this compilation on @file{stdout}.
7020 The listing includes all units on which the unit being compiled depends
7021 either directly or indirectly.
7022
7023 @ifclear vms
7024 @item -pass-exit-codes
7025 @cindex @option{-pass-exit-codes} (@command{gcc})
7026 If this switch is not used, the exit code returned by @command{gcc} when
7027 compiling multiple files indicates whether all source files have
7028 been successfully used to generate object files or not.
7029
7030 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7031 exit status and allows an integrated development environment to better
7032 react to a compilation failure. Those exit status are:
7033
7034 @table @asis
7035 @item 5
7036 There was an error in at least one source file.
7037 @item 3
7038 At least one source file did not generate an object file.
7039 @item 2
7040 The compiler died unexpectedly (internal error for example).
7041 @item 0
7042 An object file has been generated for every source file.
7043 @end table
7044 @end ifclear
7045 @end table
7046
7047 @node Debugging Control
7048 @subsection Debugging Control
7049
7050 @table @option
7051 @c !sort!
7052 @cindex Debugging options
7053 @ifclear vms
7054 @item -gnatd@var{x}
7055 @cindex @option{-gnatd} (@command{gcc})
7056 Activate internal debugging switches. @var{x} is a letter or digit, or
7057 string of letters or digits, which specifies the type of debugging
7058 outputs desired. Normally these are used only for internal development
7059 or system debugging purposes. You can find full documentation for these
7060 switches in the body of the @code{Debug} unit in the compiler source
7061 file @file{debug.adb}.
7062 @end ifclear
7063
7064 @item -gnatG[=nn]
7065 @cindex @option{-gnatG} (@command{gcc})
7066 This switch causes the compiler to generate auxiliary output containing
7067 a pseudo-source listing of the generated expanded code. Like most Ada
7068 compilers, GNAT works by first transforming the high level Ada code into
7069 lower level constructs. For example, tasking operations are transformed
7070 into calls to the tasking run-time routines. A unique capability of GNAT
7071 is to list this expanded code in a form very close to normal Ada source.
7072 This is very useful in understanding the implications of various Ada
7073 usage on the efficiency of the generated code. There are many cases in
7074 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7075 generate a lot of run-time code. By using @option{-gnatG} you can identify
7076 these cases, and consider whether it may be desirable to modify the coding
7077 approach to improve efficiency.
7078
7079 The optional parameter @code{nn} if present after -gnatG specifies an
7080 alternative maximum line length that overrides the normal default of 72.
7081 This value is in the range 40-999999, values less than 40 being silently
7082 reset to 40. The equal sign is optional.
7083
7084 The format of the output is very similar to standard Ada source, and is
7085 easily understood by an Ada programmer. The following special syntactic
7086 additions correspond to low level features used in the generated code that
7087 do not have any exact analogies in pure Ada source form. The following
7088 is a partial list of these special constructions. See the spec
7089 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7090
7091 If the switch @option{-gnatL} is used in conjunction with
7092 @cindex @option{-gnatL} (@command{gcc})
7093 @option{-gnatG}, then the original source lines are interspersed
7094 in the expanded source (as comment lines with the original line number).
7095
7096 @table @code
7097 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7098 Shows the storage pool being used for an allocator.
7099
7100 @item at end @var{procedure-name};
7101 Shows the finalization (cleanup) procedure for a scope.
7102
7103 @item (if @var{expr} then @var{expr} else @var{expr})
7104 Conditional expression equivalent to the @code{x?y:z} construction in C.
7105
7106 @item @var{target}^^^(@var{source})
7107 A conversion with floating-point truncation instead of rounding.
7108
7109 @item @var{target}?(@var{source})
7110 A conversion that bypasses normal Ada semantic checking. In particular
7111 enumeration types and fixed-point types are treated simply as integers.
7112
7113 @item @var{target}?^^^(@var{source})
7114 Combines the above two cases.
7115
7116 @item @var{x} #/ @var{y}
7117 @itemx @var{x} #mod @var{y}
7118 @itemx @var{x} #* @var{y}
7119 @itemx @var{x} #rem @var{y}
7120 A division or multiplication of fixed-point values which are treated as
7121 integers without any kind of scaling.
7122
7123 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7124 Shows the storage pool associated with a @code{free} statement.
7125
7126 @item [subtype or type declaration]
7127 Used to list an equivalent declaration for an internally generated
7128 type that is referenced elsewhere in the listing.
7129
7130 @item freeze @var{type-name} @ovar{actions}
7131 Shows the point at which @var{type-name} is frozen, with possible
7132 associated actions to be performed at the freeze point.
7133
7134 @item reference @var{itype}
7135 Reference (and hence definition) to internal type @var{itype}.
7136
7137 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7138 Intrinsic function call.
7139
7140 @item @var{label-name} : label
7141 Declaration of label @var{labelname}.
7142
7143 @item #$ @var{subprogram-name}
7144 An implicit call to a run-time support routine
7145 (to meet the requirement of H.3.1(9) in a
7146 convenient manner).
7147
7148 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7149 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7150 @var{expr}, but handled more efficiently).
7151
7152 @item [constraint_error]
7153 Raise the @code{Constraint_Error} exception.
7154
7155 @item @var{expression}'reference
7156 A pointer to the result of evaluating @var{expression}.
7157
7158 @item @var{target-type}!(@var{source-expression})
7159 An unchecked conversion of @var{source-expression} to @var{target-type}.
7160
7161 @item [@var{numerator}/@var{denominator}]
7162 Used to represent internal real literals (that) have no exact
7163 representation in base 2-16 (for example, the result of compile time
7164 evaluation of the expression 1.0/27.0).
7165 @end table
7166
7167 @item -gnatD[=nn]
7168 @cindex @option{-gnatD} (@command{gcc})
7169 When used in conjunction with @option{-gnatG}, this switch causes
7170 the expanded source, as described above for
7171 @option{-gnatG} to be written to files with names
7172 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7173 instead of to the standard output file. For
7174 example, if the source file name is @file{hello.adb}, then a file
7175 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7176 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7177 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7178 you to do source level debugging using the generated code which is
7179 sometimes useful for complex code, for example to find out exactly
7180 which part of a complex construction raised an exception. This switch
7181 also suppress generation of cross-reference information (see
7182 @option{-gnatx}) since otherwise the cross-reference information
7183 would refer to the @file{^.dg^.DG^} file, which would cause
7184 confusion since this is not the original source file.
7185
7186 Note that @option{-gnatD} actually implies @option{-gnatG}
7187 automatically, so it is not necessary to give both options.
7188 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7189
7190 If the switch @option{-gnatL} is used in conjunction with
7191 @cindex @option{-gnatL} (@command{gcc})
7192 @option{-gnatDG}, then the original source lines are interspersed
7193 in the expanded source (as comment lines with the original line number).
7194
7195 The optional parameter @code{nn} if present after -gnatD specifies an
7196 alternative maximum line length that overrides the normal default of 72.
7197 This value is in the range 40-999999, values less than 40 being silently
7198 reset to 40. The equal sign is optional.
7199
7200 @item -gnatr
7201 @cindex @option{-gnatr} (@command{gcc})
7202 @cindex pragma Restrictions
7203 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7204 so that violation of restrictions causes warnings rather than illegalities.
7205 This is useful during the development process when new restrictions are added
7206 or investigated. The switch also causes pragma Profile to be treated as
7207 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7208 restriction warnings rather than restrictions.
7209
7210 @ifclear vms
7211 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7212 @cindex @option{-gnatR} (@command{gcc})
7213 This switch controls output from the compiler of a listing showing
7214 representation information for declared types and objects. For
7215 @option{-gnatR0}, no information is output (equivalent to omitting
7216 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7217 so @option{-gnatR} with no parameter has the same effect), size and alignment
7218 information is listed for declared array and record types. For
7219 @option{-gnatR2}, size and alignment information is listed for all
7220 declared types and objects. Finally @option{-gnatR3} includes symbolic
7221 expressions for values that are computed at run time for
7222 variant records. These symbolic expressions have a mostly obvious
7223 format with #n being used to represent the value of the n'th
7224 discriminant. See source files @file{repinfo.ads/adb} in the
7225 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7226 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7227 the output is to a file with the name @file{^file.rep^file_REP^} where
7228 file is the name of the corresponding source file.
7229 @end ifclear
7230 @ifset vms
7231 @item /REPRESENTATION_INFO
7232 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7233 This qualifier controls output from the compiler of a listing showing
7234 representation information for declared types and objects. For
7235 @option{/REPRESENTATION_INFO=NONE}, no information is output
7236 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7237 @option{/REPRESENTATION_INFO} without option is equivalent to
7238 @option{/REPRESENTATION_INFO=ARRAYS}.
7239 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7240 information is listed for declared array and record types. For
7241 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7242 is listed for all expression information for values that are computed
7243 at run time for variant records. These symbolic expressions have a mostly
7244 obvious format with #n being used to represent the value of the n'th
7245 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7246 @code{GNAT} sources for full details on the format of
7247 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7248 If _FILE is added at the end of an option
7249 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7250 then the output is to a file with the name @file{file_REP} where
7251 file is the name of the corresponding source file.
7252 @end ifset
7253 Note that it is possible for record components to have zero size. In
7254 this case, the component clause uses an obvious extension of permitted
7255 Ada syntax, for example @code{at 0 range 0 .. -1}.
7256
7257 Representation information requires that code be generated (since it is the
7258 code generator that lays out complex data structures). If an attempt is made
7259 to output representation information when no code is generated, for example
7260 when a subunit is compiled on its own, then no information can be generated
7261 and the compiler outputs a message to this effect.
7262
7263 @item -gnatS
7264 @cindex @option{-gnatS} (@command{gcc})
7265 The use of the switch @option{-gnatS} for an
7266 Ada compilation will cause the compiler to output a
7267 representation of package Standard in a form very
7268 close to standard Ada. It is not quite possible to
7269 do this entirely in standard Ada (since new
7270 numeric base types cannot be created in standard
7271 Ada), but the output is easily
7272 readable to any Ada programmer, and is useful to
7273 determine the characteristics of target dependent
7274 types in package Standard.
7275
7276 @item -gnatx
7277 @cindex @option{-gnatx} (@command{gcc})
7278 Normally the compiler generates full cross-referencing information in
7279 the @file{ALI} file. This information is used by a number of tools,
7280 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7281 suppresses this information. This saves some space and may slightly
7282 speed up compilation, but means that these tools cannot be used.
7283 @end table
7284
7285 @node Exception Handling Control
7286 @subsection Exception Handling Control
7287
7288 @noindent
7289 GNAT uses two methods for handling exceptions at run-time. The
7290 @code{setjmp/longjmp} method saves the context when entering
7291 a frame with an exception handler. Then when an exception is
7292 raised, the context can be restored immediately, without the
7293 need for tracing stack frames. This method provides very fast
7294 exception propagation, but introduces significant overhead for
7295 the use of exception handlers, even if no exception is raised.
7296
7297 The other approach is called ``zero cost'' exception handling.
7298 With this method, the compiler builds static tables to describe
7299 the exception ranges. No dynamic code is required when entering
7300 a frame containing an exception handler. When an exception is
7301 raised, the tables are used to control a back trace of the
7302 subprogram invocation stack to locate the required exception
7303 handler. This method has considerably poorer performance for
7304 the propagation of exceptions, but there is no overhead for
7305 exception handlers if no exception is raised. Note that in this
7306 mode and in the context of mixed Ada and C/C++ programming,
7307 to propagate an exception through a C/C++ code, the C/C++ code
7308 must be compiled with the @option{-funwind-tables} GCC's
7309 option.
7310
7311 The following switches may be used to control which of the
7312 two exception handling methods is used.
7313
7314 @table @option
7315 @c !sort!
7316
7317 @item --RTS=sjlj
7318 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7319 This switch causes the setjmp/longjmp run-time (when available) to be used
7320 for exception handling. If the default
7321 mechanism for the target is zero cost exceptions, then
7322 this switch can be used to modify this default, and must be
7323 used for all units in the partition.
7324 This option is rarely used. One case in which it may be
7325 advantageous is if you have an application where exception
7326 raising is common and the overall performance of the
7327 application is improved by favoring exception propagation.
7328
7329 @item --RTS=zcx
7330 @cindex @option{--RTS=zcx} (@command{gnatmake})
7331 @cindex Zero Cost Exceptions
7332 This switch causes the zero cost approach to be used
7333 for exception handling. If this is the default mechanism for the
7334 target (see below), then this switch is unneeded. If the default
7335 mechanism for the target is setjmp/longjmp exceptions, then
7336 this switch can be used to modify this default, and must be
7337 used for all units in the partition.
7338 This option can only be used if the zero cost approach
7339 is available for the target in use, otherwise it will generate an error.
7340 @end table
7341
7342 @noindent
7343 The same option @option{--RTS} must be used both for @command{gcc}
7344 and @command{gnatbind}. Passing this option to @command{gnatmake}
7345 (@pxref{Switches for gnatmake}) will ensure the required consistency
7346 through the compilation and binding steps.
7347
7348 @node Units to Sources Mapping Files
7349 @subsection Units to Sources Mapping Files
7350
7351 @table @option
7352
7353 @item -gnatem^^=^@var{path}
7354 @cindex @option{-gnatem} (@command{gcc})
7355 A mapping file is a way to communicate to the compiler two mappings:
7356 from unit names to file names (without any directory information) and from
7357 file names to path names (with full directory information). These mappings
7358 are used by the compiler to short-circuit the path search.
7359
7360 The use of mapping files is not required for correct operation of the
7361 compiler, but mapping files can improve efficiency, particularly when
7362 sources are read over a slow network connection. In normal operation,
7363 you need not be concerned with the format or use of mapping files,
7364 and the @option{-gnatem} switch is not a switch that you would use
7365 explicitly. it is intended only for use by automatic tools such as
7366 @command{gnatmake} running under the project file facility. The
7367 description here of the format of mapping files is provided
7368 for completeness and for possible use by other tools.
7369
7370 A mapping file is a sequence of sets of three lines. In each set,
7371 the first line is the unit name, in lower case, with ``@code{%s}''
7372 appended for
7373 specs and ``@code{%b}'' appended for bodies; the second line is the
7374 file name; and the third line is the path name.
7375
7376 Example:
7377 @smallexample
7378    main%b
7379    main.2.ada
7380    /gnat/project1/sources/main.2.ada
7381 @end smallexample
7382
7383 When the switch @option{-gnatem} is specified, the compiler will create
7384 in memory the two mappings from the specified file. If there is any problem
7385 (nonexistent file, truncated file or duplicate entries), no mapping will
7386 be created.
7387
7388 Several @option{-gnatem} switches may be specified; however, only the last
7389 one on the command line will be taken into account.
7390
7391 When using a project file, @command{gnatmake} create a temporary mapping file
7392 and communicates it to the compiler using this switch.
7393
7394 @end table
7395
7396 @node Integrated Preprocessing
7397 @subsection Integrated Preprocessing
7398
7399 @noindent
7400 GNAT sources may be preprocessed immediately before compilation.
7401 In this case, the actual
7402 text of the source is not the text of the source file, but is derived from it
7403 through a process called preprocessing. Integrated preprocessing is specified
7404 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7405 indicates, through a text file, the preprocessing data to be used.
7406 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7407
7408 @noindent
7409 Note that when integrated preprocessing is used, the output from the
7410 preprocessor is not written to any external file. Instead it is passed
7411 internally to the compiler. If you need to preserve the result of
7412 preprocessing in a file, then you should use @command{gnatprep}
7413 to perform the desired preprocessing in stand-alone mode.
7414
7415 @noindent
7416 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7417 used when Integrated Preprocessing is used. The reason is that preprocessing
7418 with another Preprocessing Data file without changing the sources will
7419 not trigger recompilation without this switch.
7420
7421 @noindent
7422 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7423 always trigger recompilation for sources that are preprocessed,
7424 because @command{gnatmake} cannot compute the checksum of the source after
7425 preprocessing.
7426
7427 @noindent
7428 The actual preprocessing function is described in details in section
7429 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7430 preprocessing is triggered and parameterized.
7431
7432 @table @code
7433
7434 @item -gnatep=@var{file}
7435 @cindex @option{-gnatep} (@command{gcc})
7436 This switch indicates to the compiler the file name (without directory
7437 information) of the preprocessor data file to use. The preprocessor data file
7438 should be found in the source directories.
7439
7440 @noindent
7441 A preprocessing data file is a text file with significant lines indicating
7442 how should be preprocessed either a specific source or all sources not
7443 mentioned in other lines. A significant line is a nonempty, non-comment line.
7444 Comments are similar to Ada comments.
7445
7446 @noindent
7447 Each significant line starts with either a literal string or the character '*'.
7448 A literal string is the file name (without directory information) of the source
7449 to preprocess. A character '*' indicates the preprocessing for all the sources
7450 that are not specified explicitly on other lines (order of the lines is not
7451 significant). It is an error to have two lines with the same file name or two
7452 lines starting with the character '*'.
7453
7454 @noindent
7455 After the file name or the character '*', another optional literal string
7456 indicating the file name of the definition file to be used for preprocessing
7457 (@pxref{Form of Definitions File}). The definition files are found by the
7458 compiler in one of the source directories. In some cases, when compiling
7459 a source in a directory other than the current directory, if the definition
7460 file is in the current directory, it may be necessary to add the current
7461 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7462 the compiler would not find the definition file.
7463
7464 @noindent
7465 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7466 be found. Those ^switches^switches^ are:
7467
7468 @table @code
7469
7470 @item -b
7471 Causes both preprocessor lines and the lines deleted by
7472 preprocessing to be replaced by blank lines, preserving the line number.
7473 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7474 it cancels the effect of @option{-c}.
7475
7476 @item -c
7477 Causes both preprocessor lines and the lines deleted
7478 by preprocessing to be retained as comments marked
7479 with the special string ``@code{--! }''.
7480
7481 @item -Dsymbol=value
7482 Define or redefine a symbol, associated with value. A symbol is an Ada
7483 identifier, or an Ada reserved word, with the exception of @code{if},
7484 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7485 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7486 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7487 same name defined in a definition file.
7488
7489 @item -s
7490 Causes a sorted list of symbol names and values to be
7491 listed on the standard output file.
7492
7493 @item -u
7494 Causes undefined symbols to be treated as having the value @code{FALSE}
7495 in the context
7496 of a preprocessor test. In the absence of this option, an undefined symbol in
7497 a @code{#if} or @code{#elsif} test will be treated as an error.
7498
7499 @end table
7500
7501 @noindent
7502 Examples of valid lines in a preprocessor data file:
7503
7504 @smallexample
7505   "toto.adb"  "prep.def" -u
7506   --  preprocess "toto.adb", using definition file "prep.def",
7507   --  undefined symbol are False.
7508
7509   * -c -DVERSION=V101
7510   --  preprocess all other sources without a definition file;
7511   --  suppressed lined are commented; symbol VERSION has the value V101.
7512
7513   "titi.adb" "prep2.def" -s
7514   --  preprocess "titi.adb", using definition file "prep2.def";
7515   --  list all symbols with their values.
7516 @end smallexample
7517
7518 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7519 @cindex @option{-gnateD} (@command{gcc})
7520 Define or redefine a preprocessing symbol, associated with value. If no value
7521 is given on the command line, then the value of the symbol is @code{True}.
7522 A symbol is an identifier, following normal Ada (case-insensitive)
7523 rules for its syntax, and value is any sequence (including an empty sequence)
7524 of characters from the set (letters, digits, period, underline).
7525 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7526 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7527
7528 @noindent
7529 A symbol declared with this ^switch^switch^ on the command line replaces a
7530 symbol with the same name either in a definition file or specified with a
7531 ^switch^switch^ -D in the preprocessor data file.
7532
7533 @noindent
7534 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7535
7536 @item -gnateG
7537 When integrated preprocessing is performed and the preprocessor modifies
7538 the source text, write the result of this preprocessing into a file
7539 <source>^.prep^_prep^.
7540
7541 @end table
7542
7543 @node Code Generation Control
7544 @subsection Code Generation Control
7545
7546 @noindent
7547
7548 The GCC technology provides a wide range of target dependent
7549 @option{-m} switches for controlling
7550 details of code generation with respect to different versions of
7551 architectures. This includes variations in instruction sets (e.g.@:
7552 different members of the power pc family), and different requirements
7553 for optimal arrangement of instructions (e.g.@: different members of
7554 the x86 family). The list of available @option{-m} switches may be
7555 found in the GCC documentation.
7556
7557 Use of these @option{-m} switches may in some cases result in improved
7558 code performance.
7559
7560 The GNAT Pro technology is tested and qualified without any
7561 @option{-m} switches,
7562 so generally the most reliable approach is to avoid the use of these
7563 switches. However, we generally expect most of these switches to work
7564 successfully with GNAT Pro, and many customers have reported successful
7565 use of these options.
7566
7567 Our general advice is to avoid the use of @option{-m} switches unless
7568 special needs lead to requirements in this area. In particular,
7569 there is no point in using @option{-m} switches to improve performance
7570 unless you actually see a performance improvement.
7571
7572 @ifset vms
7573 @node Return Codes
7574 @subsection Return Codes
7575 @cindex Return Codes
7576 @cindex @option{/RETURN_CODES=VMS}
7577
7578 @noindent
7579 On VMS, GNAT compiled programs return POSIX-style codes by default,
7580 e.g.@: @option{/RETURN_CODES=POSIX}.
7581
7582 To enable VMS style return codes, use GNAT BIND and LINK with the option
7583 @option{/RETURN_CODES=VMS}. For example:
7584
7585 @smallexample
7586 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7587 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7588 @end smallexample
7589
7590 @noindent
7591 Programs built with /RETURN_CODES=VMS are suitable to be called in
7592 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7593 are suitable for spawning with appropriate GNAT RTL routines.
7594
7595 @end ifset
7596
7597 @node Search Paths and the Run-Time Library (RTL)
7598 @section Search Paths and the Run-Time Library (RTL)
7599
7600 @noindent
7601 With the GNAT source-based library system, the compiler must be able to
7602 find source files for units that are needed by the unit being compiled.
7603 Search paths are used to guide this process.
7604
7605 The compiler compiles one source file whose name must be given
7606 explicitly on the command line. In other words, no searching is done
7607 for this file. To find all other source files that are needed (the most
7608 common being the specs of units), the compiler examines the following
7609 directories, in the following order:
7610
7611 @enumerate
7612 @item
7613 The directory containing the source file of the main unit being compiled
7614 (the file name on the command line).
7615
7616 @item
7617 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7618 @command{gcc} command line, in the order given.
7619
7620 @item
7621 @findex ADA_PRJ_INCLUDE_FILE
7622 Each of the directories listed in the text file whose name is given
7623 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7624
7625 @noindent
7626 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7627 driver when project files are used. It should not normally be set
7628 by other means.
7629
7630 @item
7631 @findex ADA_INCLUDE_PATH
7632 Each of the directories listed in the value of the
7633 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7634 @ifclear vms
7635 Construct this value
7636 exactly as the @env{PATH} environment variable: a list of directory
7637 names separated by colons (semicolons when working with the NT version).
7638 @end ifclear
7639 @ifset vms
7640 Normally, define this value as a logical name containing a comma separated
7641 list of directory names.
7642
7643 This variable can also be defined by means of an environment string
7644 (an argument to the HP C exec* set of functions).
7645
7646 Logical Name:
7647 @smallexample
7648 DEFINE ANOTHER_PATH FOO:[BAG]
7649 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7650 @end smallexample
7651
7652 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7653 first, followed by the standard Ada
7654 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7655 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7656 (Text_IO, Sequential_IO, etc)
7657 instead of the standard Ada packages. Thus, in order to get the standard Ada
7658 packages by default, ADA_INCLUDE_PATH must be redefined.
7659 @end ifset
7660
7661 @item
7662 The content of the @file{ada_source_path} file which is part of the GNAT
7663 installation tree and is used to store standard libraries such as the
7664 GNAT Run Time Library (RTL) source files.
7665 @ifclear vms
7666 @ref{Installing a library}
7667 @end ifclear
7668 @end enumerate
7669
7670 @noindent
7671 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7672 inhibits the use of the directory
7673 containing the source file named in the command line. You can still
7674 have this directory on your search path, but in this case it must be
7675 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7676
7677 Specifying the switch @option{-nostdinc}
7678 inhibits the search of the default location for the GNAT Run Time
7679 Library (RTL) source files.
7680
7681 The compiler outputs its object files and ALI files in the current
7682 working directory.
7683 @ifclear vms
7684 Caution: The object file can be redirected with the @option{-o} switch;
7685 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7686 so the @file{ALI} file will not go to the right place. Therefore, you should
7687 avoid using the @option{-o} switch.
7688 @end ifclear
7689
7690 @findex System.IO
7691 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7692 children make up the GNAT RTL, together with the simple @code{System.IO}
7693 package used in the @code{"Hello World"} example. The sources for these units
7694 are needed by the compiler and are kept together in one directory. Not
7695 all of the bodies are needed, but all of the sources are kept together
7696 anyway. In a normal installation, you need not specify these directory
7697 names when compiling or binding. Either the environment variables or
7698 the built-in defaults cause these files to be found.
7699
7700 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7701 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7702 consisting of child units of @code{GNAT}. This is a collection of generally
7703 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7704 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7705
7706 Besides simplifying access to the RTL, a major use of search paths is
7707 in compiling sources from multiple directories. This can make
7708 development environments much more flexible.
7709
7710 @node Order of Compilation Issues
7711 @section Order of Compilation Issues
7712
7713 @noindent
7714 If, in our earlier example, there was a spec for the @code{hello}
7715 procedure, it would be contained in the file @file{hello.ads}; yet this
7716 file would not have to be explicitly compiled. This is the result of the
7717 model we chose to implement library management. Some of the consequences
7718 of this model are as follows:
7719
7720 @itemize @bullet
7721 @item
7722 There is no point in compiling specs (except for package
7723 specs with no bodies) because these are compiled as needed by clients. If
7724 you attempt a useless compilation, you will receive an error message.
7725 It is also useless to compile subunits because they are compiled as needed
7726 by the parent.
7727
7728 @item
7729 There are no order of compilation requirements: performing a
7730 compilation never obsoletes anything. The only way you can obsolete
7731 something and require recompilations is to modify one of the
7732 source files on which it depends.
7733
7734 @item
7735 There is no library as such, apart from the ALI files
7736 (@pxref{The Ada Library Information Files}, for information on the format
7737 of these files). For now we find it convenient to create separate ALI files,
7738 but eventually the information therein may be incorporated into the object
7739 file directly.
7740
7741 @item
7742 When you compile a unit, the source files for the specs of all units
7743 that it @code{with}'s, all its subunits, and the bodies of any generics it
7744 instantiates must be available (reachable by the search-paths mechanism
7745 described above), or you will receive a fatal error message.
7746 @end itemize
7747
7748 @node Examples
7749 @section Examples
7750
7751 @noindent
7752 The following are some typical Ada compilation command line examples:
7753
7754 @table @code
7755 @item $ gcc -c xyz.adb
7756 Compile body in file @file{xyz.adb} with all default options.
7757
7758 @ifclear vms
7759 @item $ gcc -c -O2 -gnata xyz-def.adb
7760 @end ifclear
7761 @ifset vms
7762 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7763 @end ifset
7764
7765 Compile the child unit package in file @file{xyz-def.adb} with extensive
7766 optimizations, and pragma @code{Assert}/@code{Debug} statements
7767 enabled.
7768
7769 @item $ gcc -c -gnatc abc-def.adb
7770 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7771 mode.
7772 @end table
7773
7774 @node Binding Using gnatbind
7775 @chapter Binding Using @code{gnatbind}
7776 @findex gnatbind
7777
7778 @menu
7779 * Running gnatbind::
7780 * Switches for gnatbind::
7781 * Command-Line Access::
7782 * Search Paths for gnatbind::
7783 * Examples of gnatbind Usage::
7784 @end menu
7785
7786 @noindent
7787 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7788 to bind compiled GNAT objects.
7789
7790 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7791 driver (see @ref{The GNAT Driver and Project Files}).
7792
7793 The @code{gnatbind} program performs four separate functions:
7794
7795 @enumerate
7796 @item
7797 Checks that a program is consistent, in accordance with the rules in
7798 Chapter 10 of the Ada Reference Manual. In particular, error
7799 messages are generated if a program uses inconsistent versions of a
7800 given unit.
7801
7802 @item
7803 Checks that an acceptable order of elaboration exists for the program
7804 and issues an error message if it cannot find an order of elaboration
7805 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7806
7807 @item
7808 Generates a main program incorporating the given elaboration order.
7809 This program is a small Ada package (body and spec) that
7810 must be subsequently compiled
7811 using the GNAT compiler. The necessary compilation step is usually
7812 performed automatically by @command{gnatlink}. The two most important
7813 functions of this program
7814 are to call the elaboration routines of units in an appropriate order
7815 and to call the main program.
7816
7817 @item
7818 Determines the set of object files required by the given main program.
7819 This information is output in the forms of comments in the generated program,
7820 to be read by the @command{gnatlink} utility used to link the Ada application.
7821 @end enumerate
7822
7823 @node Running gnatbind
7824 @section Running @code{gnatbind}
7825
7826 @noindent
7827 The form of the @code{gnatbind} command is
7828
7829 @smallexample
7830 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7831 @end smallexample
7832
7833 @noindent
7834 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7835 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7836 package in two files whose names are
7837 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7838 For example, if given the
7839 parameter @file{hello.ali}, for a main program contained in file
7840 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7841 and @file{b~hello.adb}.
7842
7843 When doing consistency checking, the binder takes into consideration
7844 any source files it can locate. For example, if the binder determines
7845 that the given main program requires the package @code{Pack}, whose
7846 @file{.ALI}
7847 file is @file{pack.ali} and whose corresponding source spec file is
7848 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7849 (using the same search path conventions as previously described for the
7850 @command{gcc} command). If it can locate this source file, it checks that
7851 the time stamps
7852 or source checksums of the source and its references to in @file{ALI} files
7853 match. In other words, any @file{ALI} files that mentions this spec must have
7854 resulted from compiling this version of the source file (or in the case
7855 where the source checksums match, a version close enough that the
7856 difference does not matter).
7857
7858 @cindex Source files, use by binder
7859 The effect of this consistency checking, which includes source files, is
7860 that the binder ensures that the program is consistent with the latest
7861 version of the source files that can be located at bind time. Editing a
7862 source file without compiling files that depend on the source file cause
7863 error messages to be generated by the binder.
7864
7865 For example, suppose you have a main program @file{hello.adb} and a
7866 package @code{P}, from file @file{p.ads} and you perform the following
7867 steps:
7868
7869 @enumerate
7870 @item
7871 Enter @code{gcc -c hello.adb} to compile the main program.
7872
7873 @item
7874 Enter @code{gcc -c p.ads} to compile package @code{P}.
7875
7876 @item
7877 Edit file @file{p.ads}.
7878
7879 @item
7880 Enter @code{gnatbind hello}.
7881 @end enumerate
7882
7883 @noindent
7884 At this point, the file @file{p.ali} contains an out-of-date time stamp
7885 because the file @file{p.ads} has been edited. The attempt at binding
7886 fails, and the binder generates the following error messages:
7887
7888 @smallexample
7889 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7890 error: "p.ads" has been modified and must be recompiled
7891 @end smallexample
7892
7893 @noindent
7894 Now both files must be recompiled as indicated, and then the bind can
7895 succeed, generating a main program. You need not normally be concerned
7896 with the contents of this file, but for reference purposes a sample
7897 binder output file is given in @ref{Example of Binder Output File}.
7898
7899 In most normal usage, the default mode of @command{gnatbind} which is to
7900 generate the main package in Ada, as described in the previous section.
7901 In particular, this means that any Ada programmer can read and understand
7902 the generated main program. It can also be debugged just like any other
7903 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7904 @command{gnatbind} and @command{gnatlink}.
7905
7906 However for some purposes it may be convenient to generate the main
7907 program in C rather than Ada. This may for example be helpful when you
7908 are generating a mixed language program with the main program in C. The
7909 GNAT compiler itself is an example.
7910 The use of the @option{^-C^/BIND_FILE=C^} switch
7911 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7912 be generated in C (and compiled using the gnu C compiler).
7913
7914 @node Switches for gnatbind
7915 @section Switches for @command{gnatbind}
7916
7917 @noindent
7918 The following switches are available with @code{gnatbind}; details will
7919 be presented in subsequent sections.
7920
7921 @menu
7922 * Consistency-Checking Modes::
7923 * Binder Error Message Control::
7924 * Elaboration Control::
7925 * Output Control::
7926 * Binding with Non-Ada Main Programs::
7927 * Binding Programs with No Main Subprogram::
7928 @end menu
7929
7930 @table @option
7931 @c !sort!
7932
7933 @item --version
7934 @cindex @option{--version} @command{gnatbind}
7935 Display Copyright and version, then exit disregarding all other options.
7936
7937 @item --help
7938 @cindex @option{--help} @command{gnatbind}
7939 If @option{--version} was not used, display usage, then exit disregarding
7940 all other options.
7941
7942 @item -a
7943 @cindex @option{-a} @command{gnatbind}
7944 Indicates that, if supported by the platform, the adainit procedure should
7945 be treated as an initialisation routine by the linker (a constructor). This
7946 is intended to be used by the Project Manager to automatically initialize
7947 shared Stand-Alone Libraries.
7948
7949 @item ^-aO^/OBJECT_SEARCH^
7950 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7951 Specify directory to be searched for ALI files.
7952
7953 @item ^-aI^/SOURCE_SEARCH^
7954 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7955 Specify directory to be searched for source file.
7956
7957 @item ^-A^/BIND_FILE=ADA^
7958 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7959 Generate binder program in Ada (default)
7960
7961 @item ^-b^/REPORT_ERRORS=BRIEF^
7962 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7963 Generate brief messages to @file{stderr} even if verbose mode set.
7964
7965 @item ^-c^/NOOUTPUT^
7966 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7967 Check only, no generation of binder output file.
7968
7969 @item ^-C^/BIND_FILE=C^
7970 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7971 Generate binder program in C
7972
7973 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7974 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7975 This switch can be used to change the default task stack size value
7976 to a specified size @var{nn}, which is expressed in bytes by default, or
7977 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7978 with @var{m}.
7979 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7980 in effect, to completing all task specs with
7981 @smallexample @c ada
7982    pragma Storage_Size (nn);
7983 @end smallexample
7984 When they do not already have such a pragma.
7985
7986 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7987 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7988 This switch can be used to change the default secondary stack size value
7989 to a specified size @var{nn}, which is expressed in bytes by default, or
7990 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7991 with @var{m}.
7992
7993 The secondary stack is used to deal with functions that return a variable
7994 sized result, for example a function returning an unconstrained
7995 String. There are two ways in which this secondary stack is allocated.
7996
7997 For most targets, the secondary stack is growing on demand and is allocated
7998 as a chain of blocks in the heap. The -D option is not very
7999 relevant. It only give some control over the size of the allocated
8000 blocks (whose size is the minimum of the default secondary stack size value,
8001 and the actual size needed for the current allocation request).
8002
8003 For certain targets, notably VxWorks 653,
8004 the secondary stack is allocated by carving off a fixed ratio chunk of the
8005 primary task stack. The -D option is used to define the
8006 size of the environment task's secondary stack.
8007
8008 @item ^-e^/ELABORATION_DEPENDENCIES^
8009 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8010 Output complete list of elaboration-order dependencies.
8011
8012 @item ^-E^/STORE_TRACEBACKS^
8013 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8014 Store tracebacks in exception occurrences when the target supports it.
8015 This is the default with the zero cost exception mechanism.
8016 @ignore
8017 @c The following may get moved to an appendix
8018 This option is currently supported on the following targets:
8019 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8020 @end ignore
8021 See also the packages @code{GNAT.Traceback} and
8022 @code{GNAT.Traceback.Symbolic} for more information.
8023 @ifclear vms
8024 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8025 @command{gcc} option.
8026 @end ifclear
8027
8028 @item ^-F^/FORCE_ELABS_FLAGS^
8029 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8030 Force the checks of elaboration flags. @command{gnatbind} does not normally
8031 generate checks of elaboration flags for the main executable, except when
8032 a Stand-Alone Library is used. However, there are cases when this cannot be
8033 detected by gnatbind. An example is importing an interface of a Stand-Alone
8034 Library through a pragma Import and only specifying through a linker switch
8035 this Stand-Alone Library. This switch is used to guarantee that elaboration
8036 flag checks are generated.
8037
8038 @item ^-h^/HELP^
8039 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8040 Output usage (help) information
8041
8042 @item ^-I^/SEARCH^
8043 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8044 Specify directory to be searched for source and ALI files.
8045
8046 @item ^-I-^/NOCURRENT_DIRECTORY^
8047 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8048 Do not look for sources in the current directory where @code{gnatbind} was
8049 invoked, and do not look for ALI files in the directory containing the
8050 ALI file named in the @code{gnatbind} command line.
8051
8052 @item ^-l^/ORDER_OF_ELABORATION^
8053 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8054 Output chosen elaboration order.
8055
8056 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8057 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8058 Bind the units for library building. In this case the adainit and
8059 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8060 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8061 ^@var{xxx}final^@var{XXX}FINAL^.
8062 Implies ^-n^/NOCOMPILE^.
8063 @ifclear vms
8064 (@xref{GNAT and Libraries}, for more details.)
8065 @end ifclear
8066 @ifset vms
8067 On OpenVMS, these init and final procedures are exported in uppercase
8068 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8069 the init procedure will be "TOTOINIT" and the exported name of the final
8070 procedure will be "TOTOFINAL".
8071 @end ifset
8072
8073 @item ^-Mxyz^/RENAME_MAIN=xyz^
8074 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8075 Rename generated main program from main to xyz. This option is
8076 supported on cross environments only.
8077
8078 @item ^-m^/ERROR_LIMIT=^@var{n}
8079 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8080 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8081 in the range 1..999999. The default value if no switch is
8082 given is 9999. If the number of warnings reaches this limit, then a
8083 message is output and further warnings are suppressed, the bind
8084 continues in this case. If the number of errors reaches this
8085 limit, then a message is output and the bind is abandoned.
8086 A value of zero means that no limit is enforced. The equal
8087 sign is optional.
8088
8089 @ifset unw
8090 Furthermore, under Windows, the sources pointed to by the libraries path
8091 set in the registry are not searched for.
8092 @end ifset
8093
8094 @item ^-n^/NOMAIN^
8095 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8096 No main program.
8097
8098 @item -nostdinc
8099 @cindex @option{-nostdinc} (@command{gnatbind})
8100 Do not look for sources in the system default directory.
8101
8102 @item -nostdlib
8103 @cindex @option{-nostdlib} (@command{gnatbind})
8104 Do not look for library files in the system default directory.
8105
8106 @item --RTS=@var{rts-path}
8107 @cindex @option{--RTS} (@code{gnatbind})
8108 Specifies the default location of the runtime library. Same meaning as the
8109 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8110
8111 @item ^-o ^/OUTPUT=^@var{file}
8112 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8113 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8114 Note that if this option is used, then linking must be done manually,
8115 gnatlink cannot be used.
8116
8117 @item ^-O^/OBJECT_LIST^
8118 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8119 Output object list.
8120
8121 @item ^-p^/PESSIMISTIC_ELABORATION^
8122 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8123 Pessimistic (worst-case) elaboration order
8124
8125 @item ^-R^-R^
8126 @cindex @option{^-R^-R^} (@command{gnatbind})
8127 Output closure source list.
8128
8129 @item ^-s^/READ_SOURCES=ALL^
8130 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8131 Require all source files to be present.
8132
8133 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8134 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8135 Specifies the value to be used when detecting uninitialized scalar
8136 objects with pragma Initialize_Scalars.
8137 The @var{xxx} ^string specified with the switch^option^ may be either
8138 @itemize @bullet
8139 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8140 @item ``@option{^lo^LOW^}'' for the lowest possible value
8141 @item ``@option{^hi^HIGH^}'' for the highest possible value
8142 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8143 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8144 @end itemize
8145
8146 In addition, you can specify @option{-Sev} to indicate that the value is
8147 to be set at run time. In this case, the program will look for an environment
8148 @cindex GNAT_INIT_SCALARS
8149 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8150 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8151 If no environment variable is found, or if it does not have a valid value,
8152 then the default is @option{in} (invalid values).
8153
8154 @ifclear vms
8155 @item -static
8156 @cindex @option{-static} (@code{gnatbind})
8157 Link against a static GNAT run time.
8158
8159 @item -shared
8160 @cindex @option{-shared} (@code{gnatbind})
8161 Link against a shared GNAT run time when available.
8162 @end ifclear
8163
8164 @item ^-t^/NOTIME_STAMP_CHECK^
8165 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8166 Tolerate time stamp and other consistency errors
8167
8168 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8169 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8170 Set the time slice value to @var{n} milliseconds. If the system supports
8171 the specification of a specific time slice value, then the indicated value
8172 is used. If the system does not support specific time slice values, but
8173 does support some general notion of round-robin scheduling, then any
8174 nonzero value will activate round-robin scheduling.
8175
8176 A value of zero is treated specially. It turns off time
8177 slicing, and in addition, indicates to the tasking run time that the
8178 semantics should match as closely as possible the Annex D
8179 requirements of the Ada RM, and in particular sets the default
8180 scheduling policy to @code{FIFO_Within_Priorities}.
8181
8182 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8183 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8184 Enable dynamic stack usage, with @var{n} results stored and displayed
8185 at program termination. A result is generated when a task
8186 terminates. Results that can't be stored are displayed on the fly, at
8187 task termination. This option is currently not supported on Itanium
8188 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8189
8190 @item ^-v^/REPORT_ERRORS=VERBOSE^
8191 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8192 Verbose mode. Write error messages, header, summary output to
8193 @file{stdout}.
8194
8195 @ifclear vms
8196 @item -w@var{x}
8197 @cindex @option{-w} (@code{gnatbind})
8198 Warning mode (@var{x}=s/e for suppress/treat as error)
8199 @end ifclear
8200
8201 @ifset vms
8202 @item /WARNINGS=NORMAL
8203 @cindex @option{/WARNINGS} (@code{gnatbind})
8204 Normal warnings mode. Warnings are issued but ignored
8205
8206 @item /WARNINGS=SUPPRESS
8207 @cindex @option{/WARNINGS} (@code{gnatbind})
8208 All warning messages are suppressed
8209
8210 @item /WARNINGS=ERROR
8211 @cindex @option{/WARNINGS} (@code{gnatbind})
8212 Warning messages are treated as fatal errors
8213 @end ifset
8214
8215 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8216 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8217 Override default wide character encoding for standard Text_IO files.
8218
8219 @item ^-x^/READ_SOURCES=NONE^
8220 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8221 Exclude source files (check object consistency only).
8222
8223 @ifset vms
8224 @item /READ_SOURCES=AVAILABLE
8225 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8226 Default mode, in which sources are checked for consistency only if
8227 they are available.
8228 @end ifset
8229
8230 @item ^-y^/ENABLE_LEAP_SECONDS^
8231 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8232 Enable leap seconds support in @code{Ada.Calendar} and its children.
8233
8234 @item ^-z^/ZERO_MAIN^
8235 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8236 No main subprogram.
8237 @end table
8238
8239 @ifclear vms
8240 @noindent
8241 You may obtain this listing of switches by running @code{gnatbind} with
8242 no arguments.
8243 @end ifclear
8244
8245 @node Consistency-Checking Modes
8246 @subsection Consistency-Checking Modes
8247
8248 @noindent
8249 As described earlier, by default @code{gnatbind} checks
8250 that object files are consistent with one another and are consistent
8251 with any source files it can locate. The following switches control binder
8252 access to sources.
8253
8254 @table @option
8255 @c !sort!
8256 @item ^-s^/READ_SOURCES=ALL^
8257 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8258 Require source files to be present. In this mode, the binder must be
8259 able to locate all source files that are referenced, in order to check
8260 their consistency. In normal mode, if a source file cannot be located it
8261 is simply ignored. If you specify this switch, a missing source
8262 file is an error.
8263
8264 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8265 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8266 Override default wide character encoding for standard Text_IO files.
8267 Normally the default wide character encoding method used for standard
8268 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8269 the main source input (see description of switch
8270 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8271 use of this switch for the binder (which has the same set of
8272 possible arguments) overrides this default as specified.
8273
8274 @item ^-x^/READ_SOURCES=NONE^
8275 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8276 Exclude source files. In this mode, the binder only checks that ALI
8277 files are consistent with one another. Source files are not accessed.
8278 The binder runs faster in this mode, and there is still a guarantee that
8279 the resulting program is self-consistent.
8280 If a source file has been edited since it was last compiled, and you
8281 specify this switch, the binder will not detect that the object
8282 file is out of date with respect to the source file. Note that this is the
8283 mode that is automatically used by @command{gnatmake} because in this
8284 case the checking against sources has already been performed by
8285 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8286
8287 @ifset vms
8288 @item /READ_SOURCES=AVAILABLE
8289 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8290 This is the default mode in which source files are checked if they are
8291 available, and ignored if they are not available.
8292 @end ifset
8293 @end table
8294
8295 @node Binder Error Message Control
8296 @subsection Binder Error Message Control
8297
8298 @noindent
8299 The following switches provide control over the generation of error
8300 messages from the binder:
8301
8302 @table @option
8303 @c !sort!
8304 @item ^-v^/REPORT_ERRORS=VERBOSE^
8305 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8306 Verbose mode. In the normal mode, brief error messages are generated to
8307 @file{stderr}. If this switch is present, a header is written
8308 to @file{stdout} and any error messages are directed to @file{stdout}.
8309 All that is written to @file{stderr} is a brief summary message.
8310
8311 @item ^-b^/REPORT_ERRORS=BRIEF^
8312 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8313 Generate brief error messages to @file{stderr} even if verbose mode is
8314 specified. This is relevant only when used with the
8315 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8316
8317 @ifclear vms
8318 @item -m@var{n}
8319 @cindex @option{-m} (@code{gnatbind})
8320 Limits the number of error messages to @var{n}, a decimal integer in the
8321 range 1-999. The binder terminates immediately if this limit is reached.
8322
8323 @item -M@var{xxx}
8324 @cindex @option{-M} (@code{gnatbind})
8325 Renames the generated main program from @code{main} to @code{xxx}.
8326 This is useful in the case of some cross-building environments, where
8327 the actual main program is separate from the one generated
8328 by @code{gnatbind}.
8329 @end ifclear
8330
8331 @item ^-ws^/WARNINGS=SUPPRESS^
8332 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8333 @cindex Warnings
8334 Suppress all warning messages.
8335
8336 @item ^-we^/WARNINGS=ERROR^
8337 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8338 Treat any warning messages as fatal errors.
8339
8340 @ifset vms
8341 @item /WARNINGS=NORMAL
8342 Standard mode with warnings generated, but warnings do not get treated
8343 as errors.
8344 @end ifset
8345
8346 @item ^-t^/NOTIME_STAMP_CHECK^
8347 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8348 @cindex Time stamp checks, in binder
8349 @cindex Binder consistency checks
8350 @cindex Consistency checks, in binder
8351 The binder performs a number of consistency checks including:
8352
8353 @itemize @bullet
8354 @item
8355 Check that time stamps of a given source unit are consistent
8356 @item
8357 Check that checksums of a given source unit are consistent
8358 @item
8359 Check that consistent versions of @code{GNAT} were used for compilation
8360 @item
8361 Check consistency of configuration pragmas as required
8362 @end itemize
8363
8364 @noindent
8365 Normally failure of such checks, in accordance with the consistency
8366 requirements of the Ada Reference Manual, causes error messages to be
8367 generated which abort the binder and prevent the output of a binder
8368 file and subsequent link to obtain an executable.
8369
8370 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8371 into warnings, so that
8372 binding and linking can continue to completion even in the presence of such
8373 errors. The result may be a failed link (due to missing symbols), or a
8374 non-functional executable which has undefined semantics.
8375 @emph{This means that
8376 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8377 with extreme care.}
8378 @end table
8379
8380 @node Elaboration Control
8381 @subsection Elaboration Control
8382
8383 @noindent
8384 The following switches provide additional control over the elaboration
8385 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8386
8387 @table @option
8388 @item ^-p^/PESSIMISTIC_ELABORATION^
8389 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8390 Normally the binder attempts to choose an elaboration order that is
8391 likely to minimize the likelihood of an elaboration order error resulting
8392 in raising a @code{Program_Error} exception. This switch reverses the
8393 action of the binder, and requests that it deliberately choose an order
8394 that is likely to maximize the likelihood of an elaboration error.
8395 This is useful in ensuring portability and avoiding dependence on
8396 accidental fortuitous elaboration ordering.
8397
8398 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8399 switch if dynamic
8400 elaboration checking is used (@option{-gnatE} switch used for compilation).
8401 This is because in the default static elaboration mode, all necessary
8402 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8403 These implicit pragmas are still respected by the binder in
8404 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8405 safe elaboration order is assured.
8406 @end table
8407
8408 @node Output Control
8409 @subsection Output Control
8410
8411 @noindent
8412 The following switches allow additional control over the output
8413 generated by the binder.
8414
8415 @table @option
8416 @c !sort!
8417
8418 @item ^-A^/BIND_FILE=ADA^
8419 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8420 Generate binder program in Ada (default). The binder program is named
8421 @file{b~@var{mainprog}.adb} by default. This can be changed with
8422 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8423
8424 @item ^-c^/NOOUTPUT^
8425 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8426 Check only. Do not generate the binder output file. In this mode the
8427 binder performs all error checks but does not generate an output file.
8428
8429 @item ^-C^/BIND_FILE=C^
8430 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8431 Generate binder program in C. The binder program is named
8432 @file{b_@var{mainprog}.c}.
8433 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8434 option.
8435
8436 @item ^-e^/ELABORATION_DEPENDENCIES^
8437 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8438 Output complete list of elaboration-order dependencies, showing the
8439 reason for each dependency. This output can be rather extensive but may
8440 be useful in diagnosing problems with elaboration order. The output is
8441 written to @file{stdout}.
8442
8443 @item ^-h^/HELP^
8444 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8445 Output usage information. The output is written to @file{stdout}.
8446
8447 @item ^-K^/LINKER_OPTION_LIST^
8448 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8449 Output linker options to @file{stdout}. Includes library search paths,
8450 contents of pragmas Ident and Linker_Options, and libraries added
8451 by @code{gnatbind}.
8452
8453 @item ^-l^/ORDER_OF_ELABORATION^
8454 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8455 Output chosen elaboration order. The output is written to @file{stdout}.
8456
8457 @item ^-O^/OBJECT_LIST^
8458 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8459 Output full names of all the object files that must be linked to provide
8460 the Ada component of the program. The output is written to @file{stdout}.
8461 This list includes the files explicitly supplied and referenced by the user
8462 as well as implicitly referenced run-time unit files. The latter are
8463 omitted if the corresponding units reside in shared libraries. The
8464 directory names for the run-time units depend on the system configuration.
8465
8466 @item ^-o ^/OUTPUT=^@var{file}
8467 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8468 Set name of output file to @var{file} instead of the normal
8469 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8470 binder generated body filename. In C mode you would normally give
8471 @var{file} an extension of @file{.c} because it will be a C source program.
8472 Note that if this option is used, then linking must be done manually.
8473 It is not possible to use gnatlink in this case, since it cannot locate
8474 the binder file.
8475
8476 @item ^-r^/RESTRICTION_LIST^
8477 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8478 Generate list of @code{pragma Restrictions} that could be applied to
8479 the current unit. This is useful for code audit purposes, and also may
8480 be used to improve code generation in some cases.
8481
8482 @end table
8483
8484 @node Binding with Non-Ada Main Programs
8485 @subsection Binding with Non-Ada Main Programs
8486
8487 @noindent
8488 In our description so far we have assumed that the main
8489 program is in Ada, and that the task of the binder is to generate a
8490 corresponding function @code{main} that invokes this Ada main
8491 program. GNAT also supports the building of executable programs where
8492 the main program is not in Ada, but some of the called routines are
8493 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8494 The following switch is used in this situation:
8495
8496 @table @option
8497 @item ^-n^/NOMAIN^
8498 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8499 No main program. The main program is not in Ada.
8500 @end table
8501
8502 @noindent
8503 In this case, most of the functions of the binder are still required,
8504 but instead of generating a main program, the binder generates a file
8505 containing the following callable routines:
8506
8507 @table @code
8508 @item adainit
8509 @findex adainit
8510 You must call this routine to initialize the Ada part of the program by
8511 calling the necessary elaboration routines. A call to @code{adainit} is
8512 required before the first call to an Ada subprogram.
8513
8514 Note that it is assumed that the basic execution environment must be setup
8515 to be appropriate for Ada execution at the point where the first Ada
8516 subprogram is called. In particular, if the Ada code will do any
8517 floating-point operations, then the FPU must be setup in an appropriate
8518 manner. For the case of the x86, for example, full precision mode is
8519 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8520 that the FPU is in the right state.
8521
8522 @item adafinal
8523 @findex adafinal
8524 You must call this routine to perform any library-level finalization
8525 required by the Ada subprograms. A call to @code{adafinal} is required
8526 after the last call to an Ada subprogram, and before the program
8527 terminates.
8528 @end table
8529
8530 @noindent
8531 If the @option{^-n^/NOMAIN^} switch
8532 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8533 @cindex Binder, multiple input files
8534 is given, more than one ALI file may appear on
8535 the command line for @code{gnatbind}. The normal @dfn{closure}
8536 calculation is performed for each of the specified units. Calculating
8537 the closure means finding out the set of units involved by tracing
8538 @code{with} references. The reason it is necessary to be able to
8539 specify more than one ALI file is that a given program may invoke two or
8540 more quite separate groups of Ada units.
8541
8542 The binder takes the name of its output file from the last specified ALI
8543 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8544 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8545 The output is an Ada unit in source form that can
8546 be compiled with GNAT unless the -C switch is used in which case the
8547 output is a C source file, which must be compiled using the C compiler.
8548 This compilation occurs automatically as part of the @command{gnatlink}
8549 processing.
8550
8551 Currently the GNAT run time requires a FPU using 80 bits mode
8552 precision. Under targets where this is not the default it is required to
8553 call GNAT.Float_Control.Reset before using floating point numbers (this
8554 include float computation, float input and output) in the Ada code. A
8555 side effect is that this could be the wrong mode for the foreign code
8556 where floating point computation could be broken after this call.
8557
8558 @node Binding Programs with No Main Subprogram
8559 @subsection Binding Programs with No Main Subprogram
8560
8561 @noindent
8562 It is possible to have an Ada program which does not have a main
8563 subprogram. This program will call the elaboration routines of all the
8564 packages, then the finalization routines.
8565
8566 The following switch is used to bind programs organized in this manner:
8567
8568 @table @option
8569 @item ^-z^/ZERO_MAIN^
8570 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8571 Normally the binder checks that the unit name given on the command line
8572 corresponds to a suitable main subprogram. When this switch is used,
8573 a list of ALI files can be given, and the execution of the program
8574 consists of elaboration of these units in an appropriate order. Note
8575 that the default wide character encoding method for standard Text_IO
8576 files is always set to Brackets if this switch is set (you can use
8577 the binder switch
8578 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8579 @end table
8580
8581 @node Command-Line Access
8582 @section Command-Line Access
8583
8584 @noindent
8585 The package @code{Ada.Command_Line} provides access to the command-line
8586 arguments and program name. In order for this interface to operate
8587 correctly, the two variables
8588
8589 @smallexample
8590 @group
8591 int gnat_argc;
8592 char **gnat_argv;
8593 @end group
8594 @end smallexample
8595
8596 @noindent
8597 @findex gnat_argv
8598 @findex gnat_argc
8599 are declared in one of the GNAT library routines. These variables must
8600 be set from the actual @code{argc} and @code{argv} values passed to the
8601 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8602 generates the C main program to automatically set these variables.
8603 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8604 set these variables. If they are not set, the procedures in
8605 @code{Ada.Command_Line} will not be available, and any attempt to use
8606 them will raise @code{Constraint_Error}. If command line access is
8607 required, your main program must set @code{gnat_argc} and
8608 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8609 it.
8610
8611 @node Search Paths for gnatbind
8612 @section Search Paths for @code{gnatbind}
8613
8614 @noindent
8615 The binder takes the name of an ALI file as its argument and needs to
8616 locate source files as well as other ALI files to verify object consistency.
8617
8618 For source files, it follows exactly the same search rules as @command{gcc}
8619 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8620 directories searched are:
8621
8622 @enumerate
8623 @item
8624 The directory containing the ALI file named in the command line, unless
8625 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8626
8627 @item
8628 All directories specified by @option{^-I^/SEARCH^}
8629 switches on the @code{gnatbind}
8630 command line, in the order given.
8631
8632 @item
8633 @findex ADA_PRJ_OBJECTS_FILE
8634 Each of the directories listed in the text file whose name is given
8635 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8636
8637 @noindent
8638 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8639 driver when project files are used. It should not normally be set
8640 by other means.
8641
8642 @item
8643 @findex ADA_OBJECTS_PATH
8644 Each of the directories listed in the value of the
8645 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8646 @ifset unw
8647 Construct this value
8648 exactly as the @env{PATH} environment variable: a list of directory
8649 names separated by colons (semicolons when working with the NT version
8650 of GNAT).
8651 @end ifset
8652 @ifset vms
8653 Normally, define this value as a logical name containing a comma separated
8654 list of directory names.
8655
8656 This variable can also be defined by means of an environment string
8657 (an argument to the HP C exec* set of functions).
8658
8659 Logical Name:
8660 @smallexample
8661 DEFINE ANOTHER_PATH FOO:[BAG]
8662 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8663 @end smallexample
8664
8665 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8666 first, followed by the standard Ada
8667 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8668 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8669 (Text_IO, Sequential_IO, etc)
8670 instead of the standard Ada packages. Thus, in order to get the standard Ada
8671 packages by default, ADA_OBJECTS_PATH must be redefined.
8672 @end ifset
8673
8674 @item
8675 The content of the @file{ada_object_path} file which is part of the GNAT
8676 installation tree and is used to store standard libraries such as the
8677 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8678 specified.
8679 @ifclear vms
8680 @ref{Installing a library}
8681 @end ifclear
8682 @end enumerate
8683
8684 @noindent
8685 In the binder the switch @option{^-I^/SEARCH^}
8686 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8687 is used to specify both source and
8688 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8689 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8690 instead if you want to specify
8691 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8692 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8693 if you want to specify library paths
8694 only. This means that for the binder
8695 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8696 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8697 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8698 The binder generates the bind file (a C language source file) in the
8699 current working directory.
8700
8701 @findex Ada
8702 @findex System
8703 @findex Interfaces
8704 @findex GNAT
8705 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8706 children make up the GNAT Run-Time Library, together with the package
8707 GNAT and its children, which contain a set of useful additional
8708 library functions provided by GNAT. The sources for these units are
8709 needed by the compiler and are kept together in one directory. The ALI
8710 files and object files generated by compiling the RTL are needed by the
8711 binder and the linker and are kept together in one directory, typically
8712 different from the directory containing the sources. In a normal
8713 installation, you need not specify these directory names when compiling
8714 or binding. Either the environment variables or the built-in defaults
8715 cause these files to be found.
8716
8717 Besides simplifying access to the RTL, a major use of search paths is
8718 in compiling sources from multiple directories. This can make
8719 development environments much more flexible.
8720
8721 @node Examples of gnatbind Usage
8722 @section Examples of @code{gnatbind} Usage
8723
8724 @noindent
8725 This section contains a number of examples of using the GNAT binding
8726 utility @code{gnatbind}.
8727
8728 @table @code
8729 @item gnatbind hello
8730 The main program @code{Hello} (source program in @file{hello.adb}) is
8731 bound using the standard switch settings. The generated main program is
8732 @file{b~hello.adb}. This is the normal, default use of the binder.
8733
8734 @ifclear vms
8735 @item gnatbind hello -o mainprog.adb
8736 @end ifclear
8737 @ifset vms
8738 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8739 @end ifset
8740 The main program @code{Hello} (source program in @file{hello.adb}) is
8741 bound using the standard switch settings. The generated main program is
8742 @file{mainprog.adb} with the associated spec in
8743 @file{mainprog.ads}. Note that you must specify the body here not the
8744 spec, in the case where the output is in Ada. Note that if this option
8745 is used, then linking must be done manually, since gnatlink will not
8746 be able to find the generated file.
8747
8748 @ifclear vms
8749 @item gnatbind main -C -o mainprog.c -x
8750 @end ifclear
8751 @ifset vms
8752 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8753 @end ifset
8754 The main program @code{Main} (source program in
8755 @file{main.adb}) is bound, excluding source files from the
8756 consistency checking, generating
8757 the file @file{mainprog.c}.
8758
8759 @ifclear vms
8760 @item gnatbind -x main_program -C -o mainprog.c
8761 This command is exactly the same as the previous example. Switches may
8762 appear anywhere in the command line, and single letter switches may be
8763 combined into a single switch.
8764 @end ifclear
8765
8766 @ifclear vms
8767 @item gnatbind -n math dbase -C -o ada-control.c
8768 @end ifclear
8769 @ifset vms
8770 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8771 @end ifset
8772 The main program is in a language other than Ada, but calls to
8773 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8774 to @code{gnatbind} generates the file @file{ada-control.c} containing
8775 the @code{adainit} and @code{adafinal} routines to be called before and
8776 after accessing the Ada units.
8777 @end table
8778
8779 @c ------------------------------------
8780 @node Linking Using gnatlink
8781 @chapter Linking Using @command{gnatlink}
8782 @c ------------------------------------
8783 @findex gnatlink
8784
8785 @noindent
8786 This chapter discusses @command{gnatlink}, a tool that links
8787 an Ada program and builds an executable file. This utility
8788 invokes the system linker ^(via the @command{gcc} command)^^
8789 with a correct list of object files and library references.
8790 @command{gnatlink} automatically determines the list of files and
8791 references for the Ada part of a program. It uses the binder file
8792 generated by the @command{gnatbind} to determine this list.
8793
8794 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8795 driver (see @ref{The GNAT Driver and Project Files}).
8796
8797 @menu
8798 * Running gnatlink::
8799 * Switches for gnatlink::
8800 @end menu
8801
8802 @node Running gnatlink
8803 @section Running @command{gnatlink}
8804
8805 @noindent
8806 The form of the @command{gnatlink} command is
8807
8808 @smallexample
8809 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8810            @ovar{non-Ada objects} @ovar{linker options}
8811 @end smallexample
8812
8813 @noindent
8814 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8815 non-Ada objects
8816 or linker options) may be in any order, provided that no non-Ada object may
8817 be mistaken for a main @file{ALI} file.
8818 Any file name @file{F} without the @file{.ali}
8819 extension will be taken as the main @file{ALI} file if a file exists
8820 whose name is the concatenation of @file{F} and @file{.ali}.
8821
8822 @noindent
8823 @file{@var{mainprog}.ali} references the ALI file of the main program.
8824 The @file{.ali} extension of this file can be omitted. From this
8825 reference, @command{gnatlink} locates the corresponding binder file
8826 @file{b~@var{mainprog}.adb} and, using the information in this file along
8827 with the list of non-Ada objects and linker options, constructs a
8828 linker command file to create the executable.
8829
8830 The arguments other than the @command{gnatlink} switches and the main
8831 @file{ALI} file are passed to the linker uninterpreted.
8832 They typically include the names of
8833 object files for units written in other languages than Ada and any library
8834 references required to resolve references in any of these foreign language
8835 units, or in @code{Import} pragmas in any Ada units.
8836
8837 @var{linker options} is an optional list of linker specific
8838 switches.
8839 The default linker called by gnatlink is @command{gcc} which in
8840 turn calls the appropriate system linker.
8841 Standard options for the linker such as @option{-lmy_lib} or
8842 @option{-Ldir} can be added as is.
8843 For options that are not recognized by
8844 @command{gcc} as linker options, use the @command{gcc} switches
8845 @option{-Xlinker} or @option{-Wl,}.
8846 Refer to the GCC documentation for
8847 details. Here is an example showing how to generate a linker map:
8848
8849 @smallexample
8850 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8851 @end smallexample
8852
8853 Using @var{linker options} it is possible to set the program stack and
8854 heap size.
8855 @ifset unw
8856 See @ref{Setting Stack Size from gnatlink} and
8857 @ref{Setting Heap Size from gnatlink}.
8858 @end ifset
8859
8860 @command{gnatlink} determines the list of objects required by the Ada
8861 program and prepends them to the list of objects passed to the linker.
8862 @command{gnatlink} also gathers any arguments set by the use of
8863 @code{pragma Linker_Options} and adds them to the list of arguments
8864 presented to the linker.
8865
8866 @ifset vms
8867 @command{gnatlink} accepts the following types of extra files on the command
8868 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8869 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8870 handled according to their extension.
8871 @end ifset
8872
8873 @node Switches for gnatlink
8874 @section Switches for @command{gnatlink}
8875
8876 @noindent
8877 The following switches are available with the @command{gnatlink} utility:
8878
8879 @table @option
8880 @c !sort!
8881
8882 @item --version
8883 @cindex @option{--version} @command{gnatlink}
8884 Display Copyright and version, then exit disregarding all other options.
8885
8886 @item --help
8887 @cindex @option{--help} @command{gnatlink}
8888 If @option{--version} was not used, display usage, then exit disregarding
8889 all other options.
8890
8891 @item ^-A^/BIND_FILE=ADA^
8892 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8893 The binder has generated code in Ada. This is the default.
8894
8895 @item ^-C^/BIND_FILE=C^
8896 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8897 If instead of generating a file in Ada, the binder has generated one in
8898 C, then the linker needs to know about it. Use this switch to signal
8899 to @command{gnatlink} that the binder has generated C code rather than
8900 Ada code.
8901
8902 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8903 @cindex Command line length
8904 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8905 On some targets, the command line length is limited, and @command{gnatlink}
8906 will generate a separate file for the linker if the list of object files
8907 is too long.
8908 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8909 to be generated even if
8910 the limit is not exceeded. This is useful in some cases to deal with
8911 special situations where the command line length is exceeded.
8912
8913 @item ^-g^/DEBUG^
8914 @cindex Debugging information, including
8915 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8916 The option to include debugging information causes the Ada bind file (in
8917 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8918 @option{^-g^/DEBUG^}.
8919 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8920 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8921 Without @option{^-g^/DEBUG^}, the binder removes these files by
8922 default. The same procedure apply if a C bind file was generated using
8923 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8924 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8925
8926 @item ^-n^/NOCOMPILE^
8927 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8928 Do not compile the file generated by the binder. This may be used when
8929 a link is rerun with different options, but there is no need to recompile
8930 the binder file.
8931
8932 @item ^-v^/VERBOSE^
8933 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8934 Causes additional information to be output, including a full list of the
8935 included object files. This switch option is most useful when you want
8936 to see what set of object files are being used in the link step.
8937
8938 @item ^-v -v^/VERBOSE/VERBOSE^
8939 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8940 Very verbose mode. Requests that the compiler operate in verbose mode when
8941 it compiles the binder file, and that the system linker run in verbose mode.
8942
8943 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8944 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8945 @var{exec-name} specifies an alternate name for the generated
8946 executable program. If this switch is omitted, the executable has the same
8947 name as the main unit. For example, @code{gnatlink try.ali} creates
8948 an executable called @file{^try^TRY.EXE^}.
8949
8950 @ifclear vms
8951 @item -b @var{target}
8952 @cindex @option{-b} (@command{gnatlink})
8953 Compile your program to run on @var{target}, which is the name of a
8954 system configuration. You must have a GNAT cross-compiler built if
8955 @var{target} is not the same as your host system.
8956
8957 @item -B@var{dir}
8958 @cindex @option{-B} (@command{gnatlink})
8959 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8960 from @var{dir} instead of the default location. Only use this switch
8961 when multiple versions of the GNAT compiler are available.
8962 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8963 for further details. You would normally use the @option{-b} or
8964 @option{-V} switch instead.
8965
8966 @item --GCC=@var{compiler_name}
8967 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8968 Program used for compiling the binder file. The default is
8969 @command{gcc}. You need to use quotes around @var{compiler_name} if
8970 @code{compiler_name} contains spaces or other separator characters.
8971 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8972 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8973 inserted after your command name. Thus in the above example the compiler
8974 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8975 A limitation of this syntax is that the name and path name of the executable
8976 itself must not include any embedded spaces. If the compiler executable is
8977 different from the default one (gcc or <prefix>-gcc), then the back-end
8978 switches in the ALI file are not used to compile the binder generated source.
8979 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8980 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8981 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8982 is taken into account. However, all the additional switches are also taken
8983 into account. Thus,
8984 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8985 @option{--GCC="bar -x -y -z -t"}.
8986
8987 @item --LINK=@var{name}
8988 @cindex @option{--LINK=} (@command{gnatlink})
8989 @var{name} is the name of the linker to be invoked. This is especially
8990 useful in mixed language programs since languages such as C++ require
8991 their own linker to be used. When this switch is omitted, the default
8992 name for the linker is @command{gcc}. When this switch is used, the
8993 specified linker is called instead of @command{gcc} with exactly the same
8994 parameters that would have been passed to @command{gcc} so if the desired
8995 linker requires different parameters it is necessary to use a wrapper
8996 script that massages the parameters before invoking the real linker. It
8997 may be useful to control the exact invocation by using the verbose
8998 switch.
8999
9000 @end ifclear
9001
9002 @ifset vms
9003 @item /DEBUG=TRACEBACK
9004 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9005 This qualifier causes sufficient information to be included in the
9006 executable file to allow a traceback, but does not include the full
9007 symbol information needed by the debugger.
9008
9009 @item /IDENTIFICATION="<string>"
9010 @code{"<string>"} specifies the string to be stored in the image file
9011 identification field in the image header.
9012 It overrides any pragma @code{Ident} specified string.
9013
9014 @item /NOINHIBIT-EXEC
9015 Generate the executable file even if there are linker warnings.
9016
9017 @item /NOSTART_FILES
9018 Don't link in the object file containing the ``main'' transfer address.
9019 Used when linking with a foreign language main program compiled with an
9020 HP compiler.
9021
9022 @item /STATIC
9023 Prefer linking with object libraries over sharable images, even without
9024 /DEBUG.
9025 @end ifset
9026
9027 @end table
9028
9029 @node The GNAT Make Program gnatmake
9030 @chapter The GNAT Make Program @command{gnatmake}
9031 @findex gnatmake
9032
9033 @menu
9034 * Running gnatmake::
9035 * Switches for gnatmake::
9036 * Mode Switches for gnatmake::
9037 * Notes on the Command Line::
9038 * How gnatmake Works::
9039 * Examples of gnatmake Usage::
9040 @end menu
9041 @noindent
9042 A typical development cycle when working on an Ada program consists of
9043 the following steps:
9044
9045 @enumerate
9046 @item
9047 Edit some sources to fix bugs.
9048
9049 @item
9050 Add enhancements.
9051
9052 @item
9053 Compile all sources affected.
9054
9055 @item
9056 Rebind and relink.
9057
9058 @item
9059 Test.
9060 @end enumerate
9061
9062 @noindent
9063 The third step can be tricky, because not only do the modified files
9064 @cindex Dependency rules
9065 have to be compiled, but any files depending on these files must also be
9066 recompiled. The dependency rules in Ada can be quite complex, especially
9067 in the presence of overloading, @code{use} clauses, generics and inlined
9068 subprograms.
9069
9070 @command{gnatmake} automatically takes care of the third and fourth steps
9071 of this process. It determines which sources need to be compiled,
9072 compiles them, and binds and links the resulting object files.
9073
9074 Unlike some other Ada make programs, the dependencies are always
9075 accurately recomputed from the new sources. The source based approach of
9076 the GNAT compilation model makes this possible. This means that if
9077 changes to the source program cause corresponding changes in
9078 dependencies, they will always be tracked exactly correctly by
9079 @command{gnatmake}.
9080
9081 @node Running gnatmake
9082 @section Running @command{gnatmake}
9083
9084 @noindent
9085 The usual form of the @command{gnatmake} command is
9086
9087 @smallexample
9088 $ gnatmake @ovar{switches} @var{file_name}
9089       @ovar{file_names} @ovar{mode_switches}
9090 @end smallexample
9091
9092 @noindent
9093 The only required argument is one @var{file_name}, which specifies
9094 a compilation unit that is a main program. Several @var{file_names} can be
9095 specified: this will result in several executables being built.
9096 If @code{switches} are present, they can be placed before the first
9097 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9098 If @var{mode_switches} are present, they must always be placed after
9099 the last @var{file_name} and all @code{switches}.
9100
9101 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9102 extension may be omitted from the @var{file_name} arguments. However, if
9103 you are using non-standard extensions, then it is required that the
9104 extension be given. A relative or absolute directory path can be
9105 specified in a @var{file_name}, in which case, the input source file will
9106 be searched for in the specified directory only. Otherwise, the input
9107 source file will first be searched in the directory where
9108 @command{gnatmake} was invoked and if it is not found, it will be search on
9109 the source path of the compiler as described in
9110 @ref{Search Paths and the Run-Time Library (RTL)}.
9111
9112 All @command{gnatmake} output (except when you specify
9113 @option{^-M^/DEPENDENCIES_LIST^}) is to
9114 @file{stderr}. The output produced by the
9115 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9116 @file{stdout}.
9117
9118 @node Switches for gnatmake
9119 @section Switches for @command{gnatmake}
9120
9121 @noindent
9122 You may specify any of the following switches to @command{gnatmake}:
9123
9124 @table @option
9125 @c !sort!
9126
9127 @item --version
9128 @cindex @option{--version} @command{gnatmake}
9129 Display Copyright and version, then exit disregarding all other options.
9130
9131 @item --help
9132 @cindex @option{--help} @command{gnatmake}
9133 If @option{--version} was not used, display usage, then exit disregarding
9134 all other options.
9135
9136 @ifclear vms
9137 @item --GCC=@var{compiler_name}
9138 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9139 Program used for compiling. The default is `@command{gcc}'. You need to use
9140 quotes around @var{compiler_name} if @code{compiler_name} contains
9141 spaces or other separator characters. As an example @option{--GCC="foo -x
9142 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9143 compiler. A limitation of this syntax is that the name and path name of
9144 the executable itself must not include any embedded spaces. Note that
9145 switch @option{-c} is always inserted after your command name. Thus in the
9146 above example the compiler command that will be used by @command{gnatmake}
9147 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9148 used, only the last @var{compiler_name} is taken into account. However,
9149 all the additional switches are also taken into account. Thus,
9150 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9151 @option{--GCC="bar -x -y -z -t"}.
9152
9153 @item --GNATBIND=@var{binder_name}
9154 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9155 Program used for binding. The default is `@code{gnatbind}'. You need to
9156 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9157 or other separator characters. As an example @option{--GNATBIND="bar -x
9158 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9159 binder. Binder switches that are normally appended by @command{gnatmake}
9160 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9161 A limitation of this syntax is that the name and path name of the executable
9162 itself must not include any embedded spaces.
9163
9164 @item --GNATLINK=@var{linker_name}
9165 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9166 Program used for linking. The default is `@command{gnatlink}'. You need to
9167 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9168 or other separator characters. As an example @option{--GNATLINK="lan -x
9169 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9170 linker. Linker switches that are normally appended by @command{gnatmake} to
9171 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9172 A limitation of this syntax is that the name and path name of the executable
9173 itself must not include any embedded spaces.
9174
9175 @end ifclear
9176
9177 @item ^-a^/ALL_FILES^
9178 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9179 Consider all files in the make process, even the GNAT internal system
9180 files (for example, the predefined Ada library files), as well as any
9181 locked files. Locked files are files whose ALI file is write-protected.
9182 By default,
9183 @command{gnatmake} does not check these files,
9184 because the assumption is that the GNAT internal files are properly up
9185 to date, and also that any write protected ALI files have been properly
9186 installed. Note that if there is an installation problem, such that one
9187 of these files is not up to date, it will be properly caught by the
9188 binder.
9189 You may have to specify this switch if you are working on GNAT
9190 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9191 in conjunction with @option{^-f^/FORCE_COMPILE^}
9192 if you need to recompile an entire application,
9193 including run-time files, using special configuration pragmas,
9194 such as a @code{Normalize_Scalars} pragma.
9195
9196 By default
9197 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9198 internal files with
9199 @ifclear vms
9200 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9201 @end ifclear
9202 @ifset vms
9203 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9204 @end ifset
9205
9206 @item ^-b^/ACTIONS=BIND^
9207 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9208 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9209 compilation and binding, but no link.
9210 Can be combined with @option{^-l^/ACTIONS=LINK^}
9211 to do binding and linking. When not combined with
9212 @option{^-c^/ACTIONS=COMPILE^}
9213 all the units in the closure of the main program must have been previously
9214 compiled and must be up to date. The root unit specified by @var{file_name}
9215 may be given without extension, with the source extension or, if no GNAT
9216 Project File is specified, with the ALI file extension.
9217
9218 @item ^-c^/ACTIONS=COMPILE^
9219 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9220 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9221 is also specified. Do not perform linking, except if both
9222 @option{^-b^/ACTIONS=BIND^} and
9223 @option{^-l^/ACTIONS=LINK^} are also specified.
9224 If the root unit specified by @var{file_name} is not a main unit, this is the
9225 default. Otherwise @command{gnatmake} will attempt binding and linking
9226 unless all objects are up to date and the executable is more recent than
9227 the objects.
9228
9229 @item ^-C^/MAPPING^
9230 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9231 Use a temporary mapping file. A mapping file is a way to communicate to the
9232 compiler two mappings: from unit names to file names (without any directory
9233 information) and from file names to path names (with full directory
9234 information). These mappings are used by the compiler to short-circuit the path
9235 search. When @command{gnatmake} is invoked with this switch, it will create
9236 a temporary mapping file, initially populated by the project manager,
9237 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9238 Each invocation of the compiler will add the newly accessed sources to the
9239 mapping file. This will improve the source search during the next invocation
9240 of the compiler.
9241
9242 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9243 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9244 Use a specific mapping file. The file, specified as a path name (absolute or
9245 relative) by this switch, should already exist, otherwise the switch is
9246 ineffective. The specified mapping file will be communicated to the compiler.
9247 This switch is not compatible with a project file
9248 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9249 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9250
9251 @item ^-d^/DISPLAY_PROGRESS^
9252 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9253 Display progress for each source, up to date or not, as a single line
9254
9255 @smallexample
9256 completed x out of y (zz%)
9257 @end smallexample
9258
9259 If the file needs to be compiled this is displayed after the invocation of
9260 the compiler. These lines are displayed even in quiet output mode.
9261
9262 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9263 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9264 Put all object files and ALI file in directory @var{dir}.
9265 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9266 and ALI files go in the current working directory.
9267
9268 This switch cannot be used when using a project file.
9269
9270 @ifclear vms
9271 @item -eL
9272 @cindex @option{-eL} (@command{gnatmake})
9273 Follow all symbolic links when processing project files.
9274 @end ifclear
9275
9276 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9277 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9278 Output the commands for the compiler, the binder and the linker
9279 on ^standard output^SYS$OUTPUT^,
9280 instead of ^standard error^SYS$ERROR^.
9281
9282 @item ^-f^/FORCE_COMPILE^
9283 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9284 Force recompilations. Recompile all sources, even though some object
9285 files may be up to date, but don't recompile predefined or GNAT internal
9286 files or locked files (files with a write-protected ALI file),
9287 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9288
9289 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9290 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9291 When using project files, if some errors or warnings are detected during
9292 parsing and verbose mode is not in effect (no use of switch
9293 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9294 file, rather than its simple file name.
9295
9296 @item ^-g^/DEBUG^
9297 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9298 Enable debugging. This switch is simply passed to the compiler and to the
9299 linker.
9300
9301 @item ^-i^/IN_PLACE^
9302 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9303 In normal mode, @command{gnatmake} compiles all object files and ALI files
9304 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9305 then instead object files and ALI files that already exist are overwritten
9306 in place. This means that once a large project is organized into separate
9307 directories in the desired manner, then @command{gnatmake} will automatically
9308 maintain and update this organization. If no ALI files are found on the
9309 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9310 the new object and ALI files are created in the
9311 directory containing the source being compiled. If another organization
9312 is desired, where objects and sources are kept in different directories,
9313 a useful technique is to create dummy ALI files in the desired directories.
9314 When detecting such a dummy file, @command{gnatmake} will be forced to
9315 recompile the corresponding source file, and it will be put the resulting
9316 object and ALI files in the directory where it found the dummy file.
9317
9318 @item ^-j^/PROCESSES=^@var{n}
9319 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9320 @cindex Parallel make
9321 Use @var{n} processes to carry out the (re)compilations. On a
9322 multiprocessor machine compilations will occur in parallel. In the
9323 event of compilation errors, messages from various compilations might
9324 get interspersed (but @command{gnatmake} will give you the full ordered
9325 list of failing compiles at the end). If this is problematic, rerun
9326 the make process with n set to 1 to get a clean list of messages.
9327
9328 @item ^-k^/CONTINUE_ON_ERROR^
9329 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9330 Keep going. Continue as much as possible after a compilation error. To
9331 ease the programmer's task in case of compilation errors, the list of
9332 sources for which the compile fails is given when @command{gnatmake}
9333 terminates.
9334
9335 If @command{gnatmake} is invoked with several @file{file_names} and with this
9336 switch, if there are compilation errors when building an executable,
9337 @command{gnatmake} will not attempt to build the following executables.
9338
9339 @item ^-l^/ACTIONS=LINK^
9340 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9341 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9342 and linking. Linking will not be performed if combined with
9343 @option{^-c^/ACTIONS=COMPILE^}
9344 but not with @option{^-b^/ACTIONS=BIND^}.
9345 When not combined with @option{^-b^/ACTIONS=BIND^}
9346 all the units in the closure of the main program must have been previously
9347 compiled and must be up to date, and the main program needs to have been bound.
9348 The root unit specified by @var{file_name}
9349 may be given without extension, with the source extension or, if no GNAT
9350 Project File is specified, with the ALI file extension.
9351
9352 @item ^-m^/MINIMAL_RECOMPILATION^
9353 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9354 Specify that the minimum necessary amount of recompilations
9355 be performed. In this mode @command{gnatmake} ignores time
9356 stamp differences when the only
9357 modifications to a source file consist in adding/removing comments,
9358 empty lines, spaces or tabs. This means that if you have changed the
9359 comments in a source file or have simply reformatted it, using this
9360 switch will tell @command{gnatmake} not to recompile files that depend on it
9361 (provided other sources on which these files depend have undergone no
9362 semantic modifications). Note that the debugging information may be
9363 out of date with respect to the sources if the @option{-m} switch causes
9364 a compilation to be switched, so the use of this switch represents a
9365 trade-off between compilation time and accurate debugging information.
9366
9367 @item ^-M^/DEPENDENCIES_LIST^
9368 @cindex Dependencies, producing list
9369 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9370 Check if all objects are up to date. If they are, output the object
9371 dependences to @file{stdout} in a form that can be directly exploited in
9372 a @file{Makefile}. By default, each source file is prefixed with its
9373 (relative or absolute) directory name. This name is whatever you
9374 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9375 and @option{^-I^/SEARCH^} switches. If you use
9376 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9377 @option{^-q^/QUIET^}
9378 (see below), only the source file names,
9379 without relative paths, are output. If you just specify the
9380 @option{^-M^/DEPENDENCIES_LIST^}
9381 switch, dependencies of the GNAT internal system files are omitted. This
9382 is typically what you want. If you also specify
9383 the @option{^-a^/ALL_FILES^} switch,
9384 dependencies of the GNAT internal files are also listed. Note that
9385 dependencies of the objects in external Ada libraries (see switch
9386 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9387 are never reported.
9388
9389 @item ^-n^/DO_OBJECT_CHECK^
9390 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9391 Don't compile, bind, or link. Checks if all objects are up to date.
9392 If they are not, the full name of the first file that needs to be
9393 recompiled is printed.
9394 Repeated use of this option, followed by compiling the indicated source
9395 file, will eventually result in recompiling all required units.
9396
9397 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9398 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9399 Output executable name. The name of the final executable program will be
9400 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9401 name for the executable will be the name of the input file in appropriate form
9402 for an executable file on the host system.
9403
9404 This switch cannot be used when invoking @command{gnatmake} with several
9405 @file{file_names}.
9406
9407 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9408 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9409 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9410 automatically missing object directories, library directories and exec
9411 directories.
9412
9413 @item ^-P^/PROJECT_FILE=^@var{project}
9414 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9415 Use project file @var{project}. Only one such switch can be used.
9416 @xref{gnatmake and Project Files}.
9417
9418 @item ^-q^/QUIET^
9419 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9420 Quiet. When this flag is not set, the commands carried out by
9421 @command{gnatmake} are displayed.
9422
9423 @item ^-s^/SWITCH_CHECK/^
9424 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9425 Recompile if compiler switches have changed since last compilation.
9426 All compiler switches but -I and -o are taken into account in the
9427 following way:
9428 orders between different ``first letter'' switches are ignored, but
9429 orders between same switches are taken into account. For example,
9430 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9431 is equivalent to @option{-O -g}.
9432
9433 This switch is recommended when Integrated Preprocessing is used.
9434
9435 @item ^-u^/UNIQUE^
9436 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9437 Unique. Recompile at most the main files. It implies -c. Combined with
9438 -f, it is equivalent to calling the compiler directly. Note that using
9439 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9440 (@pxref{Project Files and Main Subprograms}).
9441
9442 @item ^-U^/ALL_PROJECTS^
9443 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9444 When used without a project file or with one or several mains on the command
9445 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9446 on the command line, all sources of all project files are checked and compiled
9447 if not up to date, and libraries are rebuilt, if necessary.
9448
9449 @item ^-v^/REASONS^
9450 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9451 Verbose. Display the reason for all recompilations @command{gnatmake}
9452 decides are necessary, with the highest verbosity level.
9453
9454 @item ^-vl^/LOW_VERBOSITY^
9455 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9456 Verbosity level Low. Display fewer lines than in verbosity Medium.
9457
9458 @item ^-vm^/MEDIUM_VERBOSITY^
9459 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9460 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9461
9462 @item ^-vh^/HIGH_VERBOSITY^
9463 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9464 Verbosity level High. Equivalent to ^-v^/REASONS^.
9465
9466 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9467 Indicate the verbosity of the parsing of GNAT project files.
9468 @xref{Switches Related to Project Files}.
9469
9470 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9471 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9472 Indicate that sources that are not part of any Project File may be compiled.
9473 Normally, when using Project Files, only sources that are part of a Project
9474 File may be compile. When this switch is used, a source outside of all Project
9475 Files may be compiled. The ALI file and the object file will be put in the
9476 object directory of the main Project. The compilation switches used will only
9477 be those specified on the command line. Even when
9478 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9479 command line need to be sources of a project file.
9480
9481 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9482 Indicate that external variable @var{name} has the value @var{value}.
9483 The Project Manager will use this value for occurrences of
9484 @code{external(name)} when parsing the project file.
9485 @xref{Switches Related to Project Files}.
9486
9487 @item ^-z^/NOMAIN^
9488 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9489 No main subprogram. Bind and link the program even if the unit name
9490 given on the command line is a package name. The resulting executable
9491 will execute the elaboration routines of the package and its closure,
9492 then the finalization routines.
9493
9494 @end table
9495
9496 @table @asis
9497 @item @command{gcc} @asis{switches}
9498 @ifclear vms
9499 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9500 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9501 @end ifclear
9502 @ifset vms
9503 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9504 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9505 automatically treated as a compiler switch, and passed on to all
9506 compilations that are carried out.
9507 @end ifset
9508 @end table
9509
9510 @noindent
9511 Source and library search path switches:
9512
9513 @table @option
9514 @c !sort!
9515 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9516 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9517 When looking for source files also look in directory @var{dir}.
9518 The order in which source files search is undertaken is
9519 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9520
9521 @item ^-aL^/SKIP_MISSING=^@var{dir}
9522 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9523 Consider @var{dir} as being an externally provided Ada library.
9524 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9525 files have been located in directory @var{dir}. This allows you to have
9526 missing bodies for the units in @var{dir} and to ignore out of date bodies
9527 for the same units. You still need to specify
9528 the location of the specs for these units by using the switches
9529 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9530 or @option{^-I^/SEARCH=^@var{dir}}.
9531 Note: this switch is provided for compatibility with previous versions
9532 of @command{gnatmake}. The easier method of causing standard libraries
9533 to be excluded from consideration is to write-protect the corresponding
9534 ALI files.
9535
9536 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9537 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9538 When searching for library and object files, look in directory
9539 @var{dir}. The order in which library files are searched is described in
9540 @ref{Search Paths for gnatbind}.
9541
9542 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9543 @cindex Search paths, for @command{gnatmake}
9544 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9545 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9546 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9547
9548 @item ^-I^/SEARCH=^@var{dir}
9549 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9550 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9551 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9552
9553 @item ^-I-^/NOCURRENT_DIRECTORY^
9554 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9555 @cindex Source files, suppressing search
9556 Do not look for source files in the directory containing the source
9557 file named in the command line.
9558 Do not look for ALI or object files in the directory
9559 where @command{gnatmake} was invoked.
9560
9561 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9562 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9563 @cindex Linker libraries
9564 Add directory @var{dir} to the list of directories in which the linker
9565 will search for libraries. This is equivalent to
9566 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9567 @ifclear vms
9568 Furthermore, under Windows, the sources pointed to by the libraries path
9569 set in the registry are not searched for.
9570 @end ifclear
9571
9572 @item -nostdinc
9573 @cindex @option{-nostdinc} (@command{gnatmake})
9574 Do not look for source files in the system default directory.
9575
9576 @item -nostdlib
9577 @cindex @option{-nostdlib} (@command{gnatmake})
9578 Do not look for library files in the system default directory.
9579
9580 @item --RTS=@var{rts-path}
9581 @cindex @option{--RTS} (@command{gnatmake})
9582 Specifies the default location of the runtime library. GNAT looks for the
9583 runtime
9584 in the following directories, and stops as soon as a valid runtime is found
9585 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9586 @file{ada_object_path} present):
9587
9588 @itemize @bullet
9589 @item <current directory>/$rts_path
9590
9591 @item <default-search-dir>/$rts_path
9592
9593 @item <default-search-dir>/rts-$rts_path
9594 @end itemize
9595
9596 @noindent
9597 The selected path is handled like a normal RTS path.
9598
9599 @end table
9600
9601 @node Mode Switches for gnatmake
9602 @section Mode Switches for @command{gnatmake}
9603
9604 @noindent
9605 The mode switches (referred to as @code{mode_switches}) allow the
9606 inclusion of switches that are to be passed to the compiler itself, the
9607 binder or the linker. The effect of a mode switch is to cause all
9608 subsequent switches up to the end of the switch list, or up to the next
9609 mode switch, to be interpreted as switches to be passed on to the
9610 designated component of GNAT.
9611
9612 @table @option
9613 @c !sort!
9614 @item -cargs @var{switches}
9615 @cindex @option{-cargs} (@command{gnatmake})
9616 Compiler switches. Here @var{switches} is a list of switches
9617 that are valid switches for @command{gcc}. They will be passed on to
9618 all compile steps performed by @command{gnatmake}.
9619
9620 @item -bargs @var{switches}
9621 @cindex @option{-bargs} (@command{gnatmake})
9622 Binder switches. Here @var{switches} is a list of switches
9623 that are valid switches for @code{gnatbind}. They will be passed on to
9624 all bind steps performed by @command{gnatmake}.
9625
9626 @item -largs @var{switches}
9627 @cindex @option{-largs} (@command{gnatmake})
9628 Linker switches. Here @var{switches} is a list of switches
9629 that are valid switches for @command{gnatlink}. They will be passed on to
9630 all link steps performed by @command{gnatmake}.
9631
9632 @item -margs @var{switches}
9633 @cindex @option{-margs} (@command{gnatmake})
9634 Make switches. The switches are directly interpreted by @command{gnatmake},
9635 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9636 or @option{-largs}.
9637 @end table
9638
9639 @node Notes on the Command Line
9640 @section Notes on the Command Line
9641
9642 @noindent
9643 This section contains some additional useful notes on the operation
9644 of the @command{gnatmake} command.
9645
9646 @itemize @bullet
9647 @item
9648 @cindex Recompilation, by @command{gnatmake}
9649 If @command{gnatmake} finds no ALI files, it recompiles the main program
9650 and all other units required by the main program.
9651 This means that @command{gnatmake}
9652 can be used for the initial compile, as well as during subsequent steps of
9653 the development cycle.
9654
9655 @item
9656 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9657 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9658 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9659 warning.
9660
9661 @item
9662 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9663 is used to specify both source and
9664 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9665 instead if you just want to specify
9666 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9667 if you want to specify library paths
9668 only.
9669
9670 @item
9671 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9672 This may conveniently be used to exclude standard libraries from
9673 consideration and in particular it means that the use of the
9674 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9675 unless @option{^-a^/ALL_FILES^} is also specified.
9676
9677 @item
9678 @command{gnatmake} has been designed to make the use of Ada libraries
9679 particularly convenient. Assume you have an Ada library organized
9680 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9681 of your Ada compilation units,
9682 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9683 specs of these units, but no bodies. Then to compile a unit
9684 stored in @code{main.adb}, which uses this Ada library you would just type
9685
9686 @smallexample
9687 @ifclear vms
9688 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9689 @end ifclear
9690 @ifset vms
9691 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9692            /SKIP_MISSING=@i{[OBJ_DIR]} main
9693 @end ifset
9694 @end smallexample
9695
9696 @item
9697 Using @command{gnatmake} along with the
9698 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9699 switch provides a mechanism for avoiding unnecessary recompilations. Using
9700 this switch,
9701 you can update the comments/format of your
9702 source files without having to recompile everything. Note, however, that
9703 adding or deleting lines in a source files may render its debugging
9704 info obsolete. If the file in question is a spec, the impact is rather
9705 limited, as that debugging info will only be useful during the
9706 elaboration phase of your program. For bodies the impact can be more
9707 significant. In all events, your debugger will warn you if a source file
9708 is more recent than the corresponding object, and alert you to the fact
9709 that the debugging information may be out of date.
9710 @end itemize
9711
9712 @node How gnatmake Works
9713 @section How @command{gnatmake} Works
9714
9715 @noindent
9716 Generally @command{gnatmake} automatically performs all necessary
9717 recompilations and you don't need to worry about how it works. However,
9718 it may be useful to have some basic understanding of the @command{gnatmake}
9719 approach and in particular to understand how it uses the results of
9720 previous compilations without incorrectly depending on them.
9721
9722 First a definition: an object file is considered @dfn{up to date} if the
9723 corresponding ALI file exists and if all the source files listed in the
9724 dependency section of this ALI file have time stamps matching those in
9725 the ALI file. This means that neither the source file itself nor any
9726 files that it depends on have been modified, and hence there is no need
9727 to recompile this file.
9728
9729 @command{gnatmake} works by first checking if the specified main unit is up
9730 to date. If so, no compilations are required for the main unit. If not,
9731 @command{gnatmake} compiles the main program to build a new ALI file that
9732 reflects the latest sources. Then the ALI file of the main unit is
9733 examined to find all the source files on which the main program depends,
9734 and @command{gnatmake} recursively applies the above procedure on all these
9735 files.
9736
9737 This process ensures that @command{gnatmake} only trusts the dependencies
9738 in an existing ALI file if they are known to be correct. Otherwise it
9739 always recompiles to determine a new, guaranteed accurate set of
9740 dependencies. As a result the program is compiled ``upside down'' from what may
9741 be more familiar as the required order of compilation in some other Ada
9742 systems. In particular, clients are compiled before the units on which
9743 they depend. The ability of GNAT to compile in any order is critical in
9744 allowing an order of compilation to be chosen that guarantees that
9745 @command{gnatmake} will recompute a correct set of new dependencies if
9746 necessary.
9747
9748 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9749 imported by several of the executables, it will be recompiled at most once.
9750
9751 Note: when using non-standard naming conventions
9752 (@pxref{Using Other File Names}), changing through a configuration pragmas
9753 file the version of a source and invoking @command{gnatmake} to recompile may
9754 have no effect, if the previous version of the source is still accessible
9755 by @command{gnatmake}. It may be necessary to use the switch
9756 ^-f^/FORCE_COMPILE^.
9757
9758 @node Examples of gnatmake Usage
9759 @section Examples of @command{gnatmake} Usage
9760
9761 @table @code
9762 @item gnatmake hello.adb
9763 Compile all files necessary to bind and link the main program
9764 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9765 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9766
9767 @item gnatmake main1 main2 main3
9768 Compile all files necessary to bind and link the main programs
9769 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9770 (containing unit @code{Main2}) and @file{main3.adb}
9771 (containing unit @code{Main3}) and bind and link the resulting object files
9772 to generate three executable files @file{^main1^MAIN1.EXE^},
9773 @file{^main2^MAIN2.EXE^}
9774 and @file{^main3^MAIN3.EXE^}.
9775
9776 @ifclear vms
9777 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9778 @end ifclear
9779
9780 @ifset vms
9781 @item gnatmake Main_Unit /QUIET
9782 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9783 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9784 @end ifset
9785 Compile all files necessary to bind and link the main program unit
9786 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9787 be done with optimization level 2 and the order of elaboration will be
9788 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9789 displaying commands it is executing.
9790 @end table
9791
9792 @c *************************
9793 @node Improving Performance
9794 @chapter Improving Performance
9795 @cindex Improving performance
9796
9797 @noindent
9798 This chapter presents several topics related to program performance.
9799 It first describes some of the tradeoffs that need to be considered
9800 and some of the techniques for making your program run faster.
9801 It then documents the @command{gnatelim} tool and unused subprogram/data
9802 elimination feature, which can reduce the size of program executables.
9803
9804 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9805 driver (see @ref{The GNAT Driver and Project Files}).
9806
9807 @ifnottex
9808 @menu
9809 * Performance Considerations::
9810 * Text_IO Suggestions::
9811 * Reducing Size of Ada Executables with gnatelim::
9812 * Reducing Size of Executables with unused subprogram/data elimination::
9813 @end menu
9814 @end ifnottex
9815
9816 @c *****************************
9817 @node Performance Considerations
9818 @section Performance Considerations
9819
9820 @noindent
9821 The GNAT system provides a number of options that allow a trade-off
9822 between
9823
9824 @itemize @bullet
9825 @item
9826 performance of the generated code
9827
9828 @item
9829 speed of compilation
9830
9831 @item
9832 minimization of dependences and recompilation
9833
9834 @item
9835 the degree of run-time checking.
9836 @end itemize
9837
9838 @noindent
9839 The defaults (if no options are selected) aim at improving the speed
9840 of compilation and minimizing dependences, at the expense of performance
9841 of the generated code:
9842
9843 @itemize @bullet
9844 @item
9845 no optimization
9846
9847 @item
9848 no inlining of subprogram calls
9849
9850 @item
9851 all run-time checks enabled except overflow and elaboration checks
9852 @end itemize
9853
9854 @noindent
9855 These options are suitable for most program development purposes. This
9856 chapter describes how you can modify these choices, and also provides
9857 some guidelines on debugging optimized code.
9858
9859 @menu
9860 * Controlling Run-Time Checks::
9861 * Use of Restrictions::
9862 * Optimization Levels::
9863 * Debugging Optimized Code::
9864 * Inlining of Subprograms::
9865 * Other Optimization Switches::
9866 * Optimization and Strict Aliasing::
9867
9868 @ifset vms
9869 * Coverage Analysis::
9870 @end ifset
9871 @end menu
9872
9873 @node Controlling Run-Time Checks
9874 @subsection Controlling Run-Time Checks
9875
9876 @noindent
9877 By default, GNAT generates all run-time checks, except integer overflow
9878 checks, stack overflow checks, and checks for access before elaboration on
9879 subprogram calls. The latter are not required in default mode, because all
9880 necessary checking is done at compile time.
9881 @cindex @option{-gnatp} (@command{gcc})
9882 @cindex @option{-gnato} (@command{gcc})
9883 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9884 be modified. @xref{Run-Time Checks}.
9885
9886 Our experience is that the default is suitable for most development
9887 purposes.
9888
9889 We treat integer overflow specially because these
9890 are quite expensive and in our experience are not as important as other
9891 run-time checks in the development process. Note that division by zero
9892 is not considered an overflow check, and divide by zero checks are
9893 generated where required by default.
9894
9895 Elaboration checks are off by default, and also not needed by default, since
9896 GNAT uses a static elaboration analysis approach that avoids the need for
9897 run-time checking. This manual contains a full chapter discussing the issue
9898 of elaboration checks, and if the default is not satisfactory for your use,
9899 you should read this chapter.
9900
9901 For validity checks, the minimal checks required by the Ada Reference
9902 Manual (for case statements and assignments to array elements) are on
9903 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9904 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9905 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9906 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9907 are also suppressed entirely if @option{-gnatp} is used.
9908
9909 @cindex Overflow checks
9910 @cindex Checks, overflow
9911 @findex Suppress
9912 @findex Unsuppress
9913 @cindex pragma Suppress
9914 @cindex pragma Unsuppress
9915 Note that the setting of the switches controls the default setting of
9916 the checks. They may be modified using either @code{pragma Suppress} (to
9917 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9918 checks) in the program source.
9919
9920 @node Use of Restrictions
9921 @subsection Use of Restrictions
9922
9923 @noindent
9924 The use of pragma Restrictions allows you to control which features are
9925 permitted in your program. Apart from the obvious point that if you avoid
9926 relatively expensive features like finalization (enforceable by the use
9927 of pragma Restrictions (No_Finalization), the use of this pragma does not
9928 affect the generated code in most cases.
9929
9930 One notable exception to this rule is that the possibility of task abort
9931 results in some distributed overhead, particularly if finalization or
9932 exception handlers are used. The reason is that certain sections of code
9933 have to be marked as non-abortable.
9934
9935 If you use neither the @code{abort} statement, nor asynchronous transfer
9936 of control (@code{select @dots{} then abort}), then this distributed overhead
9937 is removed, which may have a general positive effect in improving
9938 overall performance.  Especially code involving frequent use of tasking
9939 constructs and controlled types will show much improved performance.
9940 The relevant restrictions pragmas are
9941
9942 @smallexample @c ada
9943    pragma Restrictions (No_Abort_Statements);
9944    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9945 @end smallexample
9946
9947 @noindent
9948 It is recommended that these restriction pragmas be used if possible. Note
9949 that this also means that you can write code without worrying about the
9950 possibility of an immediate abort at any point.
9951
9952 @node Optimization Levels
9953 @subsection Optimization Levels
9954 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9955
9956 @noindent
9957 Without any optimization ^option,^qualifier,^
9958 the compiler's goal is to reduce the cost of
9959 compilation and to make debugging produce the expected results.
9960 Statements are independent: if you stop the program with a breakpoint between
9961 statements, you can then assign a new value to any variable or change
9962 the program counter to any other statement in the subprogram and get exactly
9963 the results you would expect from the source code.
9964
9965 Turning on optimization makes the compiler attempt to improve the
9966 performance and/or code size at the expense of compilation time and
9967 possibly the ability to debug the program.
9968
9969 If you use multiple
9970 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9971 the last such option is the one that is effective.
9972
9973 @noindent
9974 The default is optimization off. This results in the fastest compile
9975 times, but GNAT makes absolutely no attempt to optimize, and the
9976 generated programs are considerably larger and slower than when
9977 optimization is enabled. You can use the
9978 @ifclear vms
9979 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9980 @option{-O2}, @option{-O3}, and @option{-Os})
9981 @end ifclear
9982 @ifset vms
9983 @code{OPTIMIZE} qualifier
9984 @end ifset
9985 to @command{gcc} to control the optimization level:
9986
9987 @table @option
9988 @item ^-O0^/OPTIMIZE=NONE^
9989 No optimization (the default);
9990 generates unoptimized code but has
9991 the fastest compilation time.
9992
9993 Note that many other compilers do fairly extensive optimization
9994 even if ``no optimization'' is specified. With gcc, it is
9995 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9996 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9997 really does mean no optimization at all. This difference between
9998 gcc and other compilers should be kept in mind when doing
9999 performance comparisons.
10000
10001 @item ^-O1^/OPTIMIZE=SOME^
10002 Moderate optimization;
10003 optimizes reasonably well but does not
10004 degrade compilation time significantly.
10005
10006 @item ^-O2^/OPTIMIZE=ALL^
10007 @ifset vms
10008 @itemx /OPTIMIZE=DEVELOPMENT
10009 @end ifset
10010 Full optimization;
10011 generates highly optimized code and has
10012 the slowest compilation time.
10013
10014 @item ^-O3^/OPTIMIZE=INLINING^
10015 Full optimization as in @option{-O2},
10016 and also attempts automatic inlining of small
10017 subprograms within a unit (@pxref{Inlining of Subprograms}).
10018
10019 @item ^-Os^/OPTIMIZE=SPACE^
10020 Optimize space usage of resulting program.
10021 @end table
10022
10023 @noindent
10024 Higher optimization levels perform more global transformations on the
10025 program and apply more expensive analysis algorithms in order to generate
10026 faster and more compact code. The price in compilation time, and the
10027 resulting improvement in execution time,
10028 both depend on the particular application and the hardware environment.
10029 You should experiment to find the best level for your application.
10030
10031 Since the precise set of optimizations done at each level will vary from
10032 release to release (and sometime from target to target), it is best to think
10033 of the optimization settings in general terms.
10034 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10035 the GNU Compiler Collection (GCC)}, for details about
10036 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10037 individually enable or disable specific optimizations.
10038
10039 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10040 been tested extensively at all optimization levels. There are some bugs
10041 which appear only with optimization turned on, but there have also been
10042 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10043 level of optimization does not improve the reliability of the code
10044 generator, which in practice is highly reliable at all optimization
10045 levels.
10046
10047 Note regarding the use of @option{-O3}: The use of this optimization level
10048 is generally discouraged with GNAT, since it often results in larger
10049 executables which run more slowly. See further discussion of this point
10050 in @ref{Inlining of Subprograms}.
10051
10052 @node Debugging Optimized Code
10053 @subsection Debugging Optimized Code
10054 @cindex Debugging optimized code
10055 @cindex Optimization and debugging
10056
10057 @noindent
10058 Although it is possible to do a reasonable amount of debugging at
10059 @ifclear vms
10060 nonzero optimization levels,
10061 the higher the level the more likely that
10062 @end ifclear
10063 @ifset vms
10064 @option{/OPTIMIZE} settings other than @code{NONE},
10065 such settings will make it more likely that
10066 @end ifset
10067 source-level constructs will have been eliminated by optimization.
10068 For example, if a loop is strength-reduced, the loop
10069 control variable may be completely eliminated and thus cannot be
10070 displayed in the debugger.
10071 This can only happen at @option{-O2} or @option{-O3}.
10072 Explicit temporary variables that you code might be eliminated at
10073 ^level^setting^ @option{-O1} or higher.
10074
10075 The use of the @option{^-g^/DEBUG^} switch,
10076 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10077 which is needed for source-level debugging,
10078 affects the size of the program executable on disk,
10079 and indeed the debugging information can be quite large.
10080 However, it has no effect on the generated code (and thus does not
10081 degrade performance)
10082
10083 Since the compiler generates debugging tables for a compilation unit before
10084 it performs optimizations, the optimizing transformations may invalidate some
10085 of the debugging data.  You therefore need to anticipate certain
10086 anomalous situations that may arise while debugging optimized code.
10087 These are the most common cases:
10088
10089 @enumerate
10090 @item
10091 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10092 commands show
10093 the PC bouncing back and forth in the code.  This may result from any of
10094 the following optimizations:
10095
10096 @itemize @bullet
10097 @item
10098 @i{Common subexpression elimination:} using a single instance of code for a
10099 quantity that the source computes several times.  As a result you
10100 may not be able to stop on what looks like a statement.
10101
10102 @item
10103 @i{Invariant code motion:} moving an expression that does not change within a
10104 loop, to the beginning of the loop.
10105
10106 @item
10107 @i{Instruction scheduling:} moving instructions so as to
10108 overlap loads and stores (typically) with other code, or in
10109 general to move computations of values closer to their uses. Often
10110 this causes you to pass an assignment statement without the assignment
10111 happening and then later bounce back to the statement when the
10112 value is actually needed.  Placing a breakpoint on a line of code
10113 and then stepping over it may, therefore, not always cause all the
10114 expected side-effects.
10115 @end itemize
10116
10117 @item
10118 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10119 two identical pieces of code are merged and the program counter suddenly
10120 jumps to a statement that is not supposed to be executed, simply because
10121 it (and the code following) translates to the same thing as the code
10122 that @emph{was} supposed to be executed.  This effect is typically seen in
10123 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10124 a @code{break} in a C @code{^switch^switch^} statement.
10125
10126 @item
10127 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10128 There are various reasons for this effect:
10129
10130 @itemize @bullet
10131 @item
10132 In a subprogram prologue, a parameter may not yet have been moved to its
10133 ``home''.
10134
10135 @item
10136 A variable may be dead, and its register re-used.  This is
10137 probably the most common cause.
10138
10139 @item
10140 As mentioned above, the assignment of a value to a variable may
10141 have been moved.
10142
10143 @item
10144 A variable may be eliminated entirely by value propagation or
10145 other means.  In this case, GCC may incorrectly generate debugging
10146 information for the variable
10147 @end itemize
10148
10149 @noindent
10150 In general, when an unexpected value appears for a local variable or parameter
10151 you should first ascertain if that value was actually computed by
10152 your program, as opposed to being incorrectly reported by the debugger.
10153 Record fields or
10154 array elements in an object designated by an access value
10155 are generally less of a problem, once you have ascertained that the access
10156 value is sensible.
10157 Typically, this means checking variables in the preceding code and in the
10158 calling subprogram to verify that the value observed is explainable from other
10159 values (one must apply the procedure recursively to those
10160 other values); or re-running the code and stopping a little earlier
10161 (perhaps before the call) and stepping to better see how the variable obtained
10162 the value in question; or continuing to step @emph{from} the point of the
10163 strange value to see if code motion had simply moved the variable's
10164 assignments later.
10165 @end enumerate
10166
10167 @noindent
10168 In light of such anomalies, a recommended technique is to use @option{-O0}
10169 early in the software development cycle, when extensive debugging capabilities
10170 are most needed, and then move to @option{-O1} and later @option{-O2} as
10171 the debugger becomes less critical.
10172 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10173 a release management issue.
10174 @ifclear vms
10175 Note that if you use @option{-g} you can then use the @command{strip} program
10176 on the resulting executable,
10177 which removes both debugging information and global symbols.
10178 @end ifclear
10179
10180 @node Inlining of Subprograms
10181 @subsection Inlining of Subprograms
10182
10183 @noindent
10184 A call to a subprogram in the current unit is inlined if all the
10185 following conditions are met:
10186
10187 @itemize @bullet
10188 @item
10189 The optimization level is at least @option{-O1}.
10190
10191 @item
10192 The called subprogram is suitable for inlining: It must be small enough
10193 and not contain something that @command{gcc} cannot support in inlined
10194 subprograms.
10195
10196 @item
10197 @cindex pragma Inline
10198 @findex Inline
10199 Either @code{pragma Inline} applies to the subprogram, or it is local
10200 to the unit and called once from within it, or it is small and automatic
10201 inlining (optimization level @option{-O3}) is specified.
10202 @end itemize
10203
10204 @noindent
10205 Calls to subprograms in @code{with}'ed units are normally not inlined.
10206 To achieve actual inlining (that is, replacement of the call by the code
10207 in the body of the subprogram), the following conditions must all be true.
10208
10209 @itemize @bullet
10210 @item
10211 The optimization level is at least @option{-O1}.
10212
10213 @item
10214 The called subprogram is suitable for inlining: It must be small enough
10215 and not contain something that @command{gcc} cannot support in inlined
10216 subprograms.
10217
10218 @item
10219 The call appears in a body (not in a package spec).
10220
10221 @item
10222 There is a @code{pragma Inline} for the subprogram.
10223
10224 @item
10225 @cindex @option{-gnatn} (@command{gcc})
10226 The @option{^-gnatn^/INLINE^} switch
10227 is used in the @command{gcc} command line
10228 @end itemize
10229
10230 Even if all these conditions are met, it may not be possible for
10231 the compiler to inline the call, due to the length of the body,
10232 or features in the body that make it impossible for the compiler
10233 to do the inlining.
10234
10235 Note that specifying the @option{-gnatn} switch causes additional
10236 compilation dependencies. Consider the following:
10237
10238 @smallexample @c ada
10239 @cartouche
10240 package R is
10241    procedure Q;
10242    pragma Inline (Q);
10243 end R;
10244 package body R is
10245    @dots{}
10246 end R;
10247
10248 with R;
10249 procedure Main is
10250 begin
10251    @dots{}
10252    R.Q;
10253 end Main;
10254 @end cartouche
10255 @end smallexample
10256
10257 @noindent
10258 With the default behavior (no @option{-gnatn} switch specified), the
10259 compilation of the @code{Main} procedure depends only on its own source,
10260 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10261 means that editing the body of @code{R} does not require recompiling
10262 @code{Main}.
10263
10264 On the other hand, the call @code{R.Q} is not inlined under these
10265 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10266 is compiled, the call will be inlined if the body of @code{Q} is small
10267 enough, but now @code{Main} depends on the body of @code{R} in
10268 @file{r.adb} as well as on the spec. This means that if this body is edited,
10269 the main program must be recompiled. Note that this extra dependency
10270 occurs whether or not the call is in fact inlined by @command{gcc}.
10271
10272 The use of front end inlining with @option{-gnatN} generates similar
10273 additional dependencies.
10274
10275 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10276 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10277 can be used to prevent
10278 all inlining. This switch overrides all other conditions and ensures
10279 that no inlining occurs. The extra dependences resulting from
10280 @option{-gnatn} will still be active, even if
10281 this switch is used to suppress the resulting inlining actions.
10282
10283 @cindex @option{-fno-inline-functions} (@command{gcc})
10284 Note: The @option{-fno-inline-functions} switch can be used to prevent
10285 automatic inlining of small subprograms if @option{-O3} is used.
10286
10287 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10288 Note: The @option{-fno-inline-functions-called-once} switch
10289 can be used to prevent inlining of subprograms local to the unit
10290 and called once from within it if @option{-O1} is used.
10291
10292 Note regarding the use of @option{-O3}: There is no difference in inlining
10293 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10294 pragma @code{Inline} assuming the use of @option{-gnatn}
10295 or @option{-gnatN} (the switches that activate inlining). If you have used
10296 pragma @code{Inline} in appropriate cases, then it is usually much better
10297 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10298 in this case only has the effect of inlining subprograms you did not
10299 think should be inlined. We often find that the use of @option{-O3} slows
10300 down code by performing excessive inlining, leading to increased instruction
10301 cache pressure from the increased code size. So the bottom line here is
10302 that you should not automatically assume that @option{-O3} is better than
10303 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10304 it actually improves performance.
10305
10306 @node Other Optimization Switches
10307 @subsection Other Optimization Switches
10308 @cindex Optimization Switches
10309
10310 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10311 @command{gcc} optimization switches are potentially usable. These switches
10312 have not been extensively tested with GNAT but can generally be expected
10313 to work. Examples of switches in this category are
10314 @option{-funroll-loops} and
10315 the various target-specific @option{-m} options (in particular, it has been
10316 observed that @option{-march=pentium4} can significantly improve performance
10317 on appropriate machines). For full details of these switches, see
10318 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10319 the GNU Compiler Collection (GCC)}.
10320
10321 @node Optimization and Strict Aliasing
10322 @subsection Optimization and Strict Aliasing
10323 @cindex Aliasing
10324 @cindex Strict Aliasing
10325 @cindex No_Strict_Aliasing
10326
10327 @noindent
10328 The strong typing capabilities of Ada allow an optimizer to generate
10329 efficient code in situations where other languages would be forced to
10330 make worst case assumptions preventing such optimizations. Consider
10331 the following example:
10332
10333 @smallexample @c ada
10334 @cartouche
10335 procedure R is
10336    type Int1 is new Integer;
10337    type Int2 is new Integer;
10338    type Int1A is access Int1;
10339    type Int2A is access Int2;
10340    Int1V : Int1A;
10341    Int2V : Int2A;
10342    @dots{}
10343
10344 begin
10345    @dots{}
10346    for J in Data'Range loop
10347       if Data (J) = Int1V.all then
10348          Int2V.all := Int2V.all + 1;
10349       end if;
10350    end loop;
10351    @dots{}
10352 end R;
10353 @end cartouche
10354 @end smallexample
10355
10356 @noindent
10357 In this example, since the variable @code{Int1V} can only access objects
10358 of type @code{Int1}, and @code{Int2V} can only access objects of type
10359 @code{Int2}, there is no possibility that the assignment to
10360 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10361 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10362 for all iterations of the loop and avoid the extra memory reference
10363 required to dereference it each time through the loop.
10364
10365 This kind of optimization, called strict aliasing analysis, is
10366 triggered by specifying an optimization level of @option{-O2} or
10367 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10368 when access values are involved.
10369
10370 However, although this optimization is always correct in terms of
10371 the formal semantics of the Ada Reference Manual, difficulties can
10372 arise if features like @code{Unchecked_Conversion} are used to break
10373 the typing system. Consider the following complete program example:
10374
10375 @smallexample @c ada
10376 @cartouche
10377 package p1 is
10378    type int1 is new integer;
10379    type int2 is new integer;
10380    type a1 is access int1;
10381    type a2 is access int2;
10382 end p1;
10383
10384 with p1; use p1;
10385 package p2 is
10386    function to_a2 (Input : a1) return a2;
10387 end p2;
10388
10389 with Unchecked_Conversion;
10390 package body p2 is
10391    function to_a2 (Input : a1) return a2 is
10392       function to_a2u is
10393         new Unchecked_Conversion (a1, a2);
10394    begin
10395       return to_a2u (Input);
10396    end to_a2;
10397 end p2;
10398
10399 with p2; use p2;
10400 with p1; use p1;
10401 with Text_IO; use Text_IO;
10402 procedure m is
10403    v1 : a1 := new int1;
10404    v2 : a2 := to_a2 (v1);
10405 begin
10406    v1.all := 1;
10407    v2.all := 0;
10408    put_line (int1'image (v1.all));
10409 end;
10410 @end cartouche
10411 @end smallexample
10412
10413 @noindent
10414 This program prints out 0 in @option{-O0} or @option{-O1}
10415 mode, but it prints out 1 in @option{-O2} mode. That's
10416 because in strict aliasing mode, the compiler can and
10417 does assume that the assignment to @code{v2.all} could not
10418 affect the value of @code{v1.all}, since different types
10419 are involved.
10420
10421 This behavior is not a case of non-conformance with the standard, since
10422 the Ada RM specifies that an unchecked conversion where the resulting
10423 bit pattern is not a correct value of the target type can result in an
10424 abnormal value and attempting to reference an abnormal value makes the
10425 execution of a program erroneous.  That's the case here since the result
10426 does not point to an object of type @code{int2}.  This means that the
10427 effect is entirely unpredictable.
10428
10429 However, although that explanation may satisfy a language
10430 lawyer, in practice an applications programmer expects an
10431 unchecked conversion involving pointers to create true
10432 aliases and the behavior of printing 1 seems plain wrong.
10433 In this case, the strict aliasing optimization is unwelcome.
10434
10435 Indeed the compiler recognizes this possibility, and the
10436 unchecked conversion generates a warning:
10437
10438 @smallexample
10439 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10440 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10441 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10442 @end smallexample
10443
10444 @noindent
10445 Unfortunately the problem is recognized when compiling the body of
10446 package @code{p2}, but the actual "bad" code is generated while
10447 compiling the body of @code{m} and this latter compilation does not see
10448 the suspicious @code{Unchecked_Conversion}.
10449
10450 As implied by the warning message, there are approaches you can use to
10451 avoid the unwanted strict aliasing optimization in a case like this.
10452
10453 One possibility is to simply avoid the use of @option{-O2}, but
10454 that is a bit drastic, since it throws away a number of useful
10455 optimizations that do not involve strict aliasing assumptions.
10456
10457 A less drastic approach is to compile the program using the
10458 option @option{-fno-strict-aliasing}. Actually it is only the
10459 unit containing the dereferencing of the suspicious pointer
10460 that needs to be compiled. So in this case, if we compile
10461 unit @code{m} with this switch, then we get the expected
10462 value of zero printed. Analyzing which units might need
10463 the switch can be painful, so a more reasonable approach
10464 is to compile the entire program with options @option{-O2}
10465 and @option{-fno-strict-aliasing}. If the performance is
10466 satisfactory with this combination of options, then the
10467 advantage is that the entire issue of possible "wrong"
10468 optimization due to strict aliasing is avoided.
10469
10470 To avoid the use of compiler switches, the configuration
10471 pragma @code{No_Strict_Aliasing} with no parameters may be
10472 used to specify that for all access types, the strict
10473 aliasing optimization should be suppressed.
10474
10475 However, these approaches are still overkill, in that they causes
10476 all manipulations of all access values to be deoptimized. A more
10477 refined approach is to concentrate attention on the specific
10478 access type identified as problematic.
10479
10480 First, if a careful analysis of uses of the pointer shows
10481 that there are no possible problematic references, then
10482 the warning can be suppressed by bracketing the
10483 instantiation of @code{Unchecked_Conversion} to turn
10484 the warning off:
10485
10486 @smallexample @c ada
10487    pragma Warnings (Off);
10488    function to_a2u is
10489      new Unchecked_Conversion (a1, a2);
10490    pragma Warnings (On);
10491 @end smallexample
10492
10493 @noindent
10494 Of course that approach is not appropriate for this particular
10495 example, since indeed there is a problematic reference. In this
10496 case we can take one of two other approaches.
10497
10498 The first possibility is to move the instantiation of unchecked
10499 conversion to the unit in which the type is declared. In
10500 this example, we would move the instantiation of
10501 @code{Unchecked_Conversion} from the body of package
10502 @code{p2} to the spec of package @code{p1}. Now the
10503 warning disappears. That's because any use of the
10504 access type knows there is a suspicious unchecked
10505 conversion, and the strict aliasing optimization
10506 is automatically suppressed for the type.
10507
10508 If it is not practical to move the unchecked conversion to the same unit
10509 in which the destination access type is declared (perhaps because the
10510 source type is not visible in that unit), you may use pragma
10511 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10512 same declarative sequence as the declaration of the access type:
10513
10514 @smallexample @c ada
10515    type a2 is access int2;
10516    pragma No_Strict_Aliasing (a2);
10517 @end smallexample
10518
10519 @noindent
10520 Here again, the compiler now knows that the strict aliasing optimization
10521 should be suppressed for any reference to type @code{a2} and the
10522 expected behavior is obtained.
10523
10524 Finally, note that although the compiler can generate warnings for
10525 simple cases of unchecked conversions, there are tricker and more
10526 indirect ways of creating type incorrect aliases which the compiler
10527 cannot detect. Examples are the use of address overlays and unchecked
10528 conversions involving composite types containing access types as
10529 components. In such cases, no warnings are generated, but there can
10530 still be aliasing problems. One safe coding practice is to forbid the
10531 use of address clauses for type overlaying, and to allow unchecked
10532 conversion only for primitive types. This is not really a significant
10533 restriction since any possible desired effect can be achieved by
10534 unchecked conversion of access values.
10535
10536 The aliasing analysis done in strict aliasing mode can certainly
10537 have significant benefits. We have seen cases of large scale
10538 application code where the time is increased by up to 5% by turning
10539 this optimization off. If you have code that includes significant
10540 usage of unchecked conversion, you might want to just stick with
10541 @option{-O1} and avoid the entire issue. If you get adequate
10542 performance at this level of optimization level, that's probably
10543 the safest approach. If tests show that you really need higher
10544 levels of optimization, then you can experiment with @option{-O2}
10545 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10546 has on size and speed of the code. If you really need to use
10547 @option{-O2} with strict aliasing in effect, then you should
10548 review any uses of unchecked conversion of access types,
10549 particularly if you are getting the warnings described above.
10550
10551 @ifset vms
10552 @node Coverage Analysis
10553 @subsection Coverage Analysis
10554
10555 @noindent
10556 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10557 the user to determine the distribution of execution time across a program,
10558 @pxref{Profiling} for details of usage.
10559 @end ifset
10560
10561
10562 @node Text_IO Suggestions
10563 @section @code{Text_IO} Suggestions
10564 @cindex @code{Text_IO} and performance
10565
10566 @noindent
10567 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10568 the requirement of maintaining page and line counts. If performance
10569 is critical, a recommendation is to use @code{Stream_IO} instead of
10570 @code{Text_IO} for volume output, since this package has less overhead.
10571
10572 If @code{Text_IO} must be used, note that by default output to the standard
10573 output and standard error files is unbuffered (this provides better
10574 behavior when output statements are used for debugging, or if the
10575 progress of a program is observed by tracking the output, e.g. by
10576 using the Unix @command{tail -f} command to watch redirected output.
10577
10578 If you are generating large volumes of output with @code{Text_IO} and
10579 performance is an important factor, use a designated file instead
10580 of the standard output file, or change the standard output file to
10581 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10582
10583
10584
10585 @node Reducing Size of Ada Executables with gnatelim
10586 @section Reducing Size of Ada Executables with @code{gnatelim}
10587 @findex gnatelim
10588
10589 @noindent
10590 This section describes @command{gnatelim}, a tool which detects unused
10591 subprograms and helps the compiler to create a smaller executable for your
10592 program.
10593
10594 @menu
10595 * About gnatelim::
10596 * Running gnatelim::
10597 * Correcting the List of Eliminate Pragmas::
10598 * Making Your Executables Smaller::
10599 * Summary of the gnatelim Usage Cycle::
10600 @end menu
10601
10602 @node About gnatelim
10603 @subsection About @code{gnatelim}
10604
10605 @noindent
10606 When a program shares a set of Ada
10607 packages with other programs, it may happen that this program uses
10608 only a fraction of the subprograms defined in these packages. The code
10609 created for these unused subprograms increases the size of the executable.
10610
10611 @code{gnatelim} tracks unused subprograms in an Ada program and
10612 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10613 subprograms that are declared but never called. By placing the list of
10614 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10615 recompiling your program, you may decrease the size of its executable,
10616 because the compiler will not generate the code for 'eliminated' subprograms.
10617 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10618 information about this pragma.
10619
10620 @code{gnatelim} needs as its input data the name of the main subprogram
10621 and a bind file for a main subprogram.
10622
10623 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10624 the main subprogram. @code{gnatelim} can work with both Ada and C
10625 bind files; when both are present, it uses the Ada bind file.
10626 The following commands will build the program and create the bind file:
10627
10628 @smallexample
10629 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10630 $ gnatbind main_prog
10631 @end smallexample
10632
10633 Note that @code{gnatelim} needs neither object nor ALI files.
10634
10635 @node Running gnatelim
10636 @subsection Running @code{gnatelim}
10637
10638 @noindent
10639 @code{gnatelim} has the following command-line interface:
10640
10641 @smallexample
10642 $ gnatelim @ovar{options} name
10643 @end smallexample
10644
10645 @noindent
10646 @code{name} should be a name of a source file that contains the main subprogram
10647 of a program (partition).
10648
10649 @code{gnatelim} has the following switches:
10650
10651 @table @option
10652 @c !sort!
10653 @item ^-q^/QUIET^
10654 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10655 Quiet mode: by default @code{gnatelim} outputs to the standard error
10656 stream the number of program units left to be processed. This option turns
10657 this trace off.
10658
10659 @item ^-v^/VERBOSE^
10660 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10661 Verbose mode: @code{gnatelim} version information is printed as Ada
10662 comments to the standard output stream. Also, in addition to the number of
10663 program units left @code{gnatelim} will output the name of the current unit
10664 being processed.
10665
10666 @item ^-a^/ALL^
10667 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10668 Also look for subprograms from the GNAT run time that can be eliminated. Note
10669 that when @file{gnat.adc} is produced using this switch, the entire program
10670 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10671
10672 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10673 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10674 When looking for source files also look in directory @var{dir}. Specifying
10675 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10676 sources in the current directory.
10677
10678 @item ^-b^/BIND_FILE=^@var{bind_file}
10679 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10680 Specifies @var{bind_file} as the bind file to process. If not set, the name
10681 of the bind file is computed from the full expanded Ada name
10682 of a main subprogram.
10683
10684 @item ^-C^/CONFIG_FILE=^@var{config_file}
10685 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10686 Specifies a file @var{config_file} that contains configuration pragmas. The
10687 file must be specified with full path.
10688
10689 @item ^--GCC^/COMPILER^=@var{compiler_name}
10690 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10691 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10692 available on the path.
10693
10694 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10695 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10696 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10697 available on the path.
10698 @end table
10699
10700 @noindent
10701 @code{gnatelim} sends its output to the standard output stream, and all the
10702 tracing and debug information is sent to the standard error stream.
10703 In order to produce a proper GNAT configuration file
10704 @file{gnat.adc}, redirection must be used:
10705
10706 @smallexample
10707 @ifset vms
10708 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10709 @end ifset
10710 @ifclear vms
10711 $ gnatelim main_prog.adb > gnat.adc
10712 @end ifclear
10713 @end smallexample
10714
10715 @ifclear vms
10716 @noindent
10717 or
10718
10719 @smallexample
10720 $ gnatelim main_prog.adb >> gnat.adc
10721 @end smallexample
10722
10723 @noindent
10724 in order to append the @code{gnatelim} output to the existing contents of
10725 @file{gnat.adc}.
10726 @end ifclear
10727
10728 @node Correcting the List of Eliminate Pragmas
10729 @subsection Correcting the List of Eliminate Pragmas
10730
10731 @noindent
10732 In some rare cases @code{gnatelim} may try to eliminate
10733 subprograms that are actually called in the program. In this case, the
10734 compiler will generate an error message of the form:
10735
10736 @smallexample
10737 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10738 @end smallexample
10739
10740 @noindent
10741 You will need to manually remove the wrong @code{Eliminate} pragmas from
10742 the @file{gnat.adc} file. You should recompile your program
10743 from scratch after that, because you need a consistent @file{gnat.adc} file
10744 during the entire compilation.
10745
10746 @node Making Your Executables Smaller
10747 @subsection Making Your Executables Smaller
10748
10749 @noindent
10750 In order to get a smaller executable for your program you now have to
10751 recompile the program completely with the new @file{gnat.adc} file
10752 created by @code{gnatelim} in your current directory:
10753
10754 @smallexample
10755 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10756 @end smallexample
10757
10758 @noindent
10759 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10760 recompile everything
10761 with the set of pragmas @code{Eliminate} that you have obtained with
10762 @command{gnatelim}).
10763
10764 Be aware that the set of @code{Eliminate} pragmas is specific to each
10765 program. It is not recommended to merge sets of @code{Eliminate}
10766 pragmas created for different programs in one @file{gnat.adc} file.
10767
10768 @node Summary of the gnatelim Usage Cycle
10769 @subsection Summary of the gnatelim Usage Cycle
10770
10771 @noindent
10772 Here is a quick summary of the steps to be taken in order to reduce
10773 the size of your executables with @code{gnatelim}. You may use
10774 other GNAT options to control the optimization level,
10775 to produce the debugging information, to set search path, etc.
10776
10777 @enumerate
10778 @item
10779 Produce a bind file
10780
10781 @smallexample
10782 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10783 $ gnatbind main_prog
10784 @end smallexample
10785
10786 @item
10787 Generate a list of @code{Eliminate} pragmas
10788 @smallexample
10789 @ifset vms
10790 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10791 @end ifset
10792 @ifclear vms
10793 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10794 @end ifclear
10795 @end smallexample
10796
10797 @item
10798 Recompile the application
10799
10800 @smallexample
10801 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10802 @end smallexample
10803
10804 @end enumerate
10805
10806 @node Reducing Size of Executables with unused subprogram/data elimination
10807 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10808 @findex unused subprogram/data elimination
10809
10810 @noindent
10811 This section describes how you can eliminate unused subprograms and data from
10812 your executable just by setting options at compilation time.
10813
10814 @menu
10815 * About unused subprogram/data elimination::
10816 * Compilation options::
10817 * Example of unused subprogram/data elimination::
10818 @end menu
10819
10820 @node About unused subprogram/data elimination
10821 @subsection About unused subprogram/data elimination
10822
10823 @noindent
10824 By default, an executable contains all code and data of its composing objects
10825 (directly linked or coming from statically linked libraries), even data or code
10826 never used by this executable.
10827
10828 This feature will allow you to eliminate such unused code from your
10829 executable, making it smaller (in disk and in memory).
10830
10831 This functionality is available on all Linux platforms except for the IA-64
10832 architecture and on all cross platforms using the ELF binary file format.
10833 In both cases GNU binutils version 2.16 or later are required to enable it.
10834
10835 @node Compilation options
10836 @subsection Compilation options
10837
10838 @noindent
10839 The operation of eliminating the unused code and data from the final executable
10840 is directly performed by the linker.
10841
10842 In order to do this, it has to work with objects compiled with the
10843 following options:
10844 @option{-ffunction-sections} @option{-fdata-sections}.
10845 @cindex @option{-ffunction-sections} (@command{gcc})
10846 @cindex @option{-fdata-sections} (@command{gcc})
10847 These options are usable with C and Ada files.
10848 They will place respectively each
10849 function or data in a separate section in the resulting object file.
10850
10851 Once the objects and static libraries are created with these options, the
10852 linker can perform the dead code elimination. You can do this by setting
10853 the @option{-Wl,--gc-sections} option to gcc command or in the
10854 @option{-largs} section of @command{gnatmake}. This will perform a
10855 garbage collection of code and data never referenced.
10856
10857 If the linker performs a partial link (@option{-r} ld linker option), then you
10858 will need to provide one or several entry point using the
10859 @option{-e} / @option{--entry} ld option.
10860
10861 Note that objects compiled without the @option{-ffunction-sections} and
10862 @option{-fdata-sections} options can still be linked with the executable.
10863 However, no dead code elimination will be performed on those objects (they will
10864 be linked as is).
10865
10866 The GNAT static library is now compiled with -ffunction-sections and
10867 -fdata-sections on some platforms. This allows you to eliminate the unused code
10868 and data of the GNAT library from your executable.
10869
10870 @node Example of unused subprogram/data elimination
10871 @subsection Example of unused subprogram/data elimination
10872
10873 @noindent
10874 Here is a simple example:
10875
10876 @smallexample @c ada
10877 with Aux;
10878
10879 procedure Test is
10880 begin
10881    Aux.Used (10);
10882 end Test;
10883
10884 package Aux is
10885    Used_Data   : Integer;
10886    Unused_Data : Integer;
10887
10888    procedure Used   (Data : Integer);
10889    procedure Unused (Data : Integer);
10890 end Aux;
10891
10892 package body Aux is
10893    procedure Used (Data : Integer) is
10894    begin
10895       Used_Data := Data;
10896    end Used;
10897
10898    procedure Unused (Data : Integer) is
10899    begin
10900       Unused_Data := Data;
10901    end Unused;
10902 end Aux;
10903 @end smallexample
10904
10905 @noindent
10906 @code{Unused} and @code{Unused_Data} are never referenced in this code
10907 excerpt, and hence they may be safely removed from the final executable.
10908
10909 @smallexample
10910 $ gnatmake test
10911
10912 $ nm test | grep used
10913 020015f0 T aux__unused
10914 02005d88 B aux__unused_data
10915 020015cc T aux__used
10916 02005d84 B aux__used_data
10917
10918 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10919      -largs -Wl,--gc-sections
10920
10921 $ nm test | grep used
10922 02005350 T aux__used
10923 0201ffe0 B aux__used_data
10924 @end smallexample
10925
10926 @noindent
10927 It can be observed that the procedure @code{Unused} and the object
10928 @code{Unused_Data} are removed by the linker when using the
10929 appropriate options.
10930
10931 @c ********************************
10932 @node Renaming Files Using gnatchop
10933 @chapter Renaming Files Using @code{gnatchop}
10934 @findex gnatchop
10935
10936 @noindent
10937 This chapter discusses how to handle files with multiple units by using
10938 the @code{gnatchop} utility. This utility is also useful in renaming
10939 files to meet the standard GNAT default file naming conventions.
10940
10941 @menu
10942 * Handling Files with Multiple Units::
10943 * Operating gnatchop in Compilation Mode::
10944 * Command Line for gnatchop::
10945 * Switches for gnatchop::
10946 * Examples of gnatchop Usage::
10947 @end menu
10948
10949 @node Handling Files with Multiple Units
10950 @section Handling Files with Multiple Units
10951
10952 @noindent
10953 The basic compilation model of GNAT requires that a file submitted to the
10954 compiler have only one unit and there be a strict correspondence
10955 between the file name and the unit name.
10956
10957 The @code{gnatchop} utility allows both of these rules to be relaxed,
10958 allowing GNAT to process files which contain multiple compilation units
10959 and files with arbitrary file names. @code{gnatchop}
10960 reads the specified file and generates one or more output files,
10961 containing one unit per file. The unit and the file name correspond,
10962 as required by GNAT.
10963
10964 If you want to permanently restructure a set of ``foreign'' files so that
10965 they match the GNAT rules, and do the remaining development using the
10966 GNAT structure, you can simply use @command{gnatchop} once, generate the
10967 new set of files and work with them from that point on.
10968
10969 Alternatively, if you want to keep your files in the ``foreign'' format,
10970 perhaps to maintain compatibility with some other Ada compilation
10971 system, you can set up a procedure where you use @command{gnatchop} each
10972 time you compile, regarding the source files that it writes as temporary
10973 files that you throw away.
10974
10975 Note that if your file containing multiple units starts with a byte order
10976 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
10977 will each start with a copy of this BOM, meaning that they can be compiled
10978 automatically in UTF-8 mode without needing to specify an explicit encoding.
10979
10980 @node Operating gnatchop in Compilation Mode
10981 @section Operating gnatchop in Compilation Mode
10982
10983 @noindent
10984 The basic function of @code{gnatchop} is to take a file with multiple units
10985 and split it into separate files. The boundary between files is reasonably
10986 clear, except for the issue of comments and pragmas. In default mode, the
10987 rule is that any pragmas between units belong to the previous unit, except
10988 that configuration pragmas always belong to the following unit. Any comments
10989 belong to the following unit. These rules
10990 almost always result in the right choice of
10991 the split point without needing to mark it explicitly and most users will
10992 find this default to be what they want. In this default mode it is incorrect to
10993 submit a file containing only configuration pragmas, or one that ends in
10994 configuration pragmas, to @code{gnatchop}.
10995
10996 However, using a special option to activate ``compilation mode'',
10997 @code{gnatchop}
10998 can perform another function, which is to provide exactly the semantics
10999 required by the RM for handling of configuration pragmas in a compilation.
11000 In the absence of configuration pragmas (at the main file level), this
11001 option has no effect, but it causes such configuration pragmas to be handled
11002 in a quite different manner.
11003
11004 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11005 only configuration pragmas, then this file is appended to the
11006 @file{gnat.adc} file in the current directory. This behavior provides
11007 the required behavior described in the RM for the actions to be taken
11008 on submitting such a file to the compiler, namely that these pragmas
11009 should apply to all subsequent compilations in the same compilation
11010 environment. Using GNAT, the current directory, possibly containing a
11011 @file{gnat.adc} file is the representation
11012 of a compilation environment. For more information on the
11013 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11014
11015 Second, in compilation mode, if @code{gnatchop}
11016 is given a file that starts with
11017 configuration pragmas, and contains one or more units, then these
11018 configuration pragmas are prepended to each of the chopped files. This
11019 behavior provides the required behavior described in the RM for the
11020 actions to be taken on compiling such a file, namely that the pragmas
11021 apply to all units in the compilation, but not to subsequently compiled
11022 units.
11023
11024 Finally, if configuration pragmas appear between units, they are appended
11025 to the previous unit. This results in the previous unit being illegal,
11026 since the compiler does not accept configuration pragmas that follow
11027 a unit. This provides the required RM behavior that forbids configuration
11028 pragmas other than those preceding the first compilation unit of a
11029 compilation.
11030
11031 For most purposes, @code{gnatchop} will be used in default mode. The
11032 compilation mode described above is used only if you need exactly
11033 accurate behavior with respect to compilations, and you have files
11034 that contain multiple units and configuration pragmas. In this
11035 circumstance the use of @code{gnatchop} with the compilation mode
11036 switch provides the required behavior, and is for example the mode
11037 in which GNAT processes the ACVC tests.
11038
11039 @node Command Line for gnatchop
11040 @section Command Line for @code{gnatchop}
11041
11042 @noindent
11043 The @code{gnatchop} command has the form:
11044
11045 @smallexample
11046 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11047       @ovar{directory}
11048 @end smallexample
11049
11050 @noindent
11051 The only required argument is the file name of the file to be chopped.
11052 There are no restrictions on the form of this file name. The file itself
11053 contains one or more Ada units, in normal GNAT format, concatenated
11054 together. As shown, more than one file may be presented to be chopped.
11055
11056 When run in default mode, @code{gnatchop} generates one output file in
11057 the current directory for each unit in each of the files.
11058
11059 @var{directory}, if specified, gives the name of the directory to which
11060 the output files will be written. If it is not specified, all files are
11061 written to the current directory.
11062
11063 For example, given a
11064 file called @file{hellofiles} containing
11065
11066 @smallexample @c ada
11067 @group
11068 @cartouche
11069 procedure hello;
11070
11071 with Text_IO; use Text_IO;
11072 procedure hello is
11073 begin
11074    Put_Line ("Hello");
11075 end hello;
11076 @end cartouche
11077 @end group
11078 @end smallexample
11079
11080 @noindent
11081 the command
11082
11083 @smallexample
11084 $ gnatchop ^hellofiles^HELLOFILES.^
11085 @end smallexample
11086
11087 @noindent
11088 generates two files in the current directory, one called
11089 @file{hello.ads} containing the single line that is the procedure spec,
11090 and the other called @file{hello.adb} containing the remaining text. The
11091 original file is not affected. The generated files can be compiled in
11092 the normal manner.
11093
11094 @noindent
11095 When gnatchop is invoked on a file that is empty or that contains only empty
11096 lines and/or comments, gnatchop will not fail, but will not produce any
11097 new sources.
11098
11099 For example, given a
11100 file called @file{toto.txt} containing
11101
11102 @smallexample @c ada
11103 @group
11104 @cartouche
11105 --  Just a comment
11106 @end cartouche
11107 @end group
11108 @end smallexample
11109
11110 @noindent
11111 the command
11112
11113 @smallexample
11114 $ gnatchop ^toto.txt^TOT.TXT^
11115 @end smallexample
11116
11117 @noindent
11118 will not produce any new file and will result in the following warnings:
11119
11120 @smallexample
11121 toto.txt:1:01: warning: empty file, contains no compilation units
11122 no compilation units found
11123 no source files written
11124 @end smallexample
11125
11126 @node Switches for gnatchop
11127 @section Switches for @code{gnatchop}
11128
11129 @noindent
11130 @command{gnatchop} recognizes the following switches:
11131
11132 @table @option
11133 @c !sort!
11134
11135 @item --version
11136 @cindex @option{--version} @command{gnatchop}
11137 Display Copyright and version, then exit disregarding all other options.
11138
11139 @item --help
11140 @cindex @option{--help} @command{gnatchop}
11141 If @option{--version} was not used, display usage, then exit disregarding
11142 all other options.
11143
11144 @item ^-c^/COMPILATION^
11145 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11146 Causes @code{gnatchop} to operate in compilation mode, in which
11147 configuration pragmas are handled according to strict RM rules. See
11148 previous section for a full description of this mode.
11149
11150 @ifclear vms
11151 @item -gnat@var{xxx}
11152 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11153 used to parse the given file. Not all @var{xxx} options make sense,
11154 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11155 process a source file that uses Latin-2 coding for identifiers.
11156 @end ifclear
11157
11158 @item ^-h^/HELP^
11159 Causes @code{gnatchop} to generate a brief help summary to the standard
11160 output file showing usage information.
11161
11162 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11163 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11164 Limit generated file names to the specified number @code{mm}
11165 of characters.
11166 This is useful if the
11167 resulting set of files is required to be interoperable with systems
11168 which limit the length of file names.
11169 @ifset vms
11170 If no value is given, or
11171 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11172 a default of 39, suitable for OpenVMS Alpha
11173 Systems, is assumed
11174 @end ifset
11175 @ifclear vms
11176 No space is allowed between the @option{-k} and the numeric value. The numeric
11177 value may be omitted in which case a default of @option{-k8},
11178 suitable for use
11179 with DOS-like file systems, is used. If no @option{-k} switch
11180 is present then
11181 there is no limit on the length of file names.
11182 @end ifclear
11183
11184 @item ^-p^/PRESERVE^
11185 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11186 Causes the file ^modification^creation^ time stamp of the input file to be
11187 preserved and used for the time stamp of the output file(s). This may be
11188 useful for preserving coherency of time stamps in an environment where
11189 @code{gnatchop} is used as part of a standard build process.
11190
11191 @item ^-q^/QUIET^
11192 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11193 Causes output of informational messages indicating the set of generated
11194 files to be suppressed. Warnings and error messages are unaffected.
11195
11196 @item ^-r^/REFERENCE^
11197 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11198 @findex Source_Reference
11199 Generate @code{Source_Reference} pragmas. Use this switch if the output
11200 files are regarded as temporary and development is to be done in terms
11201 of the original unchopped file. This switch causes
11202 @code{Source_Reference} pragmas to be inserted into each of the
11203 generated files to refers back to the original file name and line number.
11204 The result is that all error messages refer back to the original
11205 unchopped file.
11206 In addition, the debugging information placed into the object file (when
11207 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11208 specified)
11209 also refers back to this original file so that tools like profilers and
11210 debuggers will give information in terms of the original unchopped file.
11211
11212 If the original file to be chopped itself contains
11213 a @code{Source_Reference}
11214 pragma referencing a third file, then gnatchop respects
11215 this pragma, and the generated @code{Source_Reference} pragmas
11216 in the chopped file refer to the original file, with appropriate
11217 line numbers. This is particularly useful when @code{gnatchop}
11218 is used in conjunction with @code{gnatprep} to compile files that
11219 contain preprocessing statements and multiple units.
11220
11221 @item ^-v^/VERBOSE^
11222 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11223 Causes @code{gnatchop} to operate in verbose mode. The version
11224 number and copyright notice are output, as well as exact copies of
11225 the gnat1 commands spawned to obtain the chop control information.
11226
11227 @item ^-w^/OVERWRITE^
11228 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11229 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11230 fatal error if there is already a file with the same name as a
11231 file it would otherwise output, in other words if the files to be
11232 chopped contain duplicated units. This switch bypasses this
11233 check, and causes all but the last instance of such duplicated
11234 units to be skipped.
11235
11236 @ifclear vms
11237 @item --GCC=@var{xxxx}
11238 @cindex @option{--GCC=} (@code{gnatchop})
11239 Specify the path of the GNAT parser to be used. When this switch is used,
11240 no attempt is made to add the prefix to the GNAT parser executable.
11241 @end ifclear
11242 @end table
11243
11244 @node Examples of gnatchop Usage
11245 @section Examples of @code{gnatchop} Usage
11246
11247 @table @code
11248 @ifset vms
11249 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11250 @end ifset
11251 @ifclear vms
11252 @item gnatchop -w hello_s.ada prerelease/files
11253 @end ifclear
11254
11255 Chops the source file @file{hello_s.ada}. The output files will be
11256 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11257 overwriting any
11258 files with matching names in that directory (no files in the current
11259 directory are modified).
11260
11261 @item gnatchop ^archive^ARCHIVE.^
11262 Chops the source file @file{^archive^ARCHIVE.^}
11263 into the current directory. One
11264 useful application of @code{gnatchop} is in sending sets of sources
11265 around, for example in email messages. The required sources are simply
11266 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11267 command), and then
11268 @command{gnatchop} is used at the other end to reconstitute the original
11269 file names.
11270
11271 @item gnatchop file1 file2 file3 direc
11272 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11273 the resulting files in the directory @file{direc}. Note that if any units
11274 occur more than once anywhere within this set of files, an error message
11275 is generated, and no files are written. To override this check, use the
11276 @option{^-w^/OVERWRITE^} switch,
11277 in which case the last occurrence in the last file will
11278 be the one that is output, and earlier duplicate occurrences for a given
11279 unit will be skipped.
11280 @end table
11281
11282 @node Configuration Pragmas
11283 @chapter Configuration Pragmas
11284 @cindex Configuration pragmas
11285 @cindex Pragmas, configuration
11286
11287 @noindent
11288 Configuration pragmas include those pragmas described as
11289 such in the Ada Reference Manual, as well as
11290 implementation-dependent pragmas that are configuration pragmas.
11291 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11292 for details on these additional GNAT-specific configuration pragmas.
11293 Most notably, the pragma @code{Source_File_Name}, which allows
11294 specifying non-default names for source files, is a configuration
11295 pragma. The following is a complete list of configuration pragmas
11296 recognized by GNAT:
11297
11298 @smallexample
11299    Ada_83
11300    Ada_95
11301    Ada_05
11302    Ada_2005
11303    Assertion_Policy
11304    C_Pass_By_Copy
11305    Check_Name
11306    Check_Policy
11307    Compile_Time_Error
11308    Compile_Time_Warning
11309    Compiler_Unit
11310    Component_Alignment
11311    Debug_Policy
11312    Detect_Blocking
11313    Discard_Names
11314    Elaboration_Checks
11315    Eliminate
11316    Extend_System
11317    External_Name_Casing
11318    Fast_Math
11319    Favor_Top_Level
11320    Float_Representation
11321    Implicit_Packing
11322    Initialize_Scalars
11323    Interrupt_State
11324    License
11325    Locking_Policy
11326    Long_Float
11327    No_Run_Time
11328    No_Strict_Aliasing
11329    Normalize_Scalars
11330    Optimize_Alignment
11331    Persistent_BSS
11332    Polling
11333    Priority_Specific_Dispatching
11334    Profile
11335    Profile_Warnings
11336    Propagate_Exceptions
11337    Queuing_Policy
11338    Ravenscar
11339    Restricted_Run_Time
11340    Restrictions
11341    Restrictions_Warnings
11342    Reviewable
11343    Source_File_Name
11344    Source_File_Name_Project
11345    Style_Checks
11346    Suppress
11347    Suppress_Exception_Locations
11348    Task_Dispatching_Policy
11349    Universal_Data
11350    Unsuppress
11351    Use_VADS_Size
11352    Validity_Checks
11353    Warnings
11354    Wide_Character_Encoding
11355
11356 @end smallexample
11357
11358 @menu
11359 * Handling of Configuration Pragmas::
11360 * The Configuration Pragmas Files::
11361 @end menu
11362
11363 @node Handling of Configuration Pragmas
11364 @section Handling of Configuration Pragmas
11365
11366 Configuration pragmas may either appear at the start of a compilation
11367 unit, in which case they apply only to that unit, or they may apply to
11368 all compilations performed in a given compilation environment.
11369
11370 GNAT also provides the @code{gnatchop} utility to provide an automatic
11371 way to handle configuration pragmas following the semantics for
11372 compilations (that is, files with multiple units), described in the RM.
11373 See @ref{Operating gnatchop in Compilation Mode} for details.
11374 However, for most purposes, it will be more convenient to edit the
11375 @file{gnat.adc} file that contains configuration pragmas directly,
11376 as described in the following section.
11377
11378 @node The Configuration Pragmas Files
11379 @section The Configuration Pragmas Files
11380 @cindex @file{gnat.adc}
11381
11382 @noindent
11383 In GNAT a compilation environment is defined by the current
11384 directory at the time that a compile command is given. This current
11385 directory is searched for a file whose name is @file{gnat.adc}. If
11386 this file is present, it is expected to contain one or more
11387 configuration pragmas that will be applied to the current compilation.
11388 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11389 considered.
11390
11391 Configuration pragmas may be entered into the @file{gnat.adc} file
11392 either by running @code{gnatchop} on a source file that consists only of
11393 configuration pragmas, or more conveniently  by
11394 direct editing of the @file{gnat.adc} file, which is a standard format
11395 source file.
11396
11397 In addition to @file{gnat.adc}, additional files containing configuration
11398 pragmas may be applied to the current compilation using the switch
11399 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11400 contains only configuration pragmas. These configuration pragmas are
11401 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11402 is present and switch @option{-gnatA} is not used).
11403
11404 It is allowed to specify several switches @option{-gnatec}, all of which
11405 will be taken into account.
11406
11407 If you are using project file, a separate mechanism is provided using
11408 project attributes, see @ref{Specifying Configuration Pragmas} for more
11409 details.
11410
11411 @ifset vms
11412 Of special interest to GNAT OpenVMS Alpha is the following
11413 configuration pragma:
11414
11415 @smallexample @c ada
11416 @cartouche
11417 pragma Extend_System (Aux_DEC);
11418 @end cartouche
11419 @end smallexample
11420
11421 @noindent
11422 In the presence of this pragma, GNAT adds to the definition of the
11423 predefined package SYSTEM all the additional types and subprograms that are
11424 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11425 @end ifset
11426
11427 @node Handling Arbitrary File Naming Conventions Using gnatname
11428 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11429 @cindex Arbitrary File Naming Conventions
11430
11431 @menu
11432 * Arbitrary File Naming Conventions::
11433 * Running gnatname::
11434 * Switches for gnatname::
11435 * Examples of gnatname Usage::
11436 @end menu
11437
11438 @node Arbitrary File Naming Conventions
11439 @section Arbitrary File Naming Conventions
11440
11441 @noindent
11442 The GNAT compiler must be able to know the source file name of a compilation
11443 unit.  When using the standard GNAT default file naming conventions
11444 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11445 does not need additional information.
11446
11447 @noindent
11448 When the source file names do not follow the standard GNAT default file naming
11449 conventions, the GNAT compiler must be given additional information through
11450 a configuration pragmas file (@pxref{Configuration Pragmas})
11451 or a project file.
11452 When the non-standard file naming conventions are well-defined,
11453 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11454 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11455 if the file naming conventions are irregular or arbitrary, a number
11456 of pragma @code{Source_File_Name} for individual compilation units
11457 must be defined.
11458 To help maintain the correspondence between compilation unit names and
11459 source file names within the compiler,
11460 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11461 set of files.
11462
11463 @node Running gnatname
11464 @section Running @code{gnatname}
11465
11466 @noindent
11467 The usual form of the @code{gnatname} command is
11468
11469 @smallexample
11470 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11471       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11472 @end smallexample
11473
11474 @noindent
11475 All of the arguments are optional. If invoked without any argument,
11476 @code{gnatname} will display its usage.
11477
11478 @noindent
11479 When used with at least one naming pattern, @code{gnatname} will attempt to
11480 find all the compilation units in files that follow at least one of the
11481 naming patterns. To find these compilation units,
11482 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11483 regular files.
11484
11485 @noindent
11486 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11487 Each Naming Pattern is enclosed between double quotes.
11488 A Naming Pattern is a regular expression similar to the wildcard patterns
11489 used in file names by the Unix shells or the DOS prompt.
11490
11491 @noindent
11492 @code{gnatname} may be called with several sections of directories/patterns.
11493 Sections are separated by switch @code{--and}. In each section, there must be
11494 at least one pattern. If no directory is specified in a section, the current
11495 directory (or the project directory is @code{-P} is used) is implied.
11496 The options other that the directory switches and the patterns apply globally
11497 even if they are in different sections.
11498
11499 @noindent
11500 Examples of Naming Patterns are
11501
11502 @smallexample
11503    "*.[12].ada"
11504    "*.ad[sb]*"
11505    "body_*"    "spec_*"
11506 @end smallexample
11507
11508 @noindent
11509 For a more complete description of the syntax of Naming Patterns,
11510 see the second kind of regular expressions described in @file{g-regexp.ads}
11511 (the ``Glob'' regular expressions).
11512
11513 @noindent
11514 When invoked with no switch @code{-P}, @code{gnatname} will create a
11515 configuration pragmas file @file{gnat.adc} in the current working directory,
11516 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11517 unit.
11518
11519 @node Switches for gnatname
11520 @section Switches for @code{gnatname}
11521
11522 @noindent
11523 Switches for @code{gnatname} must precede any specified Naming Pattern.
11524
11525 @noindent
11526 You may specify any of the following switches to @code{gnatname}:
11527
11528 @table @option
11529 @c !sort!
11530
11531 @item --version
11532 @cindex @option{--version} @command{gnatname}
11533 Display Copyright and version, then exit disregarding all other options.
11534
11535 @item --help
11536 @cindex @option{--help} @command{gnatname}
11537 If @option{--version} was not used, display usage, then exit disregarding
11538 all other options.
11539
11540 @item --and
11541 Start another section of directories/patterns.
11542
11543 @item ^-c^/CONFIG_FILE=^@file{file}
11544 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11545 Create a configuration pragmas file @file{file} (instead of the default
11546 @file{gnat.adc}).
11547 @ifclear vms
11548 There may be zero, one or more space between @option{-c} and
11549 @file{file}.
11550 @end ifclear
11551 @file{file} may include directory information. @file{file} must be
11552 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11553 When a switch @option{^-c^/CONFIG_FILE^} is
11554 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11555
11556 @item ^-d^/SOURCE_DIRS=^@file{dir}
11557 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11558 Look for source files in directory @file{dir}. There may be zero, one or more
11559 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11560 When a switch @option{^-d^/SOURCE_DIRS^}
11561 is specified, the current working directory will not be searched for source
11562 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11563 or @option{^-D^/DIR_FILES^} switch.
11564 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11565 If @file{dir} is a relative path, it is relative to the directory of
11566 the configuration pragmas file specified with switch
11567 @option{^-c^/CONFIG_FILE^},
11568 or to the directory of the project file specified with switch
11569 @option{^-P^/PROJECT_FILE^} or,
11570 if neither switch @option{^-c^/CONFIG_FILE^}
11571 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11572 current working directory. The directory
11573 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11574
11575 @item ^-D^/DIRS_FILE=^@file{file}
11576 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11577 Look for source files in all directories listed in text file @file{file}.
11578 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11579 and @file{file}.
11580 @file{file} must be an existing, readable text file.
11581 Each nonempty line in @file{file} must be a directory.
11582 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11583 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11584 @file{file}.
11585
11586 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11587 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11588 Foreign patterns. Using this switch, it is possible to add sources of languages
11589 other than Ada to the list of sources of a project file.
11590 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11591 For example,
11592 @smallexample
11593 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11594 @end smallexample
11595 @noindent
11596 will look for Ada units in all files with the @file{.ada} extension,
11597 and will add to the list of file for project @file{prj.gpr} the C files
11598 with extension @file{.^c^C^}.
11599
11600 @item ^-h^/HELP^
11601 @cindex @option{^-h^/HELP^} (@code{gnatname})
11602 Output usage (help) information. The output is written to @file{stdout}.
11603
11604 @item ^-P^/PROJECT_FILE=^@file{proj}
11605 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11606 Create or update project file @file{proj}. There may be zero, one or more space
11607 between @option{-P} and @file{proj}. @file{proj} may include directory
11608 information. @file{proj} must be writable.
11609 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11610 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11611 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11612
11613 @item ^-v^/VERBOSE^
11614 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11615 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11616 This includes name of the file written, the name of the directories to search
11617 and, for each file in those directories whose name matches at least one of
11618 the Naming Patterns, an indication of whether the file contains a unit,
11619 and if so the name of the unit.
11620
11621 @item ^-v -v^/VERBOSE /VERBOSE^
11622 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11623 Very Verbose mode. In addition to the output produced in verbose mode,
11624 for each file in the searched directories whose name matches none of
11625 the Naming Patterns, an indication is given that there is no match.
11626
11627 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11628 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11629 Excluded patterns. Using this switch, it is possible to exclude some files
11630 that would match the name patterns. For example,
11631 @smallexample
11632 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11633 @end smallexample
11634 @noindent
11635 will look for Ada units in all files with the @file{.ada} extension,
11636 except those whose names end with @file{_nt.ada}.
11637
11638 @end table
11639
11640 @node Examples of gnatname Usage
11641 @section Examples of @code{gnatname} Usage
11642
11643 @ifset vms
11644 @smallexample
11645 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11646 @end smallexample
11647 @end ifset
11648
11649 @ifclear vms
11650 @smallexample
11651 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11652 @end smallexample
11653 @end ifclear
11654
11655 @noindent
11656 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11657 and be writable. In addition, the directory
11658 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11659 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11660
11661 @ifclear vms
11662 Note the optional spaces after @option{-c} and @option{-d}.
11663 @end ifclear
11664
11665 @smallexample
11666 @ifclear vms
11667 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11668   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11669 @end ifclear
11670 @ifset vms
11671 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11672   /EXCLUDED_PATTERN=*_nt_body.ada
11673   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11674   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11675 @end ifset
11676 @end smallexample
11677
11678 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11679 even in conjunction with one or several switches
11680 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11681 are used in this example.
11682
11683 @c *****************************************
11684 @c * G N A T  P r o j e c t  M a n a g e r *
11685 @c *****************************************
11686 @node GNAT Project Manager
11687 @chapter GNAT Project Manager
11688
11689 @menu
11690 * Introduction::
11691 * Examples of Project Files::
11692 * Project File Syntax::
11693 * Objects and Sources in Project Files::
11694 * Importing Projects::
11695 * Project Extension::
11696 * Project Hierarchy Extension::
11697 * External References in Project Files::
11698 * Packages in Project Files::
11699 * Variables from Imported Projects::
11700 * Naming Schemes::
11701 * Library Projects::
11702 * Stand-alone Library Projects::
11703 * Switches Related to Project Files::
11704 * Tools Supporting Project Files::
11705 * An Extended Example::
11706 * Project File Complete Syntax::
11707 @end menu
11708
11709 @c ****************
11710 @c * Introduction *
11711 @c ****************
11712
11713 @node Introduction
11714 @section Introduction
11715
11716 @noindent
11717 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11718 you to manage complex builds involving a number of source files, directories,
11719 and compilation options for different system configurations. In particular,
11720 project files allow you to specify:
11721 @itemize @bullet
11722 @item
11723 The directory or set of directories containing the source files, and/or the
11724 names of the specific source files themselves
11725 @item
11726 The directory in which the compiler's output
11727 (@file{ALI} files, object files, tree files) is to be placed
11728 @item
11729 The directory in which the executable programs is to be placed
11730 @item
11731 ^Switch^Switch^ settings for any of the project-enabled tools
11732 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11733 @code{gnatfind}); you can apply these settings either globally or to individual
11734 compilation units.
11735 @item
11736 The source files containing the main subprogram(s) to be built
11737 @item
11738 The source programming language(s) (currently Ada and/or C)
11739 @item
11740 Source file naming conventions; you can specify these either globally or for
11741 individual compilation units
11742 @end itemize
11743
11744 @menu
11745 * Project Files::
11746 @end menu
11747
11748 @node Project Files
11749 @subsection Project Files
11750
11751 @noindent
11752 Project files are written in a syntax close to that of Ada, using  familiar
11753 notions such as packages, context clauses, declarations, default values,
11754 assignments, and inheritance. Finally, project files can be built
11755 hierarchically from other project files, simplifying complex system
11756 integration and project reuse.
11757
11758 A @dfn{project} is a specific set of values for various compilation properties.
11759 The settings for a given project are described by means of
11760 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11761 Property values in project files are either strings or lists of strings.
11762 Properties that are not explicitly set receive default values.  A project
11763 file may interrogate the values of @dfn{external variables} (user-defined
11764 command-line switches or environment variables), and it may specify property
11765 settings conditionally, based on the value of such variables.
11766
11767 In simple cases, a project's source files depend only on other source files
11768 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11769 used in
11770 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11771 the Project Manager also allows more sophisticated arrangements,
11772 where the source files in one project depend on source files in other
11773 projects:
11774 @itemize @bullet
11775 @item
11776 One project can @emph{import} other projects containing needed source files.
11777 @item
11778 You can organize GNAT projects in a hierarchy: a @emph{child} project
11779 can extend a @emph{parent} project, inheriting the parent's source files and
11780 optionally overriding any of them with alternative versions
11781 @end itemize
11782
11783 @noindent
11784 More generally, the Project Manager lets you structure large development
11785 efforts into hierarchical subsystems, where build decisions are delegated
11786 to the subsystem level, and thus different compilation environments
11787 (^switch^switch^ settings) used for different subsystems.
11788
11789 The Project Manager is invoked through the
11790 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11791 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11792 @ifclear vms
11793 There may be zero, one or more spaces between @option{-P} and
11794 @option{@emph{projectfile}}.
11795 @end ifclear
11796 If you want to define (on the command line) an external variable that is
11797 queried by the project file, you must use the
11798 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11799 The Project Manager parses and interprets the project file, and drives the
11800 invoked tool based on the project settings.
11801
11802 The Project Manager supports a wide range of development strategies,
11803 for systems of all sizes.  Here are some typical practices that are
11804 easily handled:
11805 @itemize @bullet
11806 @item
11807 Using a common set of source files, but generating object files in different
11808 directories via different ^switch^switch^ settings
11809 @item
11810 Using a mostly-shared set of source files, but with different versions of
11811 some unit or units
11812 @end itemize
11813
11814 @noindent
11815 The destination of an executable can be controlled inside a project file
11816 using the @option{^-o^-o^}
11817 ^switch^switch^.
11818 In the absence of such a ^switch^switch^ either inside
11819 the project file or on the command line, any executable files generated by
11820 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11821 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11822 in the object directory of the project.
11823
11824 You can use project files to achieve some of the effects of a source
11825 versioning system (for example, defining separate projects for
11826 the different sets of sources that comprise different releases) but the
11827 Project Manager is independent of any source configuration management tools
11828 that might be used by the developers.
11829
11830 The next section introduces the main features of GNAT's project facility
11831 through a sequence of examples; subsequent sections will present the syntax
11832 and semantics in more detail. A more formal description of the project
11833 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11834 Reference Manual}.
11835
11836 @c *****************************
11837 @c * Examples of Project Files *
11838 @c *****************************
11839
11840 @node Examples of Project Files
11841 @section Examples of Project Files
11842 @noindent
11843 This section illustrates some of the typical uses of project files and
11844 explains their basic structure and behavior.
11845
11846 @menu
11847 * Common Sources with Different ^Switches^Switches^ and Directories::
11848 * Using External Variables::
11849 * Importing Other Projects::
11850 * Extending a Project::
11851 @end menu
11852
11853 @node Common Sources with Different ^Switches^Switches^ and Directories
11854 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11855
11856 @menu
11857 * Source Files::
11858 * Specifying the Object Directory::
11859 * Specifying the Exec Directory::
11860 * Project File Packages::
11861 * Specifying ^Switch^Switch^ Settings::
11862 * Main Subprograms::
11863 * Executable File Names::
11864 * Source File Naming Conventions::
11865 * Source Language(s)::
11866 @end menu
11867
11868 @noindent
11869 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11870 @file{proc.adb} are in the @file{/common} directory.  The file
11871 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11872 package @code{Pack}.  We want to compile these source files under two sets
11873 of ^switches^switches^:
11874 @itemize @bullet
11875 @item
11876 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11877 and the @option{^-gnata^-gnata^},
11878 @option{^-gnato^-gnato^},
11879 and @option{^-gnatE^-gnatE^} switches to the
11880 compiler; the compiler's output is to appear in @file{/common/debug}
11881 @item
11882 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11883 to the compiler; the compiler's output is to appear in @file{/common/release}
11884 @end itemize
11885
11886 @noindent
11887 The GNAT project files shown below, respectively @file{debug.gpr} and
11888 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11889
11890 Schematically:
11891 @smallexample
11892 @group
11893 ^/common^[COMMON]^
11894   debug.gpr
11895   release.gpr
11896   pack.ads
11897   pack.adb
11898   proc.adb
11899 @end group
11900 @group
11901 ^/common/debug^[COMMON.DEBUG]^
11902   proc.ali, proc.o
11903   pack.ali, pack.o
11904 @end group
11905 @group
11906 ^/common/release^[COMMON.RELEASE]^
11907   proc.ali, proc.o
11908   pack.ali, pack.o
11909 @end group
11910 @end smallexample
11911 Here are the corresponding project files:
11912
11913 @smallexample @c projectfile
11914 @group
11915 project Debug is
11916   for Object_Dir use "debug";
11917   for Main use ("proc");
11918
11919   package Builder is
11920     for ^Default_Switches^Default_Switches^ ("Ada")
11921         use ("^-g^-g^");
11922     for Executable ("proc.adb") use "proc1";
11923   end Builder;
11924 @end group
11925
11926 @group
11927   package Compiler is
11928     for ^Default_Switches^Default_Switches^ ("Ada")
11929        use ("-fstack-check",
11930             "^-gnata^-gnata^",
11931             "^-gnato^-gnato^",
11932             "^-gnatE^-gnatE^");
11933   end Compiler;
11934 end Debug;
11935 @end group
11936 @end smallexample
11937
11938 @smallexample @c projectfile
11939 @group
11940 project Release is
11941   for Object_Dir use "release";
11942   for Exec_Dir use ".";
11943   for Main use ("proc");
11944
11945   package Compiler is
11946     for ^Default_Switches^Default_Switches^ ("Ada")
11947         use ("^-O2^-O2^");
11948   end Compiler;
11949 end Release;
11950 @end group
11951 @end smallexample
11952
11953 @noindent
11954 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11955 insensitive), and analogously the project defined by @file{release.gpr} is
11956 @code{"Release"}.  For consistency the file should have the same name as the
11957 project, and the project file's extension should be @code{"gpr"}. These
11958 conventions are not required, but a warning is issued if they are not followed.
11959
11960 If the current directory is @file{^/temp^[TEMP]^}, then the command
11961 @smallexample
11962 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11963 @end smallexample
11964
11965 @noindent
11966 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11967 as well as the @code{^proc1^PROC1.EXE^} executable,
11968 using the ^switch^switch^ settings defined in the project file.
11969
11970 Likewise, the command
11971 @smallexample
11972 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11973 @end smallexample
11974
11975 @noindent
11976 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11977 and the @code{^proc^PROC.EXE^}
11978 executable in @file{^/common^[COMMON]^},
11979 using the ^switch^switch^ settings from the project file.
11980
11981 @node Source Files
11982 @unnumberedsubsubsec Source Files
11983
11984 @noindent
11985 If a project file does not explicitly specify a set of source directories or
11986 a set of source files, then by default the project's source files are the
11987 Ada source files in the project file directory.  Thus @file{pack.ads},
11988 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11989
11990 @node Specifying the Object Directory
11991 @unnumberedsubsubsec Specifying the Object Directory
11992
11993 @noindent
11994 Several project properties are modeled by Ada-style @emph{attributes};
11995 a property is defined by supplying the equivalent of an Ada attribute
11996 definition clause in the project file.
11997 A project's object directory is another such a property; the corresponding
11998 attribute is @code{Object_Dir}, and its value is also a string expression,
11999 specified either as absolute or relative. In the later case,
12000 it is relative to the project file directory. Thus the compiler's
12001 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12002 (for the @code{Debug} project)
12003 and to @file{^/common/release^[COMMON.RELEASE]^}
12004 (for the @code{Release} project).
12005 If @code{Object_Dir} is not specified, then the default is the project file
12006 directory itself.
12007
12008 @node Specifying the Exec Directory
12009 @unnumberedsubsubsec Specifying the Exec Directory
12010
12011 @noindent
12012 A project's exec directory is another property; the corresponding
12013 attribute is @code{Exec_Dir}, and its value is also a string expression,
12014 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12015 then the default is the object directory (which may also be the project file
12016 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12017 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12018 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12019 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12020
12021 @node Project File Packages
12022 @unnumberedsubsubsec Project File Packages
12023
12024 @noindent
12025 A GNAT tool that is integrated with the Project Manager is modeled by a
12026 corresponding package in the project file. In the example above,
12027 The @code{Debug} project defines the packages @code{Builder}
12028 (for @command{gnatmake}) and @code{Compiler};
12029 the @code{Release} project defines only the @code{Compiler} package.
12030
12031 The Ada-like package syntax is not to be taken literally.  Although packages in
12032 project files bear a surface resemblance to packages in Ada source code, the
12033 notation is simply a way to convey a grouping of properties for a named
12034 entity.  Indeed, the package names permitted in project files are restricted
12035 to a predefined set, corresponding to the project-aware tools, and the contents
12036 of packages are limited to a small set of constructs.
12037 The packages in the example above contain attribute definitions.
12038
12039 @node Specifying ^Switch^Switch^ Settings
12040 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12041
12042 @noindent
12043 ^Switch^Switch^ settings for a project-aware tool can be specified through
12044 attributes in the package that corresponds to the tool.
12045 The example above illustrates one of the relevant attributes,
12046 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12047 in both project files.
12048 Unlike simple attributes like @code{Source_Dirs},
12049 @code{^Default_Switches^Default_Switches^} is
12050 known as an @emph{associative array}.  When you define this attribute, you must
12051 supply an ``index'' (a literal string), and the effect of the attribute
12052 definition is to set the value of the array at the specified index.
12053 For the @code{^Default_Switches^Default_Switches^} attribute,
12054 the index is a programming language (in our case, Ada),
12055 and the value specified (after @code{use}) must be a list
12056 of string expressions.
12057
12058 The attributes permitted in project files are restricted to a predefined set.
12059 Some may appear at project level, others in packages.
12060 For any attribute that is an associative array, the index must always be a
12061 literal string, but the restrictions on this string (e.g., a file name or a
12062 language name) depend on the individual attribute.
12063 Also depending on the attribute, its specified value will need to be either a
12064 string or a string list.
12065
12066 In the @code{Debug} project, we set the switches for two tools,
12067 @command{gnatmake} and the compiler, and thus we include the two corresponding
12068 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12069 attribute with index @code{"Ada"}.
12070 Note that the package corresponding to
12071 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12072 similar, but only includes the @code{Compiler} package.
12073
12074 In project @code{Debug} above, the ^switches^switches^ starting with
12075 @option{-gnat} that are specified in package @code{Compiler}
12076 could have been placed in package @code{Builder}, since @command{gnatmake}
12077 transmits all such ^switches^switches^ to the compiler.
12078
12079 @node Main Subprograms
12080 @unnumberedsubsubsec Main Subprograms
12081
12082 @noindent
12083 One of the specifiable properties of a project is a list of files that contain
12084 main subprograms.  This property is captured in the @code{Main} attribute,
12085 whose value is a list of strings.  If a project defines the @code{Main}
12086 attribute, it is not necessary to identify the main subprogram(s) when
12087 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12088
12089 @node Executable File Names
12090 @unnumberedsubsubsec Executable File Names
12091
12092 @noindent
12093 By default, the executable file name corresponding to a main source is
12094 deduced from the main source file name. Through the attributes
12095 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12096 it is possible to change this default.
12097 In project @code{Debug} above, the executable file name
12098 for main source @file{^proc.adb^PROC.ADB^} is
12099 @file{^proc1^PROC1.EXE^}.
12100 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12101 of the executable files, when no attribute @code{Executable} applies:
12102 its value replace the platform-specific executable suffix.
12103 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12104 specify a non-default executable file name when several mains are built at once
12105 in a single @command{gnatmake} command.
12106
12107 @node Source File Naming Conventions
12108 @unnumberedsubsubsec Source File Naming Conventions
12109
12110 @noindent
12111 Since the project files above do not specify any source file naming
12112 conventions, the GNAT defaults are used.  The mechanism for defining source
12113 file naming conventions -- a package named @code{Naming} --
12114 is described below (@pxref{Naming Schemes}).
12115
12116 @node Source Language(s)
12117 @unnumberedsubsubsec Source Language(s)
12118
12119 @noindent
12120 Since the project files do not specify a @code{Languages} attribute, by
12121 default the GNAT tools assume that the language of the project file is Ada.
12122 More generally, a project can comprise source files
12123 in Ada, C, and/or other languages.
12124
12125 @node Using External Variables
12126 @subsection Using External Variables
12127
12128 @noindent
12129 Instead of supplying different project files for debug and release, we can
12130 define a single project file that queries an external variable (set either
12131 on the command line or via an ^environment variable^logical name^) in order to
12132 conditionally define the appropriate settings.  Again, assume that the
12133 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12134 located in directory @file{^/common^[COMMON]^}.  The following project file,
12135 @file{build.gpr}, queries the external variable named @code{STYLE} and
12136 defines an object directory and ^switch^switch^ settings based on whether
12137 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12138 the default is @code{"deb"}.
12139
12140 @smallexample @c projectfile
12141 @group
12142 project Build is
12143   for Main use ("proc");
12144
12145   type Style_Type is ("deb", "rel");
12146   Style : Style_Type := external ("STYLE", "deb");
12147
12148   case Style is
12149     when "deb" =>
12150       for Object_Dir use "debug";
12151
12152     when "rel" =>
12153       for Object_Dir use "release";
12154       for Exec_Dir use ".";
12155   end case;
12156 @end group
12157
12158 @group
12159   package Builder is
12160
12161     case Style is
12162       when "deb" =>
12163         for ^Default_Switches^Default_Switches^ ("Ada")
12164             use ("^-g^-g^");
12165         for Executable ("proc") use "proc1";
12166       when others =>
12167         null;
12168     end case;
12169
12170   end Builder;
12171 @end group
12172
12173 @group
12174   package Compiler is
12175
12176     case Style is
12177       when "deb" =>
12178         for ^Default_Switches^Default_Switches^ ("Ada")
12179             use ("^-gnata^-gnata^",
12180                  "^-gnato^-gnato^",
12181                  "^-gnatE^-gnatE^");
12182
12183       when "rel" =>
12184         for ^Default_Switches^Default_Switches^ ("Ada")
12185             use ("^-O2^-O2^");
12186     end case;
12187
12188   end Compiler;
12189
12190 end Build;
12191 @end group
12192 @end smallexample
12193
12194 @noindent
12195 @code{Style_Type} is an example of a @emph{string type}, which is the project
12196 file analog of an Ada enumeration type but whose components are string literals
12197 rather than identifiers.  @code{Style} is declared as a variable of this type.
12198
12199 The form @code{external("STYLE", "deb")} is known as an
12200 @emph{external reference}; its first argument is the name of an
12201 @emph{external variable}, and the second argument is a default value to be
12202 used if the external variable doesn't exist.  You can define an external
12203 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12204 or you can use ^an environment variable^a logical name^
12205 as an external variable.
12206
12207 Each @code{case} construct is expanded by the Project Manager based on the
12208 value of @code{Style}. Thus the command
12209 @ifclear vms
12210 @smallexample
12211 gnatmake -P/common/build.gpr -XSTYLE=deb
12212 @end smallexample
12213 @end ifclear
12214
12215 @ifset vms
12216 @smallexample
12217 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12218 @end smallexample
12219 @end ifset
12220
12221 @noindent
12222 is equivalent to the @command{gnatmake} invocation using the project file
12223 @file{debug.gpr} in the earlier example.  So is the command
12224 @smallexample
12225 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12226 @end smallexample
12227
12228 @noindent
12229 since @code{"deb"} is the default for @code{STYLE}.
12230
12231 Analogously,
12232
12233 @ifclear vms
12234 @smallexample
12235 gnatmake -P/common/build.gpr -XSTYLE=rel
12236 @end smallexample
12237 @end ifclear
12238
12239 @ifset vms
12240 @smallexample
12241 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12242 @end smallexample
12243 @end ifset
12244
12245 @noindent
12246 is equivalent to the @command{gnatmake} invocation using the project file
12247 @file{release.gpr} in the earlier example.
12248
12249 @node Importing Other Projects
12250 @subsection Importing Other Projects
12251 @cindex @code{ADA_PROJECT_PATH}
12252 @cindex @code{GPR_PROJECT_PATH}
12253
12254 @noindent
12255 A compilation unit in a source file in one project may depend on compilation
12256 units in source files in other projects.  To compile this unit under
12257 control of a project file, the
12258 dependent project must @emph{import} the projects containing the needed source
12259 files.
12260 This effect is obtained using syntax similar to an Ada @code{with} clause,
12261 but where @code{with}ed entities are strings that denote project files.
12262
12263 As an example, suppose that the two projects @code{GUI_Proj} and
12264 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12265 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12266 and @file{^/comm^[COMM]^}, respectively.
12267 Suppose that the source files for @code{GUI_Proj} are
12268 @file{gui.ads} and @file{gui.adb}, and that the source files for
12269 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12270 files is located in its respective project file directory.  Schematically:
12271
12272 @smallexample
12273 @group
12274 ^/gui^[GUI]^
12275   gui_proj.gpr
12276   gui.ads
12277   gui.adb
12278 @end group
12279
12280 @group
12281 ^/comm^[COMM]^
12282   comm_proj.gpr
12283   comm.ads
12284   comm.adb
12285 @end group
12286 @end smallexample
12287
12288 @noindent
12289 We want to develop an application in directory @file{^/app^[APP]^} that
12290 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12291 the corresponding project files (e.g.@: the ^switch^switch^ settings
12292 and object directory).
12293 Skeletal code for a main procedure might be something like the following:
12294
12295 @smallexample @c ada
12296 @group
12297 with GUI, Comm;
12298 procedure App_Main is
12299    @dots{}
12300 begin
12301    @dots{}
12302 end App_Main;
12303 @end group
12304 @end smallexample
12305
12306 @noindent
12307 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12308 effect:
12309
12310 @smallexample @c projectfile
12311 @group
12312 with "/gui/gui_proj", "/comm/comm_proj";
12313 project App_Proj is
12314    for Main use ("app_main");
12315 end App_Proj;
12316 @end group
12317 @end smallexample
12318
12319 @noindent
12320 Building an executable is achieved through the command:
12321 @smallexample
12322 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12323 @end smallexample
12324 @noindent
12325 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12326 in the directory where @file{app_proj.gpr} resides.
12327
12328 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12329 (as illustrated above) the @code{with} clause can omit the extension.
12330
12331 Our example specified an absolute path for each imported project file.
12332 Alternatively, the directory name of an imported object can be omitted
12333 if either
12334 @itemize @bullet
12335 @item
12336 The imported project file is in the same directory as the importing project
12337 file, or
12338 @item
12339 You have defined one or two ^environment variables^logical names^
12340 that includes the directory containing
12341 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12342 @code{ADA_PROJECT_PATH} is the same as
12343 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12344 directory names separated by colons (semicolons on Windows).
12345 @end itemize
12346
12347 @noindent
12348 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12349 to include @file{^/gui^[GUI]^} and
12350 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12351 as follows:
12352
12353 @smallexample @c projectfile
12354 @group
12355 with "gui_proj", "comm_proj";
12356 project App_Proj is
12357    for Main use ("app_main");
12358 end App_Proj;
12359 @end group
12360 @end smallexample
12361
12362 @noindent
12363 Importing other projects can create ambiguities.
12364 For example, the same unit might be present in different imported projects, or
12365 it might be present in both the importing project and in an imported project.
12366 Both of these conditions are errors.  Note that in the current version of
12367 the Project Manager, it is illegal to have an ambiguous unit even if the
12368 unit is never referenced by the importing project.  This restriction may be
12369 relaxed in a future release.
12370
12371 @node Extending a Project
12372 @subsection Extending a Project
12373
12374 @noindent
12375 In large software systems it is common to have multiple
12376 implementations of a common interface; in Ada terms, multiple versions of a
12377 package body for the same spec.  For example, one implementation
12378 might be safe for use in tasking programs, while another might only be used
12379 in sequential applications.  This can be modeled in GNAT using the concept
12380 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12381 another project (the ``parent'') then by default all source files of the
12382 parent project are inherited by the child, but the child project can
12383 override any of the parent's source files with new versions, and can also
12384 add new files.  This facility is the project analog of a type extension in
12385 Object-Oriented Programming.  Project hierarchies are permitted (a child
12386 project may be the parent of yet another project), and a project that
12387 inherits one project can also import other projects.
12388
12389 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12390 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12391 @file{pack.adb}, and @file{proc.adb}:
12392
12393 @smallexample
12394 @group
12395 ^/seq^[SEQ]^
12396   pack.ads
12397   pack.adb
12398   proc.adb
12399   seq_proj.gpr
12400 @end group
12401 @end smallexample
12402
12403 @noindent
12404 Note that the project file can simply be empty (that is, no attribute or
12405 package is defined):
12406
12407 @smallexample @c projectfile
12408 @group
12409 project Seq_Proj is
12410 end Seq_Proj;
12411 @end group
12412 @end smallexample
12413
12414 @noindent
12415 implying that its source files are all the Ada source files in the project
12416 directory.
12417
12418 Suppose we want to supply an alternate version of @file{pack.adb}, in
12419 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12420 @file{pack.ads} and @file{proc.adb}.  We can define a project
12421 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12422
12423 @smallexample
12424 @group
12425 ^/tasking^[TASKING]^
12426   pack.adb
12427   tasking_proj.gpr
12428 @end group
12429
12430 @group
12431 project Tasking_Proj extends "/seq/seq_proj" is
12432 end Tasking_Proj;
12433 @end group
12434 @end smallexample
12435
12436 @noindent
12437 The version of @file{pack.adb} used in a build depends on which project file
12438 is specified.
12439
12440 Note that we could have obtained the desired behavior using project import
12441 rather than project inheritance; a @code{base} project would contain the
12442 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12443 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12444 would import @code{base} and add a different version of @file{pack.adb}.  The
12445 choice depends on whether other sources in the original project need to be
12446 overridden.  If they do, then project extension is necessary, otherwise,
12447 importing is sufficient.
12448
12449 @noindent
12450 In a project file that extends another project file, it is possible to
12451 indicate that an inherited source is not part of the sources of the extending
12452 project. This is necessary sometimes when a package spec has been overloaded
12453 and no longer requires a body: in this case, it is necessary to indicate that
12454 the inherited body is not part of the sources of the project, otherwise there
12455 will be a compilation error when compiling the spec.
12456
12457 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12458 Its value is a string list: a list of file names. It is also possible to use
12459 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12460 the file name of a text file containing a list of file names, one per line.
12461
12462 @smallexample @c @projectfile
12463 project B extends "a" is
12464    for Source_Files use ("pkg.ads");
12465    --  New spec of Pkg does not need a completion
12466    for Excluded_Source_Files use ("pkg.adb");
12467 end B;
12468 @end smallexample
12469
12470 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12471 is still needed: if it is possible to build using @command{gnatmake} when such
12472 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12473 it is possible to remove the source completely from a system that includes
12474 project P.
12475
12476 @c ***********************
12477 @c * Project File Syntax *
12478 @c ***********************
12479
12480 @node Project File Syntax
12481 @section Project File Syntax
12482
12483 @menu
12484 * Basic Syntax::
12485 * Qualified Projects::
12486 * Packages::
12487 * Expressions::
12488 * String Types::
12489 * Variables::
12490 * Attributes::
12491 * Associative Array Attributes::
12492 * case Constructions::
12493 @end menu
12494
12495 @noindent
12496 This section describes the structure of project files.
12497
12498 A project may be an @emph{independent project}, entirely defined by a single
12499 project file. Any Ada source file in an independent project depends only
12500 on the predefined library and other Ada source files in the same project.
12501
12502 @noindent
12503 A project may also @dfn{depend on} other projects, in either or both of
12504 the following ways:
12505 @itemize @bullet
12506 @item It may import any number of projects
12507 @item It may extend at most one other project
12508 @end itemize
12509
12510 @noindent
12511 The dependence relation is a directed acyclic graph (the subgraph reflecting
12512 the ``extends'' relation is a tree).
12513
12514 A project's @dfn{immediate sources} are the source files directly defined by
12515 that project, either implicitly by residing in the project file's directory,
12516 or explicitly through any of the source-related attributes described below.
12517 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12518 of @var{proj} together with the immediate sources (unless overridden) of any
12519 project on which @var{proj} depends (either directly or indirectly).
12520
12521 @node Basic Syntax
12522 @subsection Basic Syntax
12523
12524 @noindent
12525 As seen in the earlier examples, project files have an Ada-like syntax.
12526 The minimal project file is:
12527 @smallexample @c projectfile
12528 @group
12529 project Empty is
12530
12531 end Empty;
12532 @end group
12533 @end smallexample
12534
12535 @noindent
12536 The identifier @code{Empty} is the name of the project.
12537 This project name must be present after the reserved
12538 word @code{end} at the end of the project file, followed by a semi-colon.
12539
12540 Any name in a project file, such as the project name or a variable name,
12541 has the same syntax as an Ada identifier.
12542
12543 The reserved words of project files are the Ada 95 reserved words plus
12544 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12545 reserved words currently used in project file syntax are:
12546
12547 @itemize @bullet
12548 @item
12549 @code{all}
12550 @item
12551 @code{at}
12552 @item
12553 @code{case}
12554 @item
12555 @code{end}
12556 @item
12557 @code{for}
12558 @item
12559 @code{is}
12560 @item
12561 @code{limited}
12562 @item
12563 @code{null}
12564 @item
12565 @code{others}
12566 @item
12567 @code{package}
12568 @item
12569 @code{renames}
12570 @item
12571 @code{type}
12572 @item
12573 @code{use}
12574 @item
12575 @code{when}
12576 @item
12577 @code{with}
12578 @end itemize
12579
12580 @noindent
12581 Comments in project files have the same syntax as in Ada, two consecutive
12582 hyphens through the end of the line.
12583
12584 @node Qualified Projects
12585 @subsection Qualified Projects
12586
12587 @noindent
12588 Before the reserved @code{project}, there may be one or two "qualifiers", that
12589 is identifiers or other reserved words, to qualify the project.
12590
12591 The current list of qualifiers is:
12592
12593 @itemize @bullet
12594 @item
12595 @code{abstract}: qualify a project with no sources. A qualified abstract
12596 project must either have no declaration of attributes @code{Source_Dirs},
12597 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12598 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12599 as empty. If it extends another project, the project it extends must also be a
12600 qualified abstract project.
12601
12602 @item
12603 @code{standard}: a standard project is a non library project with sources.
12604
12605 @item
12606 @code{aggregate}: for future extension
12607
12608 @item
12609 @code{aggregate library}: for future extension
12610
12611 @item
12612 @code{library}: a library project must declare both attributes
12613 @code{Library_Name} and @code{Library_Dir}.
12614
12615 @item
12616 @code{configuration}: a configuration project cannot be in a project tree.
12617 @end itemize
12618
12619 @node Packages
12620 @subsection Packages
12621
12622 @noindent
12623 A project file may contain @emph{packages}. The name of a package must be one
12624 of the identifiers from the following list. A package
12625 with a given name may only appear once in a project file. Package names are
12626 case insensitive. The following package names are legal:
12627
12628 @itemize @bullet
12629 @item
12630 @code{Naming}
12631 @item
12632 @code{Builder}
12633 @item
12634 @code{Compiler}
12635 @item
12636 @code{Binder}
12637 @item
12638 @code{Linker}
12639 @item
12640 @code{Finder}
12641 @item
12642 @code{Cross_Reference}
12643 @item
12644 @code{Eliminate}
12645 @item
12646 @code{Pretty_Printer}
12647 @item
12648 @code{Metrics}
12649 @item
12650 @code{gnatls}
12651 @item
12652 @code{gnatstub}
12653 @item
12654 @code{IDE}
12655 @item
12656 @code{Language_Processing}
12657 @end itemize
12658
12659 @noindent
12660 In its simplest form, a package may be empty:
12661
12662 @smallexample @c projectfile
12663 @group
12664 project Simple is
12665   package Builder is
12666   end Builder;
12667 end Simple;
12668 @end group
12669 @end smallexample
12670
12671 @noindent
12672 A package may contain @emph{attribute declarations},
12673 @emph{variable declarations} and @emph{case constructions}, as will be
12674 described below.
12675
12676 When there is ambiguity between a project name and a package name,
12677 the name always designates the project. To avoid possible confusion, it is
12678 always a good idea to avoid naming a project with one of the
12679 names allowed for packages or any name that starts with @code{gnat}.
12680
12681 @node Expressions
12682 @subsection Expressions
12683
12684 @noindent
12685 An @emph{expression} is either a @emph{string expression} or a
12686 @emph{string list expression}.
12687
12688 A @emph{string expression} is either a @emph{simple string expression} or a
12689 @emph{compound string expression}.
12690
12691 A @emph{simple string expression} is one of the following:
12692 @itemize @bullet
12693 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12694 @item A string-valued variable reference (@pxref{Variables})
12695 @item A string-valued attribute reference (@pxref{Attributes})
12696 @item An external reference (@pxref{External References in Project Files})
12697 @end itemize
12698
12699 @noindent
12700 A @emph{compound string expression} is a concatenation of string expressions,
12701 using the operator @code{"&"}
12702 @smallexample
12703        Path & "/" & File_Name & ".ads"
12704 @end smallexample
12705
12706 @noindent
12707 A @emph{string list expression} is either a
12708 @emph{simple string list expression} or a
12709 @emph{compound string list expression}.
12710
12711 A @emph{simple string list expression} is one of the following:
12712 @itemize @bullet
12713 @item A parenthesized list of zero or more string expressions,
12714 separated by commas
12715 @smallexample
12716    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12717    Empty_List := ();
12718 @end smallexample
12719 @item A string list-valued variable reference
12720 @item A string list-valued attribute reference
12721 @end itemize
12722
12723 @noindent
12724 A @emph{compound string list expression} is the concatenation (using
12725 @code{"&"}) of a simple string list expression and an expression.  Note that
12726 each term in a compound string list expression, except the first, may be
12727 either a string expression or a string list expression.
12728
12729 @smallexample @c projectfile
12730 @group
12731    File_Name_List := () & File_Name; --  One string in this list
12732    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12733    --  Two strings
12734    Big_List := File_Name_List & Extended_File_Name_List;
12735    --  Concatenation of two string lists: three strings
12736    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12737    --  Illegal: must start with a string list
12738 @end group
12739 @end smallexample
12740
12741 @node String Types
12742 @subsection String Types
12743
12744 @noindent
12745 A @emph{string type declaration} introduces a discrete set of string literals.
12746 If a string variable is declared to have this type, its value
12747 is restricted to the given set of literals.
12748
12749 Here is an example of a string type declaration:
12750
12751 @smallexample @c projectfile
12752    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12753 @end smallexample
12754
12755 @noindent
12756 Variables of a string type are called @emph{typed variables}; all other
12757 variables are called @emph{untyped variables}. Typed variables are
12758 particularly useful in @code{case} constructions, to support conditional
12759 attribute declarations.
12760 (@pxref{case Constructions}).
12761
12762 The string literals in the list are case sensitive and must all be different.
12763 They may include any graphic characters allowed in Ada, including spaces.
12764
12765 A string type may only be declared at the project level, not inside a package.
12766
12767 A string type may be referenced by its name if it has been declared in the same
12768 project file, or by an expanded name whose prefix is the name of the project
12769 in which it is declared.
12770
12771 @node Variables
12772 @subsection Variables
12773
12774 @noindent
12775 A variable may be declared at the project file level, or within a package.
12776 Here are some examples of variable declarations:
12777
12778 @smallexample @c projectfile
12779 @group
12780    This_OS : OS := external ("OS"); --  a typed variable declaration
12781    That_OS := "GNU/Linux";          --  an untyped variable declaration
12782 @end group
12783 @end smallexample
12784
12785 @noindent
12786 The syntax of a @emph{typed variable declaration} is identical to the Ada
12787 syntax for an object declaration. By contrast, the syntax of an untyped
12788 variable declaration is identical to an Ada assignment statement. In fact,
12789 variable declarations in project files have some of the characteristics of
12790 an assignment, in that successive declarations for the same variable are
12791 allowed. Untyped variable declarations do establish the expected kind of the
12792 variable (string or string list), and successive declarations for it must
12793 respect the initial kind.
12794
12795 @noindent
12796 A string variable declaration (typed or untyped) declares a variable
12797 whose value is a string. This variable may be used as a string expression.
12798 @smallexample @c projectfile
12799    File_Name       := "readme.txt";
12800    Saved_File_Name := File_Name & ".saved";
12801 @end smallexample
12802
12803 @noindent
12804 A string list variable declaration declares a variable whose value is a list
12805 of strings. The list may contain any number (zero or more) of strings.
12806
12807 @smallexample @c projectfile
12808    Empty_List := ();
12809    List_With_One_Element := ("^-gnaty^-gnaty^");
12810    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12811    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12812                  "pack2.ada", "util_.ada", "util.ada");
12813 @end smallexample
12814
12815 @noindent
12816 The same typed variable may not be declared more than once at project level,
12817 and it may not be declared more than once in any package; it is in effect
12818 a constant.
12819
12820 The same untyped variable may be declared several times. Declarations are
12821 elaborated in the order in which they appear, so  the new value replaces
12822 the old one, and any subsequent reference to the variable uses the new value.
12823 However, as noted above, if a variable has been declared as a string, all
12824 subsequent
12825 declarations must give it a string value. Similarly, if a variable has
12826 been declared as a string list, all subsequent declarations
12827 must give it a string list value.
12828
12829 A @emph{variable reference} may take several forms:
12830
12831 @itemize @bullet
12832 @item The simple variable name, for a variable in the current package (if any)
12833 or in the current project
12834 @item An expanded name, whose prefix is a context name.
12835 @end itemize
12836
12837 @noindent
12838 A @emph{context} may be one of the following:
12839
12840 @itemize @bullet
12841 @item The name of an existing package in the current project
12842 @item The name of an imported project of the current project
12843 @item The name of an ancestor project (i.e., a project extended by the current
12844 project, either directly or indirectly)
12845 @item An expanded name whose prefix is an imported/parent project name, and
12846 whose selector is a package name in that project.
12847 @end itemize
12848
12849 @noindent
12850 A variable reference may be used in an expression.
12851
12852 @node Attributes
12853 @subsection Attributes
12854
12855 @noindent
12856 A project (and its packages) may have @emph{attributes} that define
12857 the project's properties.  Some attributes have values that are strings;
12858 others have values that are string lists.
12859
12860 There are two categories of attributes: @emph{simple attributes}
12861 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12862
12863 Legal project attribute names, and attribute names for each legal package are
12864 listed below. Attributes names are case-insensitive.
12865
12866 The following attributes are defined on projects (all are simple attributes):
12867
12868 @multitable @columnfractions .4 .3
12869 @item @emph{Attribute Name}
12870 @tab @emph{Value}
12871 @item @code{Source_Files}
12872 @tab string list
12873 @item @code{Source_Dirs}
12874 @tab string list
12875 @item @code{Source_List_File}
12876 @tab string
12877 @item @code{Object_Dir}
12878 @tab string
12879 @item @code{Exec_Dir}
12880 @tab string
12881 @item @code{Excluded_Source_Dirs}
12882 @tab string list
12883 @item @code{Excluded_Source_Files}
12884 @tab string list
12885 @item @code{Excluded_Source_List_File}
12886 @tab string
12887 @item @code{Languages}
12888 @tab string list
12889 @item @code{Main}
12890 @tab string list
12891 @item @code{Library_Dir}
12892 @tab string
12893 @item @code{Library_Name}
12894 @tab string
12895 @item @code{Library_Kind}
12896 @tab string
12897 @item @code{Library_Version}
12898 @tab string
12899 @item @code{Library_Interface}
12900 @tab string
12901 @item @code{Library_Auto_Init}
12902 @tab string
12903 @item @code{Library_Options}
12904 @tab string list
12905 @item @code{Library_Src_Dir}
12906 @tab string
12907 @item @code{Library_ALI_Dir}
12908 @tab string
12909 @item @code{Library_GCC}
12910 @tab string
12911 @item @code{Library_Symbol_File}
12912 @tab string
12913 @item @code{Library_Symbol_Policy}
12914 @tab string
12915 @item @code{Library_Reference_Symbol_File}
12916 @tab string
12917 @item @code{Externally_Built}
12918 @tab string
12919 @end multitable
12920
12921 @noindent
12922 The following attributes are defined for package  @code{Naming}
12923 (@pxref{Naming Schemes}):
12924
12925 @multitable @columnfractions .4 .2 .2 .2
12926 @item Attribute Name @tab Category @tab Index @tab Value
12927 @item @code{Spec_Suffix}
12928 @tab associative array
12929 @tab language name
12930 @tab string
12931 @item @code{Body_Suffix}
12932 @tab associative array
12933 @tab language name
12934 @tab string
12935 @item @code{Separate_Suffix}
12936 @tab simple attribute
12937 @tab n/a
12938 @tab string
12939 @item @code{Casing}
12940 @tab simple attribute
12941 @tab n/a
12942 @tab string
12943 @item @code{Dot_Replacement}
12944 @tab simple attribute
12945 @tab n/a
12946 @tab string
12947 @item @code{Spec}
12948 @tab associative array
12949 @tab Ada unit name
12950 @tab string
12951 @item @code{Body}
12952 @tab associative array
12953 @tab Ada unit name
12954 @tab string
12955 @item @code{Specification_Exceptions}
12956 @tab associative array
12957 @tab language name
12958 @tab string list
12959 @item @code{Implementation_Exceptions}
12960 @tab associative array
12961 @tab language name
12962 @tab string list
12963 @end multitable
12964
12965 @noindent
12966 The following attributes are defined for packages @code{Builder},
12967 @code{Compiler}, @code{Binder},
12968 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12969 (@pxref{^Switches^Switches^ and Project Files}).
12970
12971 @multitable @columnfractions .4 .2 .2 .2
12972 @item Attribute Name @tab Category @tab Index @tab Value
12973 @item @code{^Default_Switches^Default_Switches^}
12974 @tab associative array
12975 @tab language name
12976 @tab string list
12977 @item @code{^Switches^Switches^}
12978 @tab associative array
12979 @tab file name
12980 @tab string list
12981 @end multitable
12982
12983 @noindent
12984 In addition, package @code{Compiler} has a single string attribute
12985 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12986 string attribute @code{Global_Configuration_Pragmas}.
12987
12988 @noindent
12989 Each simple attribute has a default value: the empty string (for string-valued
12990 attributes) and the empty list (for string list-valued attributes).
12991
12992 An attribute declaration defines a new value for an attribute.
12993
12994 Examples of simple attribute declarations:
12995
12996 @smallexample @c projectfile
12997    for Object_Dir use "objects";
12998    for Source_Dirs use ("units", "test/drivers");
12999 @end smallexample
13000
13001 @noindent
13002 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13003 attribute definition clause in Ada.
13004
13005 Attributes references may be appear in expressions.
13006 The general form for such a reference is @code{<entity>'<attribute>}:
13007 Associative array attributes are functions. Associative
13008 array attribute references must have an argument that is a string literal.
13009
13010 Examples are:
13011
13012 @smallexample @c projectfile
13013   project'Object_Dir
13014   Naming'Dot_Replacement
13015   Imported_Project'Source_Dirs
13016   Imported_Project.Naming'Casing
13017   Builder'^Default_Switches^Default_Switches^("Ada")
13018 @end smallexample
13019
13020 @noindent
13021 The prefix of an attribute may be:
13022 @itemize @bullet
13023 @item @code{project} for an attribute of the current project
13024 @item The name of an existing package of the current project
13025 @item The name of an imported project
13026 @item The name of a parent project that is extended by the current project
13027 @item An expanded name whose prefix is imported/parent project name,
13028 and whose selector is a package name
13029 @end itemize
13030
13031 @noindent
13032 Example:
13033 @smallexample @c projectfile
13034 @group
13035    project Prj is
13036      for Source_Dirs use project'Source_Dirs & "units";
13037      for Source_Dirs use project'Source_Dirs & "test/drivers"
13038    end Prj;
13039 @end group
13040 @end smallexample
13041
13042 @noindent
13043 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13044 has the default value: an empty string list. After this declaration,
13045 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13046 After the second attribute declaration @code{Source_Dirs} is a string list of
13047 two elements: @code{"units"} and @code{"test/drivers"}.
13048
13049 Note: this example is for illustration only. In practice,
13050 the project file would contain only one attribute declaration:
13051
13052 @smallexample @c projectfile
13053    for Source_Dirs use ("units", "test/drivers");
13054 @end smallexample
13055
13056 @node Associative Array Attributes
13057 @subsection Associative Array Attributes
13058
13059 @noindent
13060 Some attributes are defined as @emph{associative arrays}. An associative
13061 array may be regarded as a function that takes a string as a parameter
13062 and delivers a string or string list value as its result.
13063
13064 Here are some examples of single associative array attribute associations:
13065
13066 @smallexample @c projectfile
13067    for Body ("main") use "Main.ada";
13068    for ^Switches^Switches^ ("main.ada")
13069        use ("^-v^-v^",
13070             "^-gnatv^-gnatv^");
13071    for ^Switches^Switches^ ("main.ada")
13072             use Builder'^Switches^Switches^ ("main.ada")
13073               & "^-g^-g^";
13074 @end smallexample
13075
13076 @noindent
13077 Like untyped variables and simple attributes, associative array attributes
13078 may be declared several times. Each declaration supplies a new value for the
13079 attribute, and replaces the previous setting.
13080
13081 @noindent
13082 An associative array attribute may be declared as a full associative array
13083 declaration, with the value of the same attribute in an imported or extended
13084 project.
13085
13086 @smallexample @c projectfile
13087    package Builder is
13088       for Default_Switches use Default.Builder'Default_Switches;
13089    end Builder;
13090 @end smallexample
13091
13092 @noindent
13093 In this example, @code{Default} must be either a project imported by the
13094 current project, or the project that the current project extends. If the
13095 attribute is in a package (in this case, in package @code{Builder}), the same
13096 package needs to be specified.
13097
13098 @noindent
13099 A full associative array declaration replaces any other declaration for the
13100 attribute, including other full associative array declaration. Single
13101 associative array associations may be declare after a full associative
13102 declaration, modifying the value for a single association of the attribute.
13103
13104 @node case Constructions
13105 @subsection @code{case} Constructions
13106
13107 @noindent
13108 A @code{case} construction is used in a project file to effect conditional
13109 behavior.
13110 Here is a typical example:
13111
13112 @smallexample @c projectfile
13113 @group
13114 project MyProj is
13115    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13116
13117    OS : OS_Type := external ("OS", "GNU/Linux");
13118 @end group
13119
13120 @group
13121    package Compiler is
13122      case OS is
13123        when "GNU/Linux" | "Unix" =>
13124          for ^Default_Switches^Default_Switches^ ("Ada")
13125              use ("^-gnath^-gnath^");
13126        when "NT" =>
13127          for ^Default_Switches^Default_Switches^ ("Ada")
13128              use ("^-gnatP^-gnatP^");
13129        when others =>
13130      end case;
13131    end Compiler;
13132 end MyProj;
13133 @end group
13134 @end smallexample
13135
13136 @noindent
13137 The syntax of a @code{case} construction is based on the Ada case statement
13138 (although there is no @code{null} construction for empty alternatives).
13139
13140 The case expression must be a typed string variable.
13141 Each alternative comprises the reserved word @code{when}, either a list of
13142 literal strings separated by the @code{"|"} character or the reserved word
13143 @code{others},  and the @code{"=>"} token.
13144 Each literal string must belong to the string type that is the type of the
13145 case variable.
13146 An @code{others} alternative, if present, must occur last.
13147
13148 After each @code{=>}, there are zero or more constructions.  The only
13149 constructions allowed in a case construction are other case constructions,
13150 attribute declarations and variable declarations. String type declarations and
13151 package declarations are not allowed. Variable declarations are restricted to
13152 variables that have already been declared before the case construction.
13153
13154 The value of the case variable is often given by an external reference
13155 (@pxref{External References in Project Files}).
13156
13157 @c ****************************************
13158 @c * Objects and Sources in Project Files *
13159 @c ****************************************
13160
13161 @node Objects and Sources in Project Files
13162 @section Objects and Sources in Project Files
13163
13164 @menu
13165 * Object Directory::
13166 * Exec Directory::
13167 * Source Directories::
13168 * Source File Names::
13169 @end menu
13170
13171 @noindent
13172 Each project has exactly one object directory and one or more source
13173 directories. The source directories must contain at least one source file,
13174 unless  the project file explicitly specifies that no source files are present
13175 (@pxref{Source File Names}).
13176
13177 @node Object Directory
13178 @subsection Object Directory
13179
13180 @noindent
13181 The object directory for a project is the directory containing the compiler's
13182 output (such as @file{ALI} files and object files) for the project's immediate
13183 sources.
13184
13185 The object directory is given by the value of the attribute @code{Object_Dir}
13186 in the project file.
13187
13188 @smallexample @c projectfile
13189    for Object_Dir use "objects";
13190 @end smallexample
13191
13192 @noindent
13193 The attribute @code{Object_Dir} has a string value, the path name of the object
13194 directory. The path name may be absolute or relative to the directory of the
13195 project file. This directory must already exist, and be readable and writable.
13196
13197 By default, when the attribute @code{Object_Dir} is not given an explicit value
13198 or when its value is the empty string, the object directory is the same as the
13199 directory containing the project file.
13200
13201 @node Exec Directory
13202 @subsection Exec Directory
13203
13204 @noindent
13205 The exec directory for a project is the directory containing the executables
13206 for the project's main subprograms.
13207
13208 The exec directory is given by the value of the attribute @code{Exec_Dir}
13209 in the project file.
13210
13211 @smallexample @c projectfile
13212    for Exec_Dir use "executables";
13213 @end smallexample
13214
13215 @noindent
13216 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13217 directory. The path name may be absolute or relative to the directory of the
13218 project file. This directory must already exist, and be writable.
13219
13220 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13221 or when its value is the empty string, the exec directory is the same as the
13222 object directory of the project file.
13223
13224 @node Source Directories
13225 @subsection Source Directories
13226
13227 @noindent
13228 The source directories of a project are specified by the project file
13229 attribute @code{Source_Dirs}.
13230
13231 This attribute's value is a string list. If the attribute is not given an
13232 explicit value, then there is only one source directory, the one where the
13233 project file resides.
13234
13235 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13236 as in
13237
13238 @smallexample @c projectfile
13239     for Source_Dirs use ();
13240 @end smallexample
13241
13242 @noindent
13243 indicates that the project contains no source files.
13244
13245 Otherwise, each string in the string list designates one or more
13246 source directories.
13247
13248 @smallexample @c projectfile
13249    for Source_Dirs use ("sources", "test/drivers");
13250 @end smallexample
13251
13252 @noindent
13253 If a string in the list ends with @code{"/**"},  then the directory whose path
13254 name precedes the two asterisks, as well as all its subdirectories
13255 (recursively), are source directories.
13256
13257 @smallexample @c projectfile
13258    for Source_Dirs use ("/system/sources/**");
13259 @end smallexample
13260
13261 @noindent
13262 Here the directory @code{/system/sources} and all of its subdirectories
13263 (recursively) are source directories.
13264
13265 To specify that the source directories are the directory of the project file
13266 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13267 @smallexample @c projectfile
13268    for Source_Dirs use ("./**");
13269 @end smallexample
13270
13271 @noindent
13272 Each of the source directories must exist and be readable.
13273
13274 @node Source File Names
13275 @subsection Source File Names
13276
13277 @noindent
13278 In a project that contains source files, their names may be specified by the
13279 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13280 (a string). Source file names never include any directory information.
13281
13282 If the attribute @code{Source_Files} is given an explicit value, then each
13283 element of the list is a source file name.
13284
13285 @smallexample @c projectfile
13286    for Source_Files use ("main.adb");
13287    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13288 @end smallexample
13289
13290 @noindent
13291 If the attribute @code{Source_Files} is not given an explicit value,
13292 but the attribute @code{Source_List_File} is given a string value,
13293 then the source file names are contained in the text file whose path name
13294 (absolute or relative to the directory of the project file) is the
13295 value of the attribute @code{Source_List_File}.
13296
13297 Each line in the file that is not empty or is not a comment
13298 contains a source file name.
13299
13300 @smallexample @c projectfile
13301    for Source_List_File use "source_list.txt";
13302 @end smallexample
13303
13304 @noindent
13305 By default, if neither the attribute @code{Source_Files} nor the attribute
13306 @code{Source_List_File} is given an explicit value, then each file in the
13307 source directories that conforms to the project's naming scheme
13308 (@pxref{Naming Schemes}) is an immediate source of the project.
13309
13310 A warning is issued if both attributes @code{Source_Files} and
13311 @code{Source_List_File} are given explicit values. In this case, the attribute
13312 @code{Source_Files} prevails.
13313
13314 Each source file name must be the name of one existing source file
13315 in one of the source directories.
13316
13317 A @code{Source_Files} attribute whose value is an empty list
13318 indicates that there are no source files in the project.
13319
13320 If the order of the source directories is known statically, that is if
13321 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13322 be several files with the same source file name. In this case, only the file
13323 in the first directory is considered as an immediate source of the project
13324 file. If the order of the source directories is not known statically, it is
13325 an error to have several files with the same source file name.
13326
13327 Projects can be specified to have no Ada source
13328 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13329 list, or the @code{"Ada"} may be absent from @code{Languages}:
13330
13331 @smallexample @c projectfile
13332    for Source_Dirs use ();
13333    for Source_Files use ();
13334    for Languages use ("C", "C++");
13335 @end smallexample
13336
13337 @noindent
13338 Otherwise, a project must contain at least one immediate source.
13339
13340 Projects with no source files are useful as template packages
13341 (@pxref{Packages in Project Files}) for other projects; in particular to
13342 define a package @code{Naming} (@pxref{Naming Schemes}).
13343
13344 @c ****************************
13345 @c * Importing Projects *
13346 @c ****************************
13347
13348 @node  Importing Projects
13349 @section Importing Projects
13350 @cindex @code{ADA_PROJECT_PATH}
13351 @cindex @code{GPR_PROJECT_PATH}
13352
13353 @noindent
13354 An immediate source of a project P may depend on source files that
13355 are neither immediate sources of P nor in the predefined library.
13356 To get this effect, P must @emph{import} the projects that contain the needed
13357 source files.
13358
13359 @smallexample @c projectfile
13360 @group
13361   with "project1", "utilities.gpr";
13362   with "/namings/apex.gpr";
13363   project Main is
13364     @dots{}
13365 @end group
13366 @end smallexample
13367
13368 @noindent
13369 As can be seen in this example, the syntax for importing projects is similar
13370 to the syntax for importing compilation units in Ada. However, project files
13371 use literal strings instead of names, and the @code{with} clause identifies
13372 project files rather than packages.
13373
13374 Each literal string is the file name or path name (absolute or relative) of a
13375 project file. If a string corresponds to a file name, with no path or a
13376 relative path, then its location is determined by the @emph{project path}. The
13377 latter can be queried using @code{gnatls -v}. It contains:
13378
13379 @itemize @bullet
13380 @item
13381 In first position, the directory containing the current project file.
13382 @item
13383 In last position, the default project directory. This default project directory
13384 is part of the GNAT installation and is the standard place to install project
13385 files giving access to standard support libraries.
13386 @ifclear vms
13387 @ref{Installing a library}
13388 @end ifclear
13389
13390 @item
13391 In between, all the directories referenced in the
13392 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13393 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13394 @end itemize
13395
13396 @noindent
13397 If a relative pathname is used, as in
13398
13399 @smallexample @c projectfile
13400   with "tests/proj";
13401 @end smallexample
13402
13403 @noindent
13404 then the full path for the project is constructed by concatenating this
13405 relative path to those in the project path, in order, until a matching file is
13406 found. Any symbolic link will be fully resolved in the directory of the
13407 importing project file before the imported project file is examined.
13408
13409 If the @code{with}'ed project file name does not have an extension,
13410 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13411 then the file name as specified in the @code{with} clause (no extension) will
13412 be used. In the above example, if a file @code{project1.gpr} is found, then it
13413 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13414 then it will be used; if neither file exists, this is an error.
13415
13416 A warning is issued if the name of the project file does not match the
13417 name of the project; this check is case insensitive.
13418
13419 Any source file that is an immediate source of the imported project can be
13420 used by the immediate sources of the importing project, transitively. Thus
13421 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13422 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13423 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13424 because if and when @code{B} ceases to import @code{C}, some sources in
13425 @code{A} will no longer compile.
13426
13427 A side effect of this capability is that normally cyclic dependencies are not
13428 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13429 is not allowed to import @code{A}. However, there are cases when cyclic
13430 dependencies would be beneficial. For these cases, another form of import
13431 between projects exists, the @code{limited with}: a project @code{A} that
13432 imports a project @code{B} with a straight @code{with} may also be imported,
13433 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13434 to @code{A} include at least one @code{limited with}.
13435
13436 @smallexample @c 0projectfile
13437 with "../b/b.gpr";
13438 with "../c/c.gpr";
13439 project A is
13440 end A;
13441
13442 limited with "../a/a.gpr";
13443 project B is
13444 end B;
13445
13446 with "../d/d.gpr";
13447 project C is
13448 end C;
13449
13450 limited with "../a/a.gpr";
13451 project D is
13452 end D;
13453 @end smallexample
13454
13455 @noindent
13456 In the above legal example, there are two project cycles:
13457 @itemize @bullet
13458 @item A-> B-> A
13459 @item A -> C -> D -> A
13460 @end itemize
13461
13462 @noindent
13463 In each of these cycle there is one @code{limited with}: import of @code{A}
13464 from @code{B} and import of @code{A} from @code{D}.
13465
13466 The difference between straight @code{with} and @code{limited with} is that
13467 the name of a project imported with a @code{limited with} cannot be used in the
13468 project that imports it. In particular, its packages cannot be renamed and
13469 its variables cannot be referred to.
13470
13471 An exception to the above rules for @code{limited with} is that for the main
13472 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13473 @code{limited with} is equivalent to a straight @code{with}. For example,
13474 in the example above, projects @code{B} and @code{D} could not be main
13475 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13476 each have a @code{limited with} that is the only one in a cycle of importing
13477 projects.
13478
13479 @c *********************
13480 @c * Project Extension *
13481 @c *********************
13482
13483 @node Project Extension
13484 @section Project Extension
13485
13486 @noindent
13487 During development of a large system, it is sometimes necessary to use
13488 modified versions of some of the source files, without changing the original
13489 sources. This can be achieved through the @emph{project extension} facility.
13490
13491 @smallexample @c projectfile
13492    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13493 @end smallexample
13494
13495 @noindent
13496 A project extension declaration introduces an extending project
13497 (the @emph{child}) and a project being extended (the @emph{parent}).
13498
13499 By default, a child project inherits all the sources of its parent.
13500 However, inherited sources can be overridden: a unit in a parent is hidden
13501 by a unit of the same name in the child.
13502
13503 Inherited sources are considered to be sources (but not immediate sources)
13504 of the child project; see @ref{Project File Syntax}.
13505
13506 An inherited source file retains any switches specified in the parent project.
13507
13508 For example if the project @code{Utilities} contains the spec and the
13509 body of an Ada package @code{Util_IO}, then the project
13510 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13511 The original body of @code{Util_IO} will not be considered in program builds.
13512 However, the package spec will still be found in the project
13513 @code{Utilities}.
13514
13515 A child project can have only one parent, except when it is qualified as
13516 abstract. But it may import any number of other projects.
13517
13518 A project is not allowed to import directly or indirectly at the same time a
13519 child project and any of its ancestors.
13520
13521 @c *******************************
13522 @c * Project Hierarchy Extension *
13523 @c *******************************
13524
13525 @node Project Hierarchy Extension
13526 @section Project Hierarchy Extension
13527
13528 @noindent
13529 When extending a large system spanning multiple projects, it is often
13530 inconvenient to extend every project in the hierarchy that is impacted by a
13531 small change introduced. In such cases, it is possible to create a virtual
13532 extension of entire hierarchy using @code{extends all} relationship.
13533
13534 When the project is extended using @code{extends all} inheritance, all projects
13535 that are imported by it, both directly and indirectly, are considered virtually
13536 extended. That is, the Project Manager creates "virtual projects"
13537 that extend every project in the hierarchy; all these virtual projects have
13538 no sources of their own and have as object directory the object directory of
13539 the root of "extending all" project.
13540
13541 It is possible to explicitly extend one or more projects in the hierarchy
13542 in order to modify the sources. These extending projects must be imported by
13543 the "extending all" project, which will replace the corresponding virtual
13544 projects with the explicit ones.
13545
13546 When building such a project hierarchy extension, the Project Manager will
13547 ensure that both modified sources and sources in virtual extending projects
13548 that depend on them, are recompiled.
13549
13550 By means of example, consider the following hierarchy of projects.
13551
13552 @enumerate
13553 @item
13554 project A, containing package P1
13555 @item
13556 project B importing A and containing package P2 which depends on P1
13557 @item
13558 project C importing B and containing package P3 which depends on P2
13559 @end enumerate
13560
13561 @noindent
13562 We want to modify packages P1 and P3.
13563
13564 This project hierarchy will need to be extended as follows:
13565
13566 @enumerate
13567 @item
13568 Create project A1 that extends A, placing modified P1 there:
13569
13570 @smallexample @c 0projectfile
13571 project A1 extends "(@dots{})/A" is
13572 end A1;
13573 @end smallexample
13574
13575 @item
13576 Create project C1 that "extends all" C and imports A1, placing modified
13577 P3 there:
13578
13579 @smallexample @c 0projectfile
13580 with "(@dots{})/A1";
13581 project C1 extends all "(@dots{})/C" is
13582 end C1;
13583 @end smallexample
13584 @end enumerate
13585
13586 When you build project C1, your entire modified project space will be
13587 recompiled, including the virtual project B1 that has been impacted by the
13588 "extending all" inheritance of project C.
13589
13590 Note that if a Library Project in the hierarchy is virtually extended,
13591 the virtual project that extends the Library Project is not a Library Project.
13592
13593 @c ****************************************
13594 @c * External References in Project Files *
13595 @c ****************************************
13596
13597 @node  External References in Project Files
13598 @section External References in Project Files
13599
13600 @noindent
13601 A project file may contain references to external variables; such references
13602 are called @emph{external references}.
13603
13604 An external variable is either defined as part of the environment (an
13605 environment variable in Unix, for example) or else specified on the command
13606 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13607 If both, then the command line value is used.
13608
13609 The value of an external reference is obtained by means of the built-in
13610 function @code{external}, which returns a string value.
13611 This function has two forms:
13612 @itemize @bullet
13613 @item @code{external (external_variable_name)}
13614 @item @code{external (external_variable_name, default_value)}
13615 @end itemize
13616
13617 @noindent
13618 Each parameter must be a string literal.  For example:
13619
13620 @smallexample @c projectfile
13621    external ("USER")
13622    external ("OS", "GNU/Linux")
13623 @end smallexample
13624
13625 @noindent
13626 In the form with one parameter, the function returns the value of
13627 the external variable given as parameter. If this name is not present in the
13628 environment, the function returns an empty string.
13629
13630 In the form with two string parameters, the second argument is
13631 the value returned when the variable given as the first argument is not
13632 present in the environment. In the example above, if @code{"OS"} is not
13633 the name of ^an environment variable^a logical name^ and is not passed on
13634 the command line, then the returned value is @code{"GNU/Linux"}.
13635
13636 An external reference may be part of a string expression or of a string
13637 list expression, and can therefore appear in a variable declaration or
13638 an attribute declaration.
13639
13640 @smallexample @c projectfile
13641 @group
13642    type Mode_Type is ("Debug", "Release");
13643    Mode : Mode_Type := external ("MODE");
13644    case Mode is
13645      when "Debug" =>
13646         @dots{}
13647 @end group
13648 @end smallexample
13649
13650 @c *****************************
13651 @c * Packages in Project Files *
13652 @c *****************************
13653
13654 @node  Packages in Project Files
13655 @section Packages in Project Files
13656
13657 @noindent
13658 A @emph{package} defines the settings for project-aware tools within a
13659 project.
13660 For each such tool one can declare a package; the names for these
13661 packages are preset (@pxref{Packages}).
13662 A package may contain variable declarations, attribute declarations, and case
13663 constructions.
13664
13665 @smallexample @c projectfile
13666 @group
13667    project Proj is
13668       package Builder is  -- used by gnatmake
13669          for ^Default_Switches^Default_Switches^ ("Ada")
13670              use ("^-v^-v^",
13671                   "^-g^-g^");
13672       end Builder;
13673    end Proj;
13674 @end group
13675 @end smallexample
13676
13677 @noindent
13678 The syntax of package declarations mimics that of package in Ada.
13679
13680 Most of the packages have an attribute
13681 @code{^Default_Switches^Default_Switches^}.
13682 This attribute is an associative array, and its value is a string list.
13683 The index of the associative array is the name of a programming language (case
13684 insensitive). This attribute indicates the ^switch^switch^
13685 or ^switches^switches^ to be used
13686 with the corresponding tool.
13687
13688 Some packages also have another attribute, @code{^Switches^Switches^},
13689 an associative array whose value is a string list.
13690 The index is the name of a source file.
13691 This attribute indicates the ^switch^switch^
13692 or ^switches^switches^ to be used by the corresponding
13693 tool when dealing with this specific file.
13694
13695 Further information on these ^switch^switch^-related attributes is found in
13696 @ref{^Switches^Switches^ and Project Files}.
13697
13698 A package may be declared as a @emph{renaming} of another package; e.g., from
13699 the project file for an imported project.
13700
13701 @smallexample @c projectfile
13702 @group
13703   with "/global/apex.gpr";
13704   project Example is
13705     package Naming renames Apex.Naming;
13706     @dots{}
13707   end Example;
13708 @end group
13709 @end smallexample
13710
13711 @noindent
13712 Packages that are renamed in other project files often come from project files
13713 that have no sources: they are just used as templates. Any modification in the
13714 template will be reflected automatically in all the project files that rename
13715 a package from the template.
13716
13717 In addition to the tool-oriented packages, you can also declare a package
13718 named @code{Naming} to establish specialized source file naming conventions
13719 (@pxref{Naming Schemes}).
13720
13721 @c ************************************
13722 @c * Variables from Imported Projects *
13723 @c ************************************
13724
13725 @node Variables from Imported Projects
13726 @section Variables from Imported Projects
13727
13728 @noindent
13729 An attribute or variable defined in an imported or parent project can
13730 be used in expressions in the importing / extending project.
13731 Such an attribute or variable is denoted by an expanded name whose prefix
13732 is either the name of the project or the expanded name of a package within
13733 a project.
13734
13735 @smallexample @c projectfile
13736 @group
13737   with "imported";
13738   project Main extends "base" is
13739      Var1 := Imported.Var;
13740      Var2 := Base.Var & ".new";
13741 @end group
13742
13743 @group
13744      package Builder is
13745         for ^Default_Switches^Default_Switches^ ("Ada")
13746             use Imported.Builder'Ada_^Switches^Switches^ &
13747                 "^-gnatg^-gnatg^" &
13748                 "^-v^-v^";
13749      end Builder;
13750 @end group
13751
13752 @group
13753      package Compiler is
13754         for ^Default_Switches^Default_Switches^ ("Ada")
13755             use Base.Compiler'Ada_^Switches^Switches^;
13756      end Compiler;
13757   end Main;
13758 @end group
13759 @end smallexample
13760
13761 @noindent
13762 In this example:
13763
13764 @itemize @bullet
13765 @item
13766 The value of @code{Var1} is a copy of the variable @code{Var} defined
13767 in the project file @file{"imported.gpr"}
13768 @item
13769 the value of @code{Var2} is a copy of the value of variable @code{Var}
13770 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13771 @item
13772 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13773 @code{Builder} is a string list that includes in its value a copy of the value
13774 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13775 in project file @file{imported.gpr} plus two new elements:
13776 @option{"^-gnatg^-gnatg^"}
13777 and @option{"^-v^-v^"};
13778 @item
13779 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13780 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13781 defined in the @code{Compiler} package in project file @file{base.gpr},
13782 the project being extended.
13783 @end itemize
13784
13785 @c ******************
13786 @c * Naming Schemes *
13787 @c ******************
13788
13789 @node  Naming Schemes
13790 @section Naming Schemes
13791
13792 @noindent
13793 Sometimes an Ada software system is ported from a foreign compilation
13794 environment to GNAT, and the file names do not use the default GNAT
13795 conventions. Instead of changing all the file names (which for a variety
13796 of reasons might not be possible), you can define the relevant file
13797 naming scheme in the @code{Naming} package in your project file.
13798
13799 @noindent
13800 Note that the use of pragmas described in
13801 @ref{Alternative File Naming Schemes} by mean of a configuration
13802 pragmas file is not supported when using project files. You must use
13803 the features described in this paragraph. You can however use specify
13804 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13805
13806 @ifclear vms
13807 For example, the following
13808 package models the Apex file naming rules:
13809
13810 @smallexample @c projectfile
13811 @group
13812   package Naming is
13813     for Casing               use "lowercase";
13814     for Dot_Replacement      use ".";
13815     for Spec_Suffix ("Ada")  use ".1.ada";
13816     for Body_Suffix ("Ada")  use ".2.ada";
13817   end Naming;
13818 @end group
13819 @end smallexample
13820 @end ifclear
13821
13822 @ifset vms
13823 For example, the following package models the HP Ada file naming rules:
13824
13825 @smallexample @c projectfile
13826 @group
13827   package Naming is
13828     for Casing               use "lowercase";
13829     for Dot_Replacement      use "__";
13830     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13831     for Body_Suffix ("Ada")  use ".^ada^ada^";
13832   end Naming;
13833 @end group
13834 @end smallexample
13835
13836 @noindent
13837 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13838 names in lower case)
13839 @end ifset
13840
13841 @noindent
13842 You can define the following attributes in package @code{Naming}:
13843
13844 @table @code
13845
13846 @item @code{Casing}
13847 This must be a string with one of the three values @code{"lowercase"},
13848 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13849
13850 @noindent
13851 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13852
13853 @item @code{Dot_Replacement}
13854 This must be a string whose value satisfies the following conditions:
13855
13856 @itemize @bullet
13857 @item It must not be empty
13858 @item It cannot start or end with an alphanumeric character
13859 @item It cannot be a single underscore
13860 @item It cannot start with an underscore followed by an alphanumeric
13861 @item It cannot contain a dot @code{'.'} except if the entire string
13862 is @code{"."}
13863 @end itemize
13864
13865 @noindent
13866 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13867
13868 @item @code{Spec_Suffix}
13869 This is an associative array (indexed by the programming language name, case
13870 insensitive) whose value is a string that must satisfy the following
13871 conditions:
13872
13873 @itemize @bullet
13874 @item It must not be empty
13875 @item It must include at least one dot
13876 @end itemize
13877 @noindent
13878 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13879 @code{"^.ads^.ADS^"}.
13880
13881 @item @code{Body_Suffix}
13882 This is an associative array (indexed by the programming language name, case
13883 insensitive) whose value is a string that must satisfy the following
13884 conditions:
13885
13886 @itemize @bullet
13887 @item It must not be empty
13888 @item It must include at least one dot
13889 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13890 @end itemize
13891 @noindent
13892 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13893 same string, then a file name that ends with the longest of these two suffixes
13894 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13895 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13896
13897 If the suffix does not start with a '.', a file with a name exactly equal
13898 to the suffix will also be part of the project (for instance if you define
13899 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13900 of the project. This is not interesting in general when using projects to
13901 compile. However, it might become useful when a project is also used to
13902 find the list of source files in an editor, like the GNAT Programming System
13903 (GPS).
13904
13905 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13906 @code{"^.adb^.ADB^"}.
13907
13908 @item @code{Separate_Suffix}
13909 This must be a string whose value satisfies the same conditions as
13910 @code{Body_Suffix}. The same "longest suffix" rules apply.
13911
13912 @noindent
13913 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13914 value as @code{Body_Suffix ("Ada")}.
13915
13916 @item @code{Spec}
13917 @noindent
13918 You can use the associative array attribute @code{Spec}  to define
13919 the source file name for an individual Ada compilation unit's spec. The array
13920 index must be a string literal that identifies the Ada unit (case insensitive).
13921 The value of this attribute must be a string that identifies the file that
13922 contains this unit's spec (case sensitive or insensitive depending on the
13923 operating system).
13924
13925 @smallexample @c projectfile
13926    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13927 @end smallexample
13928
13929 When the source file contains several units, you can indicate at what
13930 position the unit occurs in the file, with the following. The first unit
13931 in the file has index 1
13932
13933 @smallexample @c projectfile
13934   for Body ("top") use "foo.a" at 1;
13935   for Body ("foo") use "foo.a" at 2;
13936 @end smallexample
13937
13938 @item @code{Body}
13939
13940 You can use the associative array attribute @code{Body} to
13941 define the source file name for an individual Ada compilation unit's body
13942 (possibly a subunit).  The array index must be a string literal that identifies
13943 the Ada unit (case insensitive).  The value of this attribute must be a string
13944 that identifies the file that contains this unit's body or subunit (case
13945 sensitive or insensitive depending on the operating system).
13946
13947 @smallexample @c projectfile
13948    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13949 @end smallexample
13950 @end table
13951
13952 @c ********************
13953 @c * Library Projects *
13954 @c ********************
13955
13956 @node Library Projects
13957 @section Library Projects
13958
13959 @noindent
13960 @emph{Library projects} are projects whose object code is placed in a library.
13961 (Note that this facility is not yet supported on all platforms).
13962
13963 @code{gnatmake} or @code{gprbuild} will collect all object files into a
13964 single archive, which might either be a shared or a static library. This
13965 library can later on be linked with multiple executables, potentially
13966 reducing their sizes.
13967
13968 If your project file specifies languages other than Ada, but you are still
13969 using @code{gnatmake} to compile and link, the latter will not try to
13970 compile your sources other than Ada (you should use @code{gprbuild} if that
13971 is your intent). However, @code{gnatmake} will automatically link all object
13972 files found in the object directory, whether or not they were compiled from
13973 an Ada source file. This specific behavior only applies when multiple
13974 languages are specified.
13975
13976 To create a library project, you need to define in its project file
13977 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13978 Additionally, you may define other library-related attributes such as
13979 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13980 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13981
13982 The @code{Library_Name} attribute has a string value. There is no restriction
13983 on the name of a library. It is the responsibility of the developer to
13984 choose a name that will be accepted by the platform. It is recommended to
13985 choose names that could be Ada identifiers; such names are almost guaranteed
13986 to be acceptable on all platforms.
13987
13988 The @code{Library_Dir} attribute has a string value that designates the path
13989 (absolute or relative) of the directory where the library will reside.
13990 It must designate an existing directory, and this directory must be writable,
13991 different from the project's object directory and from any source directory
13992 in the project tree.
13993
13994 If both @code{Library_Name} and @code{Library_Dir} are specified and
13995 are legal, then the project file defines a library project.  The optional
13996 library-related attributes are checked only for such project files.
13997
13998 The @code{Library_Kind} attribute has a string value that must be one of the
13999 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14000 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14001 attribute is not specified, the library is a static library, that is
14002 an archive of object files that can be potentially linked into a
14003 static executable. Otherwise, the library may be dynamic or
14004 relocatable, that is a library that is loaded only at the start of execution.
14005
14006 If you need to build both a static and a dynamic library, you should use two
14007 different object directories, since in some cases some extra code needs to
14008 be generated for the latter. For such cases, it is recommended to either use
14009 two different project files, or a single one which uses external variables
14010 to indicate what kind of library should be build.
14011
14012 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14013 directory where the ALI files of the library will be copied. When it is
14014 not specified, the ALI files are copied to the directory specified in
14015 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14016 must be writable and different from the project's object directory and from
14017 any source directory in the project tree.
14018
14019 The @code{Library_Version} attribute has a string value whose interpretation
14020 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14021 used only for dynamic/relocatable libraries as the internal name of the
14022 library (the @code{"soname"}). If the library file name (built from the
14023 @code{Library_Name}) is different from the @code{Library_Version}, then the
14024 library file will be a symbolic link to the actual file whose name will be
14025 @code{Library_Version}.
14026
14027 Example (on Unix):
14028
14029 @smallexample @c projectfile
14030 @group
14031 project Plib is
14032
14033    Version := "1";
14034
14035    for Library_Dir use "lib_dir";
14036    for Library_Name use "dummy";
14037    for Library_Kind use "relocatable";
14038    for Library_Version use "libdummy.so." & Version;
14039
14040 end Plib;
14041 @end group
14042 @end smallexample
14043
14044 @noindent
14045 Directory @file{lib_dir} will contain the internal library file whose name
14046 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14047 @file{libdummy.so.1}.
14048
14049 When @command{gnatmake} detects that a project file
14050 is a library project file, it will check all immediate sources of the project
14051 and rebuild the library if any of the sources have been recompiled.
14052
14053 Standard project files can import library project files. In such cases,
14054 the libraries will only be rebuilt if some of its sources are recompiled
14055 because they are in the closure of some other source in an importing project.
14056 Sources of the library project files that are not in such a closure will
14057 not be checked, unless the full library is checked, because one of its sources
14058 needs to be recompiled.
14059
14060 For instance, assume the project file @code{A} imports the library project file
14061 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14062 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14063 @file{l2.ads}, @file{l2.adb}.
14064
14065 If @file{l1.adb} has been modified, then the library associated with @code{L}
14066 will be rebuilt when compiling all the immediate sources of @code{A} only
14067 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14068 @code{"with L1;"}.
14069
14070 To be sure that all the sources in the library associated with @code{L} are
14071 up to date, and that all the sources of project @code{A} are also up to date,
14072 the following two commands needs to be used:
14073
14074 @smallexample
14075 gnatmake -Pl.gpr
14076 gnatmake -Pa.gpr
14077 @end smallexample
14078
14079 When a library is built or rebuilt, an attempt is made first to delete all
14080 files in the library directory.
14081 All @file{ALI} files will also be copied from the object directory to the
14082 library directory. To build executables, @command{gnatmake} will use the
14083 library rather than the individual object files.
14084
14085 @ifclear vms
14086 It is also possible to create library project files for third-party libraries
14087 that are precompiled and cannot be compiled locally thanks to the
14088 @code{externally_built} attribute. (See @ref{Installing a library}).
14089 @end ifclear
14090
14091 @c *******************************
14092 @c * Stand-alone Library Projects *
14093 @c *******************************
14094
14095 @node Stand-alone Library Projects
14096 @section Stand-alone Library Projects
14097
14098 @noindent
14099 A Stand-alone Library is a library that contains the necessary code to
14100 elaborate the Ada units that are included in the library. A Stand-alone
14101 Library is suitable to be used in an executable when the main is not
14102 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14103 subprogram.
14104
14105 A Stand-alone Library Project is a Library Project where the library is
14106 a Stand-alone Library.
14107
14108 To be a Stand-alone Library Project, in addition to the two attributes
14109 that make a project a Library Project (@code{Library_Name} and
14110 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14111 @code{Library_Interface} must be defined.
14112
14113 @smallexample @c projectfile
14114 @group
14115    for Library_Dir use "lib_dir";
14116    for Library_Name use "dummy";
14117    for Library_Interface use ("int1", "int1.child");
14118 @end group
14119 @end smallexample
14120
14121 Attribute @code{Library_Interface} has a nonempty string list value,
14122 each string in the list designating a unit contained in an immediate source
14123 of the project file.
14124
14125 When a Stand-alone Library is built, first the binder is invoked to build
14126 a package whose name depends on the library name
14127 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14128 This binder-generated package includes initialization and
14129 finalization procedures whose
14130 names depend on the library name (dummyinit and dummyfinal in the example
14131 above). The object corresponding to this package is included in the library.
14132
14133 A dynamic or relocatable Stand-alone Library is automatically initialized
14134 if automatic initialization of Stand-alone Libraries is supported on the
14135 platform and if attribute @code{Library_Auto_Init} is not specified or
14136 is specified with the value "true". A static Stand-alone Library is never
14137 automatically initialized.
14138
14139 Single string attribute @code{Library_Auto_Init} may be specified with only
14140 two possible values: "false" or "true" (case-insensitive). Specifying
14141 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14142 initialization of dynamic or relocatable libraries.
14143
14144 When a non-automatically initialized Stand-alone Library is used
14145 in an executable, its initialization procedure must be called before
14146 any service of the library is used.
14147 When the main subprogram is in Ada, it may mean that the initialization
14148 procedure has to be called during elaboration of another package.
14149
14150 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14151 (those that are listed in attribute @code{Library_Interface}) are copied to
14152 the Library Directory. As a consequence, only the Interface Units may be
14153 imported from Ada units outside of the library. If other units are imported,
14154 the binding phase will fail.
14155
14156 When a Stand-Alone Library is bound, the switches that are specified in
14157 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14158 used in the call to @command{gnatbind}.
14159
14160 The string list attribute @code{Library_Options} may be used to specified
14161 additional switches to the call to @command{gcc} to link the library.
14162
14163 The attribute @code{Library_Src_Dir}, may be specified for a
14164 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14165 single string value. Its value must be the path (absolute or relative to the
14166 project directory) of an existing directory. This directory cannot be the
14167 object directory or one of the source directories, but it can be the same as
14168 the library directory. The sources of the Interface
14169 Units of the library, necessary to an Ada client of the library, will be
14170 copied to the designated directory, called Interface Copy directory.
14171 These sources includes the specs of the Interface Units, but they may also
14172 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14173 are used, or when there is a generic units in the spec. Before the sources
14174 are copied to the Interface Copy directory, an attempt is made to delete all
14175 files in the Interface Copy directory.
14176
14177 @c *************************************
14178 @c * Switches Related to Project Files *
14179 @c *************************************
14180 @node Switches Related to Project Files
14181 @section Switches Related to Project Files
14182
14183 @noindent
14184 The following switches are used by GNAT tools that support project files:
14185
14186 @table @option
14187
14188 @item ^-P^/PROJECT_FILE=^@var{project}
14189 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14190 Indicates the name of a project file. This project file will be parsed with
14191 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14192 if any, and using the external references indicated
14193 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14194 @ifclear vms
14195 There may zero, one or more spaces between @option{-P} and @var{project}.
14196 @end ifclear
14197
14198 @noindent
14199 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14200
14201 @noindent
14202 Since the Project Manager parses the project file only after all the switches
14203 on the command line are checked, the order of the switches
14204 @option{^-P^/PROJECT_FILE^},
14205 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14206 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14207
14208 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14209 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14210 Indicates that external variable @var{name} has the value @var{value}.
14211 The Project Manager will use this value for occurrences of
14212 @code{external(name)} when parsing the project file.
14213
14214 @ifclear vms
14215 @noindent
14216 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14217 put between quotes.
14218 @smallexample
14219   -XOS=NT
14220   -X"user=John Doe"
14221 @end smallexample
14222 @end ifclear
14223
14224 @noindent
14225 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14226 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14227 @var{name}, only the last one is used.
14228
14229 @noindent
14230 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14231 takes precedence over the value of the same name in the environment.
14232
14233 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14234 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14235 Indicates the verbosity of the parsing of GNAT project files.
14236
14237 @ifclear vms
14238 @option{-vP0} means Default;
14239 @option{-vP1} means Medium;
14240 @option{-vP2} means High.
14241 @end ifclear
14242
14243 @ifset vms
14244 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14245 HIGH.
14246 @end ifset
14247
14248 @noindent
14249 The default is ^Default^DEFAULT^: no output for syntactically correct
14250 project files.
14251 @noindent
14252 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14253 only the last one is used.
14254
14255 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14256 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14257 Add directory <dir> at the beginning of the project search path, in order,
14258 after the current working directory.
14259
14260 @ifclear vms
14261 @item -eL
14262 @cindex @option{-eL} (any project-aware tool)
14263 Follow all symbolic links when processing project files.
14264 @end ifclear
14265
14266 @item ^--subdirs^/SUBDIRS^=<subdir>
14267 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14268 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14269 directories (except the source directories) are the subdirectories <subdir>
14270 of the directories specified in the project files. This applies in particular
14271 to object directories, library directories and exec directories. If the
14272 subdirectories do not exist, they are created automatically.
14273
14274 @end table
14275
14276 @c **********************************
14277 @c * Tools Supporting Project Files *
14278 @c **********************************
14279
14280 @node  Tools Supporting Project Files
14281 @section Tools Supporting Project Files
14282
14283 @menu
14284 * gnatmake and Project Files::
14285 * The GNAT Driver and Project Files::
14286 @end menu
14287
14288 @node gnatmake and Project Files
14289 @subsection gnatmake and Project Files
14290
14291 @noindent
14292 This section covers several topics related to @command{gnatmake} and
14293 project files: defining ^switches^switches^ for @command{gnatmake}
14294 and for the tools that it invokes; specifying configuration pragmas;
14295 the use of the @code{Main} attribute; building and rebuilding library project
14296 files.
14297
14298 @menu
14299 * ^Switches^Switches^ and Project Files::
14300 * Specifying Configuration Pragmas::
14301 * Project Files and Main Subprograms::
14302 * Library Project Files::
14303 @end menu
14304
14305 @node ^Switches^Switches^ and Project Files
14306 @subsubsection ^Switches^Switches^ and Project Files
14307
14308 @ifset vms
14309 It is not currently possible to specify VMS style qualifiers in the project
14310 files; only Unix style ^switches^switches^ may be specified.
14311 @end ifset
14312
14313 @noindent
14314 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14315 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14316 attribute, a @code{^Switches^Switches^} attribute, or both;
14317 as their names imply, these ^switch^switch^-related
14318 attributes affect the ^switches^switches^ that are used for each of these GNAT
14319 components when
14320 @command{gnatmake} is invoked.  As will be explained below, these
14321 component-specific ^switches^switches^ precede
14322 the ^switches^switches^ provided on the @command{gnatmake} command line.
14323
14324 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14325 array indexed by language name (case insensitive) whose value is a string list.
14326 For example:
14327
14328 @smallexample @c projectfile
14329 @group
14330 package Compiler is
14331   for ^Default_Switches^Default_Switches^ ("Ada")
14332       use ("^-gnaty^-gnaty^",
14333            "^-v^-v^");
14334 end Compiler;
14335 @end group
14336 @end smallexample
14337
14338 @noindent
14339 The @code{^Switches^Switches^} attribute is also an associative array,
14340 indexed by a file name (which may or may not be case sensitive, depending
14341 on the operating system) whose value is a string list.  For example:
14342
14343 @smallexample @c projectfile
14344 @group
14345 package Builder is
14346    for ^Switches^Switches^ ("main1.adb")
14347        use ("^-O2^-O2^");
14348    for ^Switches^Switches^ ("main2.adb")
14349        use ("^-g^-g^");
14350 end Builder;
14351 @end group
14352 @end smallexample
14353
14354 @noindent
14355 For the @code{Builder} package, the file names must designate source files
14356 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14357 file names must designate @file{ALI} or source files for main subprograms.
14358 In each case just the file name without an explicit extension is acceptable.
14359
14360 For each tool used in a program build (@command{gnatmake}, the compiler, the
14361 binder, and the linker), the corresponding package @dfn{contributes} a set of
14362 ^switches^switches^ for each file on which the tool is invoked, based on the
14363 ^switch^switch^-related attributes defined in the package.
14364 In particular, the ^switches^switches^
14365 that each of these packages contributes for a given file @var{f} comprise:
14366
14367 @itemize @bullet
14368 @item
14369 the value of attribute @code{^Switches^Switches^ (@var{f})},
14370 if it is specified in the package for the given file,
14371 @item
14372 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14373 if it is specified in the package.
14374 @end itemize
14375
14376 @noindent
14377 If neither of these attributes is defined in the package, then the package does
14378 not contribute any ^switches^switches^ for the given file.
14379
14380 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14381 two sets, in the following order: those contributed for the file
14382 by the @code{Builder} package;
14383 and the switches passed on the command line.
14384
14385 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14386 the ^switches^switches^ passed to the tool comprise three sets,
14387 in the following order:
14388
14389 @enumerate
14390 @item
14391 the applicable ^switches^switches^ contributed for the file
14392 by the @code{Builder} package in the project file supplied on the command line;
14393
14394 @item
14395 those contributed for the file by the package (in the relevant project file --
14396 see below) corresponding to the tool; and
14397
14398 @item
14399 the applicable switches passed on the command line.
14400 @end enumerate
14401
14402 @noindent
14403 The term @emph{applicable ^switches^switches^} reflects the fact that
14404 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14405 tools, depending on the individual ^switch^switch^.
14406
14407 @command{gnatmake} may invoke the compiler on source files from different
14408 projects. The Project Manager will use the appropriate project file to
14409 determine the @code{Compiler} package for each source file being compiled.
14410 Likewise for the @code{Binder} and @code{Linker} packages.
14411
14412 As an example, consider the following package in a project file:
14413
14414 @smallexample @c projectfile
14415 @group
14416 project Proj1 is
14417    package Compiler is
14418       for ^Default_Switches^Default_Switches^ ("Ada")
14419           use ("^-g^-g^");
14420       for ^Switches^Switches^ ("a.adb")
14421           use ("^-O1^-O1^");
14422       for ^Switches^Switches^ ("b.adb")
14423           use ("^-O2^-O2^",
14424                "^-gnaty^-gnaty^");
14425    end Compiler;
14426 end Proj1;
14427 @end group
14428 @end smallexample
14429
14430 @noindent
14431 If @command{gnatmake} is invoked with this project file, and it needs to
14432 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14433 @file{a.adb} will be compiled with the ^switch^switch^
14434 @option{^-O1^-O1^},
14435 @file{b.adb} with ^switches^switches^
14436 @option{^-O2^-O2^}
14437 and @option{^-gnaty^-gnaty^},
14438 and @file{c.adb} with @option{^-g^-g^}.
14439
14440 The following example illustrates the ordering of the ^switches^switches^
14441 contributed by different packages:
14442
14443 @smallexample @c projectfile
14444 @group
14445 project Proj2 is
14446    package Builder is
14447       for ^Switches^Switches^ ("main.adb")
14448           use ("^-g^-g^",
14449                "^-O1^-)1^",
14450                "^-f^-f^");
14451    end Builder;
14452 @end group
14453
14454 @group
14455    package Compiler is
14456       for ^Switches^Switches^ ("main.adb")
14457           use ("^-O2^-O2^");
14458    end Compiler;
14459 end Proj2;
14460 @end group
14461 @end smallexample
14462
14463 @noindent
14464 If you issue the command:
14465
14466 @smallexample
14467     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14468 @end smallexample
14469
14470 @noindent
14471 then the compiler will be invoked on @file{main.adb} with the following
14472 sequence of ^switches^switches^
14473
14474 @smallexample
14475    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14476 @end smallexample
14477
14478 with the last @option{^-O^-O^}
14479 ^switch^switch^ having precedence over the earlier ones;
14480 several other ^switches^switches^
14481 (such as @option{^-c^-c^}) are added implicitly.
14482
14483 The ^switches^switches^
14484 @option{^-g^-g^}
14485 and @option{^-O1^-O1^} are contributed by package
14486 @code{Builder},  @option{^-O2^-O2^} is contributed
14487 by the package @code{Compiler}
14488 and @option{^-O0^-O0^} comes from the command line.
14489
14490 The @option{^-g^-g^}
14491 ^switch^switch^ will also be passed in the invocation of
14492 @command{Gnatlink.}
14493
14494 A final example illustrates switch contributions from packages in different
14495 project files:
14496
14497 @smallexample @c projectfile
14498 @group
14499 project Proj3 is
14500    for Source_Files use ("pack.ads", "pack.adb");
14501    package Compiler is
14502       for ^Default_Switches^Default_Switches^ ("Ada")
14503           use ("^-gnata^-gnata^");
14504    end Compiler;
14505 end Proj3;
14506 @end group
14507
14508 @group
14509 with "Proj3";
14510 project Proj4 is
14511    for Source_Files use ("foo_main.adb", "bar_main.adb");
14512    package Builder is
14513       for ^Switches^Switches^ ("foo_main.adb")
14514           use ("^-s^-s^",
14515                "^-g^-g^");
14516    end Builder;
14517 end Proj4;
14518 @end group
14519
14520 @group
14521 -- Ada source file:
14522 with Pack;
14523 procedure Foo_Main is
14524    @dots{}
14525 end Foo_Main;
14526 @end group
14527 @end smallexample
14528
14529 If the command is
14530 @smallexample
14531 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14532 @end smallexample
14533
14534 @noindent
14535 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14536 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14537 @option{^-gnato^-gnato^} (passed on the command line).
14538 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14539 are @option{^-g^-g^} from @code{Proj4.Builder},
14540 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14541 and @option{^-gnato^-gnato^} from the command line.
14542
14543 @noindent
14544 When using @command{gnatmake} with project files, some ^switches^switches^ or
14545 arguments may be expressed as relative paths. As the working directory where
14546 compilation occurs may change, these relative paths are converted to absolute
14547 paths. For the ^switches^switches^ found in a project file, the relative paths
14548 are relative to the project file directory, for the switches on the command
14549 line, they are relative to the directory where @command{gnatmake} is invoked.
14550 The ^switches^switches^ for which this occurs are:
14551 ^-I^-I^,
14552 ^-A^-A^,
14553 ^-L^-L^,
14554 ^-aO^-aO^,
14555 ^-aL^-aL^,
14556 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14557 ^switch^switch^
14558 ^-o^-o^, object files specified in package @code{Linker} or after
14559 -largs on the command line). The exception to this rule is the ^switch^switch^
14560 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14561
14562 @node Specifying Configuration Pragmas
14563 @subsubsection Specifying Configuration Pragmas
14564
14565 When using @command{gnatmake} with project files, if there exists a file
14566 @file{gnat.adc} that contains configuration pragmas, this file will be
14567 ignored.
14568
14569 Configuration pragmas can be defined by means of the following attributes in
14570 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14571 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14572
14573 Both these attributes are single string attributes. Their values is the path
14574 name of a file containing configuration pragmas. If a path name is relative,
14575 then it is relative to the project directory of the project file where the
14576 attribute is defined.
14577
14578 When compiling a source, the configuration pragmas used are, in order,
14579 those listed in the file designated by attribute
14580 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14581 project file, if it is specified, and those listed in the file designated by
14582 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14583 the project file of the source, if it exists.
14584
14585 @node Project Files and Main Subprograms
14586 @subsubsection Project Files and Main Subprograms
14587
14588 @noindent
14589 When using a project file, you can invoke @command{gnatmake}
14590 with one or several main subprograms, by specifying their source files on the
14591 command line.
14592
14593 @smallexample
14594     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14595 @end smallexample
14596
14597 @noindent
14598 Each of these needs to be a source file of the same project, except
14599 when the switch ^-u^/UNIQUE^ is used.
14600
14601 @noindent
14602 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14603 same project, one of the project in the tree rooted at the project specified
14604 on the command line. The package @code{Builder} of this common project, the
14605 "main project" is the one that is considered by @command{gnatmake}.
14606
14607 @noindent
14608 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14609 imported directly or indirectly by the project specified on the command line.
14610 Note that if such a source file is not part of the project specified on the
14611 command line, the ^switches^switches^ found in package @code{Builder} of the
14612 project specified on the command line, if any, that are transmitted
14613 to the compiler will still be used, not those found in the project file of
14614 the source file.
14615
14616 @noindent
14617 When using a project file, you can also invoke @command{gnatmake} without
14618 explicitly specifying any main, and the effect depends on whether you have
14619 defined the @code{Main} attribute.  This attribute has a string list value,
14620 where each element in the list is the name of a source file (the file
14621 extension is optional) that contains a unit that can be a main subprogram.
14622
14623 If the @code{Main} attribute is defined in a project file as a non-empty
14624 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14625 line, then invoking @command{gnatmake} with this project file but without any
14626 main on the command line is equivalent to invoking @command{gnatmake} with all
14627 the file names in the @code{Main} attribute on the command line.
14628
14629 Example:
14630 @smallexample @c projectfile
14631 @group
14632    project Prj is
14633       for Main use ("main1", "main2", "main3");
14634    end Prj;
14635 @end group
14636 @end smallexample
14637
14638 @noindent
14639 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14640 is equivalent to
14641 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14642
14643 When the project attribute @code{Main} is not specified, or is specified
14644 as an empty string list, or when the switch @option{-u} is used on the command
14645 line, then invoking @command{gnatmake} with no main on the command line will
14646 result in all immediate sources of the project file being checked, and
14647 potentially recompiled. Depending on the presence of the switch @option{-u},
14648 sources from other project files on which the immediate sources of the main
14649 project file depend are also checked and potentially recompiled. In other
14650 words, the @option{-u} switch is applied to all of the immediate sources of the
14651 main project file.
14652
14653 When no main is specified on the command line and attribute @code{Main} exists
14654 and includes several mains, or when several mains are specified on the
14655 command line, the default ^switches^switches^ in package @code{Builder} will
14656 be used for all mains, even if there are specific ^switches^switches^
14657 specified for one or several mains.
14658
14659 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14660 the specific ^switches^switches^ for each main, if they are specified.
14661
14662 @node Library Project Files
14663 @subsubsection Library Project Files
14664
14665 @noindent
14666 When @command{gnatmake} is invoked with a main project file that is a library
14667 project file, it is not allowed to specify one or more mains on the command
14668 line.
14669
14670 @noindent
14671 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14672 ^-l^/ACTION=LINK^ have special meanings.
14673
14674 @itemize @bullet
14675 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14676 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14677 library.
14678
14679 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14680 to @command{gnatmake} that the binder generated file should be compiled
14681 (in the case of a stand-alone library) and that the library should be built.
14682
14683 @end itemize
14684
14685 @node The GNAT Driver and Project Files
14686 @subsection The GNAT Driver and Project Files
14687
14688 @noindent
14689 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14690 can benefit from project files:
14691 @command{^gnatbind^gnatbind^},
14692 @command{^gnatcheck^gnatcheck^}),
14693 @command{^gnatclean^gnatclean^}),
14694 @command{^gnatelim^gnatelim^},
14695 @command{^gnatfind^gnatfind^},
14696 @command{^gnatlink^gnatlink^},
14697 @command{^gnatls^gnatls^},
14698 @command{^gnatmetric^gnatmetric^},
14699 @command{^gnatpp^gnatpp^},
14700 @command{^gnatstub^gnatstub^},
14701 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14702 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14703 They must be invoked through the @command{gnat} driver.
14704
14705 The @command{gnat} driver is a wrapper that accepts a number of commands and
14706 calls the corresponding tool. It was designed initially for VMS platforms (to
14707 convert VMS qualifiers to Unix-style switches), but it is now available on all
14708 GNAT platforms.
14709
14710 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14711 (case insensitive):
14712
14713 @itemize @bullet
14714 @item
14715 BIND to invoke @command{^gnatbind^gnatbind^}
14716 @item
14717 CHOP to invoke @command{^gnatchop^gnatchop^}
14718 @item
14719 CLEAN to invoke @command{^gnatclean^gnatclean^}
14720 @item
14721 COMP or COMPILE to invoke the compiler
14722 @item
14723 ELIM to invoke @command{^gnatelim^gnatelim^}
14724 @item
14725 FIND to invoke @command{^gnatfind^gnatfind^}
14726 @item
14727 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14728 @item
14729 LINK to invoke @command{^gnatlink^gnatlink^}
14730 @item
14731 LS or LIST to invoke @command{^gnatls^gnatls^}
14732 @item
14733 MAKE to invoke @command{^gnatmake^gnatmake^}
14734 @item
14735 NAME to invoke @command{^gnatname^gnatname^}
14736 @item
14737 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14738 @item
14739 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14740 @item
14741 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14742 @item
14743 STUB to invoke @command{^gnatstub^gnatstub^}
14744 @item
14745 XREF to invoke @command{^gnatxref^gnatxref^}
14746 @end itemize
14747
14748 @noindent
14749 (note that the compiler is invoked using the command
14750 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14751
14752 @noindent
14753 On non-VMS platforms, between @command{gnat} and the command, two
14754 special switches may be used:
14755
14756 @itemize @bullet
14757 @item
14758 @command{-v} to display the invocation of the tool.
14759 @item
14760 @command{-dn} to prevent the @command{gnat} driver from removing
14761 the temporary files it has created. These temporary files are
14762 configuration files and temporary file list files.
14763 @end itemize
14764
14765 @noindent
14766 The command may be followed by switches and arguments for the invoked
14767 tool.
14768
14769 @smallexample
14770   gnat bind -C main.ali
14771   gnat ls -a main
14772   gnat chop foo.txt
14773 @end smallexample
14774
14775 @noindent
14776 Switches may also be put in text files, one switch per line, and the text
14777 files may be specified with their path name preceded by '@@'.
14778
14779 @smallexample
14780    gnat bind @@args.txt main.ali
14781 @end smallexample
14782
14783 @noindent
14784 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14785 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14786 (@option{^-P^/PROJECT_FILE^},
14787 @option{^-X^/EXTERNAL_REFERENCE^} and
14788 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14789 the switches of the invoking tool.
14790
14791 @noindent
14792 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14793 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14794 the immediate sources of the specified project file.
14795
14796 @noindent
14797 When GNAT METRIC is used with a project file, but with no source
14798 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14799 with all the immediate sources of the specified project file and with
14800 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14801 of the project.
14802
14803 @noindent
14804 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14805 a project file, no source is specified on the command line and
14806 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14807 the underlying tool (^gnatpp^gnatpp^ or
14808 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14809 not only for the immediate sources of the main project.
14810 @ifclear vms
14811 (-U stands for Universal or Union of the project files of the project tree)
14812 @end ifclear
14813
14814 @noindent
14815 For each of the following commands, there is optionally a corresponding
14816 package in the main project.
14817
14818 @itemize @bullet
14819 @item
14820 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14821
14822 @item
14823 package @code{Check} for command CHECK (invoking
14824 @code{^gnatcheck^gnatcheck^})
14825
14826 @item
14827 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14828
14829 @item
14830 package @code{Cross_Reference} for command XREF (invoking
14831 @code{^gnatxref^gnatxref^})
14832
14833 @item
14834 package @code{Eliminate} for command ELIM (invoking
14835 @code{^gnatelim^gnatelim^})
14836
14837 @item
14838 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14839
14840 @item
14841 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14842
14843 @item
14844 package @code{Gnatstub} for command STUB
14845 (invoking @code{^gnatstub^gnatstub^})
14846
14847 @item
14848 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14849
14850 @item
14851 package @code{Metrics} for command METRIC
14852 (invoking @code{^gnatmetric^gnatmetric^})
14853
14854 @item
14855 package @code{Pretty_Printer} for command PP or PRETTY
14856 (invoking @code{^gnatpp^gnatpp^})
14857
14858 @end itemize
14859
14860 @noindent
14861 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14862 a simple variable with a string list value. It contains ^switches^switches^
14863 for the invocation of @code{^gnatls^gnatls^}.
14864
14865 @smallexample @c projectfile
14866 @group
14867 project Proj1 is
14868    package gnatls is
14869       for ^Switches^Switches^
14870           use ("^-a^-a^",
14871                "^-v^-v^");
14872    end gnatls;
14873 end Proj1;
14874 @end group
14875 @end smallexample
14876
14877 @noindent
14878 All other packages have two attribute @code{^Switches^Switches^} and
14879 @code{^Default_Switches^Default_Switches^}.
14880
14881 @noindent
14882 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14883 source file name, that has a string list value: the ^switches^switches^ to be
14884 used when the tool corresponding to the package is invoked for the specific
14885 source file.
14886
14887 @noindent
14888 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14889 indexed by  the programming language that has a string list value.
14890 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14891 ^switches^switches^ for the invocation of the tool corresponding
14892 to the package, except if a specific @code{^Switches^Switches^} attribute
14893 is specified for the source file.
14894
14895 @smallexample @c projectfile
14896 @group
14897 project Proj is
14898
14899    for Source_Dirs use ("./**");
14900
14901    package gnatls is
14902       for ^Switches^Switches^ use
14903           ("^-a^-a^",
14904            "^-v^-v^");
14905    end gnatls;
14906 @end group
14907 @group
14908
14909    package Compiler is
14910       for ^Default_Switches^Default_Switches^ ("Ada")
14911           use ("^-gnatv^-gnatv^",
14912                "^-gnatwa^-gnatwa^");
14913    end Binder;
14914 @end group
14915 @group
14916
14917    package Binder is
14918       for ^Default_Switches^Default_Switches^ ("Ada")
14919           use ("^-C^-C^",
14920                "^-e^-e^");
14921    end Binder;
14922 @end group
14923 @group
14924
14925    package Linker is
14926       for ^Default_Switches^Default_Switches^ ("Ada")
14927           use ("^-C^-C^");
14928       for ^Switches^Switches^ ("main.adb")
14929           use ("^-C^-C^",
14930                "^-v^-v^",
14931                "^-v^-v^");
14932    end Linker;
14933 @end group
14934 @group
14935
14936    package Finder is
14937       for ^Default_Switches^Default_Switches^ ("Ada")
14938            use ("^-a^-a^",
14939                 "^-f^-f^");
14940    end Finder;
14941 @end group
14942 @group
14943
14944    package Cross_Reference is
14945       for ^Default_Switches^Default_Switches^ ("Ada")
14946           use ("^-a^-a^",
14947                "^-f^-f^",
14948                "^-d^-d^",
14949                "^-u^-u^");
14950    end Cross_Reference;
14951 end Proj;
14952 @end group
14953 @end smallexample
14954
14955 @noindent
14956 With the above project file, commands such as
14957
14958 @smallexample
14959    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14960    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14961    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14962    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14963    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14964 @end smallexample
14965
14966 @noindent
14967 will set up the environment properly and invoke the tool with the switches
14968 found in the package corresponding to the tool:
14969 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14970 except @code{^Switches^Switches^ ("main.adb")}
14971 for @code{^gnatlink^gnatlink^}.
14972 It is also possible to invoke some of the tools,
14973 @code{^gnatcheck^gnatcheck^}),
14974 @code{^gnatmetric^gnatmetric^}),
14975 and @code{^gnatpp^gnatpp^})
14976 on a set of project units thanks to the combination of the switches
14977 @option{-P}, @option{-U} and possibly the main unit when one is interested
14978 in its closure. For instance,
14979 @smallexample
14980 gnat metric -Pproj
14981 @end smallexample
14982 will compute the metrics for all the immediate units of project
14983 @code{proj}.
14984 @smallexample
14985 gnat metric -Pproj -U
14986 @end smallexample
14987 will compute the metrics for all the units of the closure of projects
14988 rooted at @code{proj}.
14989 @smallexample
14990 gnat metric -Pproj -U main_unit
14991 @end smallexample
14992 will compute the metrics for the closure of units rooted at
14993 @code{main_unit}. This last possibility relies implicitly
14994 on @command{gnatbind}'s option @option{-R}.
14995
14996 @c **********************
14997 @node An Extended Example
14998 @section An Extended Example
14999
15000 @noindent
15001 Suppose that we have two programs, @var{prog1} and @var{prog2},
15002 whose sources are in corresponding directories. We would like
15003 to build them with a single @command{gnatmake} command, and we want to place
15004 their object files into @file{build} subdirectories of the source directories.
15005 Furthermore, we want to have to have two separate subdirectories
15006 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15007 the object files compiled with different set of compilation flags.
15008
15009 In other words, we have the following structure:
15010
15011 @smallexample
15012 @group
15013    main
15014      |- prog1
15015      |    |- build
15016      |         | debug
15017      |         | release
15018      |- prog2
15019           |- build
15020                | debug
15021                | release
15022 @end group
15023 @end smallexample
15024
15025 @noindent
15026 Here are the project files that we must place in a directory @file{main}
15027 to maintain this structure:
15028
15029 @enumerate
15030
15031 @item We create a @code{Common} project with a package @code{Compiler} that
15032 specifies the compilation ^switches^switches^:
15033
15034 @smallexample
15035 File "common.gpr":
15036 @group
15037 @b{project} Common @b{is}
15038
15039    @b{for} Source_Dirs @b{use} (); -- No source files
15040 @end group
15041
15042 @group
15043    @b{type} Build_Type @b{is} ("release", "debug");
15044    Build : Build_Type := External ("BUILD", "debug");
15045 @end group
15046 @group
15047    @b{package} Compiler @b{is}
15048       @b{case} Build @b{is}
15049          @b{when} "release" =>
15050            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15051                    @b{use} ("^-O2^-O2^");
15052          @b{when} "debug"   =>
15053            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15054                    @b{use} ("^-g^-g^");
15055       @b{end case};
15056    @b{end} Compiler;
15057
15058 @b{end} Common;
15059 @end group
15060 @end smallexample
15061
15062 @item We create separate projects for the two programs:
15063
15064 @smallexample
15065 @group
15066 File "prog1.gpr":
15067
15068 @b{with} "common";
15069 @b{project} Prog1 @b{is}
15070
15071     @b{for} Source_Dirs @b{use} ("prog1");
15072     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15073
15074     @b{package} Compiler @b{renames} Common.Compiler;
15075
15076 @b{end} Prog1;
15077 @end group
15078 @end smallexample
15079
15080 @smallexample
15081 @group
15082 File "prog2.gpr":
15083
15084 @b{with} "common";
15085 @b{project} Prog2 @b{is}
15086
15087     @b{for} Source_Dirs @b{use} ("prog2");
15088     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15089
15090     @b{package} Compiler @b{renames} Common.Compiler;
15091
15092 @end group
15093 @b{end} Prog2;
15094 @end smallexample
15095
15096 @item We create a wrapping project @code{Main}:
15097
15098 @smallexample
15099 @group
15100 File "main.gpr":
15101
15102 @b{with} "common";
15103 @b{with} "prog1";
15104 @b{with} "prog2";
15105 @b{project} Main @b{is}
15106
15107    @b{package} Compiler @b{renames} Common.Compiler;
15108
15109 @b{end} Main;
15110 @end group
15111 @end smallexample
15112
15113 @item Finally we need to create a dummy procedure that @code{with}s (either
15114 explicitly or implicitly) all the sources of our two programs.
15115
15116 @end enumerate
15117
15118 @noindent
15119 Now we can build the programs using the command
15120
15121 @smallexample
15122    gnatmake ^-P^/PROJECT_FILE=^main dummy
15123 @end smallexample
15124
15125 @noindent
15126 for the Debug mode, or
15127
15128 @ifclear vms
15129 @smallexample
15130    gnatmake -Pmain -XBUILD=release
15131 @end smallexample
15132 @end ifclear
15133
15134 @ifset vms
15135 @smallexample
15136    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15137 @end smallexample
15138 @end ifset
15139
15140 @noindent
15141 for the Release mode.
15142
15143 @c ********************************
15144 @c * Project File Complete Syntax *
15145 @c ********************************
15146
15147 @node Project File Complete Syntax
15148 @section Project File Complete Syntax
15149
15150 @smallexample
15151 project ::=
15152   context_clause project_declaration
15153
15154 context_clause ::=
15155   @{with_clause@}
15156
15157 with_clause ::=
15158   @b{with} path_name @{ , path_name @} ;
15159
15160 path_name ::=
15161    string_literal
15162
15163 project_declaration ::=
15164   simple_project_declaration | project_extension
15165
15166 simple_project_declaration ::=
15167   @b{project} <project_>simple_name @b{is}
15168     @{declarative_item@}
15169   @b{end} <project_>simple_name;
15170
15171 project_extension ::=
15172   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15173     @{declarative_item@}
15174   @b{end} <project_>simple_name;
15175
15176 declarative_item ::=
15177   package_declaration |
15178   typed_string_declaration |
15179   other_declarative_item
15180
15181 package_declaration ::=
15182   package_spec | package_renaming
15183
15184 package_spec ::=
15185   @b{package} package_identifier @b{is}
15186     @{simple_declarative_item@}
15187   @b{end} package_identifier ;
15188
15189 package_identifier ::=
15190   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15191   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15192   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15193
15194 package_renaming ::==
15195   @b{package} package_identifier @b{renames}
15196        <project_>simple_name.package_identifier ;
15197
15198 typed_string_declaration ::=
15199   @b{type} <typed_string_>_simple_name @b{is}
15200    ( string_literal @{, string_literal@} );
15201
15202 other_declarative_item ::=
15203   attribute_declaration |
15204   typed_variable_declaration |
15205   variable_declaration |
15206   case_construction
15207
15208 attribute_declaration ::=
15209   full_associative_array_declaration |
15210   @b{for} attribute_designator @b{use} expression ;
15211
15212 full_associative_array_declaration ::=
15213   @b{for} <associative_array_attribute_>simple_name @b{use}
15214   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15215
15216 attribute_designator ::=
15217   <simple_attribute_>simple_name |
15218   <associative_array_attribute_>simple_name ( string_literal )
15219
15220 typed_variable_declaration ::=
15221   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15222
15223 variable_declaration ::=
15224   <variable_>simple_name := expression;
15225
15226 expression ::=
15227   term @{& term@}
15228
15229 term ::=
15230   literal_string |
15231   string_list |
15232   <variable_>name |
15233   external_value |
15234   attribute_reference
15235
15236 string_literal ::=
15237   (same as Ada)
15238
15239 string_list ::=
15240   ( <string_>expression @{ , <string_>expression @} )
15241
15242 external_value ::=
15243   @b{external} ( string_literal [, string_literal] )
15244
15245 attribute_reference ::=
15246   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15247
15248 attribute_prefix ::=
15249   @b{project} |
15250   <project_>simple_name | package_identifier |
15251   <project_>simple_name . package_identifier
15252
15253 case_construction ::=
15254   @b{case} <typed_variable_>name @b{is}
15255     @{case_item@}
15256   @b{end case} ;
15257
15258 case_item ::=
15259   @b{when} discrete_choice_list =>
15260       @{case_construction | attribute_declaration@}
15261
15262 discrete_choice_list ::=
15263   string_literal @{| string_literal@} |
15264   @b{others}
15265
15266 name ::=
15267   simple_name @{. simple_name@}
15268
15269 simple_name ::=
15270   identifier (same as Ada)
15271
15272 @end smallexample
15273
15274 @node The Cross-Referencing Tools gnatxref and gnatfind
15275 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15276 @findex gnatxref
15277 @findex gnatfind
15278
15279 @noindent
15280 The compiler generates cross-referencing information (unless
15281 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15282 This information indicates where in the source each entity is declared and
15283 referenced. Note that entities in package Standard are not included, but
15284 entities in all other predefined units are included in the output.
15285
15286 Before using any of these two tools, you need to compile successfully your
15287 application, so that GNAT gets a chance to generate the cross-referencing
15288 information.
15289
15290 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15291 information to provide the user with the capability to easily locate the
15292 declaration and references to an entity. These tools are quite similar,
15293 the difference being that @code{gnatfind} is intended for locating
15294 definitions and/or references to a specified entity or entities, whereas
15295 @code{gnatxref} is oriented to generating a full report of all
15296 cross-references.
15297
15298 To use these tools, you must not compile your application using the
15299 @option{-gnatx} switch on the @command{gnatmake} command line
15300 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15301 information will not be generated.
15302
15303 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15304 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15305
15306 @menu
15307 * gnatxref Switches::
15308 * gnatfind Switches::
15309 * Project Files for gnatxref and gnatfind::
15310 * Regular Expressions in gnatfind and gnatxref::
15311 * Examples of gnatxref Usage::
15312 * Examples of gnatfind Usage::
15313 @end menu
15314
15315 @node gnatxref Switches
15316 @section @code{gnatxref} Switches
15317
15318 @noindent
15319 The command invocation for @code{gnatxref} is:
15320 @smallexample
15321 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15322 @end smallexample
15323
15324 @noindent
15325 where
15326
15327 @table @var
15328 @item sourcefile1
15329 @itemx sourcefile2
15330 identifies the source files for which a report is to be generated. The
15331 ``with''ed units will be processed too. You must provide at least one file.
15332
15333 These file names are considered to be regular expressions, so for instance
15334 specifying @file{source*.adb} is the same as giving every file in the current
15335 directory whose name starts with @file{source} and whose extension is
15336 @file{adb}.
15337
15338 You shouldn't specify any directory name, just base names. @command{gnatxref}
15339 and @command{gnatfind} will be able to locate these files by themselves using
15340 the source path. If you specify directories, no result is produced.
15341
15342 @end table
15343
15344 @noindent
15345 The switches can be:
15346 @table @option
15347 @c !sort!
15348 @item --version
15349 @cindex @option{--version} @command{gnatxref}
15350 Display Copyright and version, then exit disregarding all other options.
15351
15352 @item --help
15353 @cindex @option{--help} @command{gnatxref}
15354 If @option{--version} was not used, display usage, then exit disregarding
15355 all other options.
15356
15357 @item ^-a^/ALL_FILES^
15358 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15359 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15360 the read-only files found in the library search path. Otherwise, these files
15361 will be ignored. This option can be used to protect Gnat sources or your own
15362 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15363 much faster, and their output much smaller. Read-only here refers to access
15364 or permissions status in the file system for the current user.
15365
15366 @item -aIDIR
15367 @cindex @option{-aIDIR} (@command{gnatxref})
15368 When looking for source files also look in directory DIR. The order in which
15369 source file search is undertaken is the same as for @command{gnatmake}.
15370
15371 @item -aODIR
15372 @cindex @option{-aODIR} (@command{gnatxref})
15373 When searching for library and object files, look in directory
15374 DIR. The order in which library files are searched is the same as for
15375 @command{gnatmake}.
15376
15377 @item -nostdinc
15378 @cindex @option{-nostdinc} (@command{gnatxref})
15379 Do not look for sources in the system default directory.
15380
15381 @item -nostdlib
15382 @cindex @option{-nostdlib} (@command{gnatxref})
15383 Do not look for library files in the system default directory.
15384
15385 @item --RTS=@var{rts-path}
15386 @cindex @option{--RTS} (@command{gnatxref})
15387 Specifies the default location of the runtime library. Same meaning as the
15388 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15389
15390 @item ^-d^/DERIVED_TYPES^
15391 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15392 If this switch is set @code{gnatxref} will output the parent type
15393 reference for each matching derived types.
15394
15395 @item ^-f^/FULL_PATHNAME^
15396 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15397 If this switch is set, the output file names will be preceded by their
15398 directory (if the file was found in the search path). If this switch is
15399 not set, the directory will not be printed.
15400
15401 @item ^-g^/IGNORE_LOCALS^
15402 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15403 If this switch is set, information is output only for library-level
15404 entities, ignoring local entities. The use of this switch may accelerate
15405 @code{gnatfind} and @code{gnatxref}.
15406
15407 @item -IDIR
15408 @cindex @option{-IDIR} (@command{gnatxref})
15409 Equivalent to @samp{-aODIR -aIDIR}.
15410
15411 @item -pFILE
15412 @cindex @option{-pFILE} (@command{gnatxref})
15413 Specify a project file to use @xref{Project Files}.
15414 If you need to use the @file{.gpr}
15415 project files, you should use gnatxref through the GNAT driver
15416 (@command{gnat xref -Pproject}).
15417
15418 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15419 project file in the current directory.
15420
15421 If a project file is either specified or found by the tools, then the content
15422 of the source directory and object directory lines are added as if they
15423 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15424 and @samp{^-aO^OBJECT_SEARCH^}.
15425 @item ^-u^/UNUSED^
15426 Output only unused symbols. This may be really useful if you give your
15427 main compilation unit on the command line, as @code{gnatxref} will then
15428 display every unused entity and 'with'ed package.
15429
15430 @ifclear vms
15431 @item -v
15432 Instead of producing the default output, @code{gnatxref} will generate a
15433 @file{tags} file that can be used by vi. For examples how to use this
15434 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15435 to the standard output, thus you will have to redirect it to a file.
15436 @end ifclear
15437
15438 @end table
15439
15440 @noindent
15441 All these switches may be in any order on the command line, and may even
15442 appear after the file names. They need not be separated by spaces, thus
15443 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15444 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15445
15446 @node gnatfind Switches
15447 @section @code{gnatfind} Switches
15448
15449 @noindent
15450 The command line for @code{gnatfind} is:
15451
15452 @smallexample
15453 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15454       @r{[}@var{file1} @var{file2} @dots{}]
15455 @end smallexample
15456
15457 @noindent
15458 where
15459
15460 @table @var
15461 @item pattern
15462 An entity will be output only if it matches the regular expression found
15463 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15464
15465 Omitting the pattern is equivalent to specifying @samp{*}, which
15466 will match any entity. Note that if you do not provide a pattern, you
15467 have to provide both a sourcefile and a line.
15468
15469 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15470 for matching purposes. At the current time there is no support for
15471 8-bit codes other than Latin-1, or for wide characters in identifiers.
15472
15473 @item sourcefile
15474 @code{gnatfind} will look for references, bodies or declarations
15475 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15476 and column @var{column}. See @ref{Examples of gnatfind Usage}
15477 for syntax examples.
15478
15479 @item line
15480 is a decimal integer identifying the line number containing
15481 the reference to the entity (or entities) to be located.
15482
15483 @item column
15484 is a decimal integer identifying the exact location on the
15485 line of the first character of the identifier for the
15486 entity reference. Columns are numbered from 1.
15487
15488 @item file1 file2 @dots{}
15489 The search will be restricted to these source files. If none are given, then
15490 the search will be done for every library file in the search path.
15491 These file must appear only after the pattern or sourcefile.
15492
15493 These file names are considered to be regular expressions, so for instance
15494 specifying @file{source*.adb} is the same as giving every file in the current
15495 directory whose name starts with @file{source} and whose extension is
15496 @file{adb}.
15497
15498 The location of the spec of the entity will always be displayed, even if it
15499 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15500 occurrences of the entity in the separate units of the ones given on the
15501 command line will also be displayed.
15502
15503 Note that if you specify at least one file in this part, @code{gnatfind} may
15504 sometimes not be able to find the body of the subprograms.
15505
15506 @end table
15507
15508 @noindent
15509 At least one of 'sourcefile' or 'pattern' has to be present on
15510 the command line.
15511
15512 The following switches are available:
15513 @table @option
15514 @c !sort!
15515
15516 @cindex @option{--version} @command{gnatfind}
15517 Display Copyright and version, then exit disregarding all other options.
15518
15519 @item --help
15520 @cindex @option{--help} @command{gnatfind}
15521 If @option{--version} was not used, display usage, then exit disregarding
15522 all other options.
15523
15524 @item ^-a^/ALL_FILES^
15525 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15526 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15527 the read-only files found in the library search path. Otherwise, these files
15528 will be ignored. This option can be used to protect Gnat sources or your own
15529 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15530 much faster, and their output much smaller. Read-only here refers to access
15531 or permission status in the file system for the current user.
15532
15533 @item -aIDIR
15534 @cindex @option{-aIDIR} (@command{gnatfind})
15535 When looking for source files also look in directory DIR. The order in which
15536 source file search is undertaken is the same as for @command{gnatmake}.
15537
15538 @item -aODIR
15539 @cindex @option{-aODIR} (@command{gnatfind})
15540 When searching for library and object files, look in directory
15541 DIR. The order in which library files are searched is the same as for
15542 @command{gnatmake}.
15543
15544 @item -nostdinc
15545 @cindex @option{-nostdinc} (@command{gnatfind})
15546 Do not look for sources in the system default directory.
15547
15548 @item -nostdlib
15549 @cindex @option{-nostdlib} (@command{gnatfind})
15550 Do not look for library files in the system default directory.
15551
15552 @item --RTS=@var{rts-path}
15553 @cindex @option{--RTS} (@command{gnatfind})
15554 Specifies the default location of the runtime library. Same meaning as the
15555 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15556
15557 @item ^-d^/DERIVED_TYPE_INFORMATION^
15558 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15559 If this switch is set, then @code{gnatfind} will output the parent type
15560 reference for each matching derived types.
15561
15562 @item ^-e^/EXPRESSIONS^
15563 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15564 By default, @code{gnatfind} accept the simple regular expression set for
15565 @samp{pattern}. If this switch is set, then the pattern will be
15566 considered as full Unix-style regular expression.
15567
15568 @item ^-f^/FULL_PATHNAME^
15569 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15570 If this switch is set, the output file names will be preceded by their
15571 directory (if the file was found in the search path). If this switch is
15572 not set, the directory will not be printed.
15573
15574 @item ^-g^/IGNORE_LOCALS^
15575 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15576 If this switch is set, information is output only for library-level
15577 entities, ignoring local entities. The use of this switch may accelerate
15578 @code{gnatfind} and @code{gnatxref}.
15579
15580 @item -IDIR
15581 @cindex @option{-IDIR} (@command{gnatfind})
15582 Equivalent to @samp{-aODIR -aIDIR}.
15583
15584 @item -pFILE
15585 @cindex @option{-pFILE} (@command{gnatfind})
15586 Specify a project file (@pxref{Project Files}) to use.
15587 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15588 project file in the current directory.
15589
15590 If a project file is either specified or found by the tools, then the content
15591 of the source directory and object directory lines are added as if they
15592 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15593 @samp{^-aO^/OBJECT_SEARCH^}.
15594
15595 @item ^-r^/REFERENCES^
15596 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15597 By default, @code{gnatfind} will output only the information about the
15598 declaration, body or type completion of the entities. If this switch is
15599 set, the @code{gnatfind} will locate every reference to the entities in
15600 the files specified on the command line (or in every file in the search
15601 path if no file is given on the command line).
15602
15603 @item ^-s^/PRINT_LINES^
15604 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15605 If this switch is set, then @code{gnatfind} will output the content
15606 of the Ada source file lines were the entity was found.
15607
15608 @item ^-t^/TYPE_HIERARCHY^
15609 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15610 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15611 the specified type. It act like -d option but recursively from parent
15612 type to parent type. When this switch is set it is not possible to
15613 specify more than one file.
15614
15615 @end table
15616
15617 @noindent
15618 All these switches may be in any order on the command line, and may even
15619 appear after the file names. They need not be separated by spaces, thus
15620 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15621 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15622
15623 As stated previously, gnatfind will search in every directory in the
15624 search path. You can force it to look only in the current directory if
15625 you specify @code{*} at the end of the command line.
15626
15627 @node Project Files for gnatxref and gnatfind
15628 @section Project Files for @command{gnatxref} and @command{gnatfind}
15629
15630 @noindent
15631 Project files allow a programmer to specify how to compile its
15632 application, where to find sources, etc.  These files are used
15633 @ifclear vms
15634 primarily by GPS, but they can also be used
15635 @end ifclear
15636 by the two tools
15637 @code{gnatxref} and @code{gnatfind}.
15638
15639 A project file name must end with @file{.gpr}. If a single one is
15640 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15641 extract the information from it. If multiple project files are found, none of
15642 them is read, and you have to use the @samp{-p} switch to specify the one
15643 you want to use.
15644
15645 The following lines can be included, even though most of them have default
15646 values which can be used in most cases.
15647 The lines can be entered in any order in the file.
15648 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15649 each line. If you have multiple instances, only the last one is taken into
15650 account.
15651
15652 @table @code
15653 @item src_dir=DIR
15654 [default: @code{"^./^[]^"}]
15655 specifies a directory where to look for source files. Multiple @code{src_dir}
15656 lines can be specified and they will be searched in the order they
15657 are specified.
15658
15659 @item obj_dir=DIR
15660 [default: @code{"^./^[]^"}]
15661 specifies a directory where to look for object and library files. Multiple
15662 @code{obj_dir} lines can be specified, and they will be searched in the order
15663 they are specified
15664
15665 @item comp_opt=SWITCHES
15666 [default: @code{""}]
15667 creates a variable which can be referred to subsequently by using
15668 the @code{$@{comp_opt@}} notation. This is intended to store the default
15669 switches given to @command{gnatmake} and @command{gcc}.
15670
15671 @item bind_opt=SWITCHES
15672 [default: @code{""}]
15673 creates a variable which can be referred to subsequently by using
15674 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15675 switches given to @command{gnatbind}.
15676
15677 @item link_opt=SWITCHES
15678 [default: @code{""}]
15679 creates a variable which can be referred to subsequently by using
15680 the @samp{$@{link_opt@}} notation. This is intended to store the default
15681 switches given to @command{gnatlink}.
15682
15683 @item main=EXECUTABLE
15684 [default: @code{""}]
15685 specifies the name of the executable for the application. This variable can
15686 be referred to in the following lines by using the @samp{$@{main@}} notation.
15687
15688 @ifset vms
15689 @item comp_cmd=COMMAND
15690 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15691 @end ifset
15692 @ifclear vms
15693 @item comp_cmd=COMMAND
15694 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15695 @end ifclear
15696 specifies the command used to compile a single file in the application.
15697
15698 @ifset vms
15699 @item make_cmd=COMMAND
15700 [default: @code{"GNAT MAKE $@{main@}
15701 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15702 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15703 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15704 @end ifset
15705 @ifclear vms
15706 @item make_cmd=COMMAND
15707 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15708 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15709 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15710 @end ifclear
15711 specifies the command used to recompile the whole application.
15712
15713 @item run_cmd=COMMAND
15714 [default: @code{"$@{main@}"}]
15715 specifies the command used to run the application.
15716
15717 @item debug_cmd=COMMAND
15718 [default: @code{"gdb $@{main@}"}]
15719 specifies the command used to debug the application
15720
15721 @end table
15722
15723 @noindent
15724 @command{gnatxref} and @command{gnatfind} only take into account the
15725 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15726
15727 @node Regular Expressions in gnatfind and gnatxref
15728 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15729
15730 @noindent
15731 As specified in the section about @command{gnatfind}, the pattern can be a
15732 regular expression. Actually, there are to set of regular expressions
15733 which are recognized by the program:
15734
15735 @table @code
15736 @item globbing patterns
15737 These are the most usual regular expression. They are the same that you
15738 generally used in a Unix shell command line, or in a DOS session.
15739
15740 Here is a more formal grammar:
15741 @smallexample
15742 @group
15743 @iftex
15744 @leftskip=.5cm
15745 @end iftex
15746 regexp ::= term
15747 term   ::= elmt            -- matches elmt
15748 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15749 term   ::= *               -- any string of 0 or more characters
15750 term   ::= ?               -- matches any character
15751 term   ::= [char @{char@}]   -- matches any character listed
15752 term   ::= [char - char]   -- matches any character in range
15753 @end group
15754 @end smallexample
15755
15756 @item full regular expression
15757 The second set of regular expressions is much more powerful. This is the
15758 type of regular expressions recognized by utilities such a @file{grep}.
15759
15760 The following is the form of a regular expression, expressed in Ada
15761 reference manual style BNF is as follows
15762
15763 @smallexample
15764 @iftex
15765 @leftskip=.5cm
15766 @end iftex
15767 @group
15768 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15769
15770 term ::= item @{item@}       -- concatenation (item then item)
15771
15772 item ::= elmt              -- match elmt
15773 item ::= elmt *            -- zero or more elmt's
15774 item ::= elmt +            -- one or more elmt's
15775 item ::= elmt ?            -- matches elmt or nothing
15776 @end group
15777 @group
15778 elmt ::= nschar            -- matches given character
15779 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15780 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15781 elmt ::= [char - char]     -- matches chars in given range
15782 elmt ::= \ char            -- matches given character
15783 elmt ::= .                 -- matches any single character
15784 elmt ::= ( regexp )        -- parens used for grouping
15785
15786 char ::= any character, including special characters
15787 nschar ::= any character except ()[].*+?^^^
15788 @end group
15789 @end smallexample
15790
15791 Following are a few examples:
15792
15793 @table @samp
15794 @item abcde|fghi
15795 will match any of the two strings @samp{abcde} and @samp{fghi},
15796
15797 @item abc*d
15798 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15799 @samp{abcccd}, and so on,
15800
15801 @item [a-z]+
15802 will match any string which has only lowercase characters in it (and at
15803 least one character.
15804
15805 @end table
15806 @end table
15807
15808 @node Examples of gnatxref Usage
15809 @section Examples of @code{gnatxref} Usage
15810
15811 @subsection General Usage
15812
15813 @noindent
15814 For the following examples, we will consider the following units:
15815
15816 @smallexample @c ada
15817 @group
15818 @cartouche
15819 main.ads:
15820 1: with Bar;
15821 2: package Main is
15822 3:     procedure Foo (B : in Integer);
15823 4:     C : Integer;
15824 5: private
15825 6:     D : Integer;
15826 7: end Main;
15827
15828 main.adb:
15829 1: package body Main is
15830 2:     procedure Foo (B : in Integer) is
15831 3:     begin
15832 4:        C := B;
15833 5:        D := B;
15834 6:        Bar.Print (B);
15835 7:        Bar.Print (C);
15836 8:     end Foo;
15837 9: end Main;
15838
15839 bar.ads:
15840 1: package Bar is
15841 2:     procedure Print (B : Integer);
15842 3: end bar;
15843 @end cartouche
15844 @end group
15845 @end smallexample
15846
15847 @table @code
15848
15849 @noindent
15850 The first thing to do is to recompile your application (for instance, in
15851 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15852 the cross-referencing information.
15853 You can then issue any of the following commands:
15854
15855 @item gnatxref main.adb
15856 @code{gnatxref} generates cross-reference information for main.adb
15857 and every unit 'with'ed by main.adb.
15858
15859 The output would be:
15860 @smallexample
15861 @iftex
15862 @leftskip=0cm
15863 @end iftex
15864 B                                                      Type: Integer
15865   Decl: bar.ads           2:22
15866 B                                                      Type: Integer
15867   Decl: main.ads          3:20
15868   Body: main.adb          2:20
15869   Ref:  main.adb          4:13     5:13     6:19
15870 Bar                                                    Type: Unit
15871   Decl: bar.ads           1:9
15872   Ref:  main.adb          6:8      7:8
15873        main.ads           1:6
15874 C                                                      Type: Integer
15875   Decl: main.ads          4:5
15876   Modi: main.adb          4:8
15877   Ref:  main.adb          7:19
15878 D                                                      Type: Integer
15879   Decl: main.ads          6:5
15880   Modi: main.adb          5:8
15881 Foo                                                    Type: Unit
15882   Decl: main.ads          3:15
15883   Body: main.adb          2:15
15884 Main                                                    Type: Unit
15885   Decl: main.ads          2:9
15886   Body: main.adb          1:14
15887 Print                                                   Type: Unit
15888   Decl: bar.ads           2:15
15889   Ref:  main.adb          6:12     7:12
15890 @end smallexample
15891
15892 @noindent
15893 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15894 its body is in main.adb, line 1, column 14 and is not referenced any where.
15895
15896 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15897 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15898
15899 @item gnatxref package1.adb package2.ads
15900 @code{gnatxref} will generates cross-reference information for
15901 package1.adb, package2.ads and any other package 'with'ed by any
15902 of these.
15903
15904 @end table
15905
15906 @ifclear vms
15907 @subsection Using gnatxref with vi
15908
15909 @code{gnatxref} can generate a tags file output, which can be used
15910 directly from @command{vi}. Note that the standard version of @command{vi}
15911 will not work properly with overloaded symbols. Consider using another
15912 free implementation of @command{vi}, such as @command{vim}.
15913
15914 @smallexample
15915 $ gnatxref -v gnatfind.adb > tags
15916 @end smallexample
15917
15918 @noindent
15919 will generate the tags file for @code{gnatfind} itself (if the sources
15920 are in the search path!).
15921
15922 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15923 (replacing @var{entity} by whatever you are looking for), and vi will
15924 display a new file with the corresponding declaration of entity.
15925 @end ifclear
15926
15927 @node Examples of gnatfind Usage
15928 @section Examples of @code{gnatfind} Usage
15929
15930 @table @code
15931
15932 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15933 Find declarations for all entities xyz referenced at least once in
15934 main.adb. The references are search in every library file in the search
15935 path.
15936
15937 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15938 switch is set)
15939
15940 The output will look like:
15941 @smallexample
15942 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15943 ^directory/^[directory]^main.adb:24:10: xyz <= body
15944 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15945 @end smallexample
15946
15947 @noindent
15948 that is to say, one of the entities xyz found in main.adb is declared at
15949 line 12 of main.ads (and its body is in main.adb), and another one is
15950 declared at line 45 of foo.ads
15951
15952 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15953 This is the same command as the previous one, instead @code{gnatfind} will
15954 display the content of the Ada source file lines.
15955
15956 The output will look like:
15957
15958 @smallexample
15959 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15960    procedure xyz;
15961 ^directory/^[directory]^main.adb:24:10: xyz <= body
15962    procedure xyz is
15963 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15964    xyz : Integer;
15965 @end smallexample
15966
15967 @noindent
15968 This can make it easier to find exactly the location your are looking
15969 for.
15970
15971 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15972 Find references to all entities containing an x that are
15973 referenced on line 123 of main.ads.
15974 The references will be searched only in main.ads and foo.adb.
15975
15976 @item gnatfind main.ads:123
15977 Find declarations and bodies for all entities that are referenced on
15978 line 123 of main.ads.
15979
15980 This is the same as @code{gnatfind "*":main.adb:123}.
15981
15982 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15983 Find the declaration for the entity referenced at column 45 in
15984 line 123 of file main.adb in directory mydir. Note that it
15985 is usual to omit the identifier name when the column is given,
15986 since the column position identifies a unique reference.
15987
15988 The column has to be the beginning of the identifier, and should not
15989 point to any character in the middle of the identifier.
15990
15991 @end table
15992
15993 @c *********************************
15994 @node The GNAT Pretty-Printer gnatpp
15995 @chapter The GNAT Pretty-Printer @command{gnatpp}
15996 @findex gnatpp
15997 @cindex Pretty-Printer
15998
15999 @noindent
16000 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16001 for source reformatting / pretty-printing.
16002 It takes an Ada source file as input and generates a reformatted
16003 version as output.
16004 You can specify various style directives via switches; e.g.,
16005 identifier case conventions, rules of indentation, and comment layout.
16006
16007 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16008 tree for the input source and thus requires the input to be syntactically and
16009 semantically legal.
16010 If this condition is not met, @command{gnatpp} will terminate with an
16011 error message; no output file will be generated.
16012
16013 If the source files presented to @command{gnatpp} contain
16014 preprocessing directives, then the output file will
16015 correspond to the generated source after all
16016 preprocessing is carried out. There is no way
16017 using @command{gnatpp} to obtain pretty printed files that
16018 include the preprocessing directives.
16019
16020 If the compilation unit
16021 contained in the input source depends semantically upon units located
16022 outside the current directory, you have to provide the source search path
16023 when invoking @command{gnatpp}, if these units are contained in files with
16024 names that do not follow the GNAT file naming rules, you have to provide
16025 the configuration file describing the corresponding naming scheme;
16026 see the description of the @command{gnatpp}
16027 switches below. Another possibility is to use a project file and to
16028 call @command{gnatpp} through the @command{gnat} driver
16029
16030 The @command{gnatpp} command has the form
16031
16032 @smallexample
16033 $ gnatpp @ovar{switches} @var{filename}
16034 @end smallexample
16035
16036 @noindent
16037 where
16038 @itemize @bullet
16039 @item
16040 @var{switches} is an optional sequence of switches defining such properties as
16041 the formatting rules, the source search path, and the destination for the
16042 output source file
16043
16044 @item
16045 @var{filename} is the name (including the extension) of the source file to
16046 reformat; ``wildcards'' or several file names on the same gnatpp command are
16047 allowed.  The file name may contain path information; it does not have to
16048 follow the GNAT file naming rules
16049 @end itemize
16050
16051 @menu
16052 * Switches for gnatpp::
16053 * Formatting Rules::
16054 @end menu
16055
16056 @node Switches for gnatpp
16057 @section Switches for @command{gnatpp}
16058
16059 @noindent
16060 The following subsections describe the various switches accepted by
16061 @command{gnatpp}, organized by category.
16062
16063 @ifclear vms
16064 You specify a switch by supplying a name and generally also a value.
16065 In many cases the values for a switch with a given name are incompatible with
16066 each other
16067 (for example the switch that controls the casing of a reserved word may have
16068 exactly one value: upper case, lower case, or
16069 mixed case) and thus exactly one such switch can be in effect for an
16070 invocation of @command{gnatpp}.
16071 If more than one is supplied, the last one is used.
16072 However, some values for the same switch are mutually compatible.
16073 You may supply several such switches to @command{gnatpp}, but then
16074 each must be specified in full, with both the name and the value.
16075 Abbreviated forms (the name appearing once, followed by each value) are
16076 not permitted.
16077 For example, to set
16078 the alignment of the assignment delimiter both in declarations and in
16079 assignment statements, you must write @option{-A2A3}
16080 (or @option{-A2 -A3}), but not @option{-A23}.
16081 @end ifclear
16082
16083 @ifset vms
16084 In many cases the set of options for a given qualifier are incompatible with
16085 each other (for example the qualifier that controls the casing of a reserved
16086 word may have exactly one option, which specifies either upper case, lower
16087 case, or mixed case), and thus exactly one such option can be in effect for
16088 an invocation of @command{gnatpp}.
16089 If more than one is supplied, the last one is used.
16090 However, some qualifiers have options that are mutually compatible,
16091 and then you may then supply several such options when invoking
16092 @command{gnatpp}.
16093 @end ifset
16094
16095 In most cases, it is obvious whether or not the
16096 ^values for a switch with a given name^options for a given qualifier^
16097 are compatible with each other.
16098 When the semantics might not be evident, the summaries below explicitly
16099 indicate the effect.
16100
16101 @menu
16102 * Alignment Control::
16103 * Casing Control::
16104 * Construct Layout Control::
16105 * General Text Layout Control::
16106 * Other Formatting Options::
16107 * Setting the Source Search Path::
16108 * Output File Control::
16109 * Other gnatpp Switches::
16110 @end menu
16111
16112 @node Alignment Control
16113 @subsection Alignment Control
16114 @cindex Alignment control in @command{gnatpp}
16115
16116 @noindent
16117 Programs can be easier to read if certain constructs are vertically aligned.
16118 By default all alignments are set ON.
16119 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16120 OFF, and then use one or more of the other
16121 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16122 to activate alignment for specific constructs.
16123
16124 @table @option
16125 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16126
16127 @ifset vms
16128 @item /ALIGN=ON
16129 Set all alignments to ON
16130 @end ifset
16131
16132 @item ^-A0^/ALIGN=OFF^
16133 Set all alignments to OFF
16134
16135 @item ^-A1^/ALIGN=COLONS^
16136 Align @code{:} in declarations
16137
16138 @item ^-A2^/ALIGN=DECLARATIONS^
16139 Align @code{:=} in initializations in declarations
16140
16141 @item ^-A3^/ALIGN=STATEMENTS^
16142 Align @code{:=} in assignment statements
16143
16144 @item ^-A4^/ALIGN=ARROWS^
16145 Align @code{=>} in associations
16146
16147 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16148 Align @code{at} keywords in the component clauses in record
16149 representation clauses
16150 @end table
16151
16152 @noindent
16153 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16154 is allowed.
16155
16156 @node Casing Control
16157 @subsection Casing Control
16158 @cindex Casing control in @command{gnatpp}
16159
16160 @noindent
16161 @command{gnatpp} allows you to specify the casing for reserved words,
16162 pragma names, attribute designators and identifiers.
16163 For identifiers you may define a
16164 general rule for name casing but also override this rule
16165 via a set of dictionary files.
16166
16167 Three types of casing are supported: lower case, upper case, and mixed case.
16168 Lower and upper case are self-explanatory (but since some letters in
16169 Latin1 and other GNAT-supported character sets
16170 exist only in lower-case form, an upper case conversion will have no
16171 effect on them.)
16172 ``Mixed case'' means that the first letter, and also each letter immediately
16173 following an underscore, are converted to their uppercase forms;
16174 all the other letters are converted to their lowercase forms.
16175
16176 @table @option
16177 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16178 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16179 Attribute designators are lower case
16180
16181 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16182 Attribute designators are upper case
16183
16184 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16185 Attribute designators are mixed case (this is the default)
16186
16187 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16188 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16189 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16190 lower case (this is the default)
16191
16192 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16193 Keywords are upper case
16194
16195 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16196 @item ^-nD^/NAME_CASING=AS_DECLARED^
16197 Name casing for defining occurrences are as they appear in the source file
16198 (this is the default)
16199
16200 @item ^-nU^/NAME_CASING=UPPER_CASE^
16201 Names are in upper case
16202
16203 @item ^-nL^/NAME_CASING=LOWER_CASE^
16204 Names are in lower case
16205
16206 @item ^-nM^/NAME_CASING=MIXED_CASE^
16207 Names are in mixed case
16208
16209 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16210 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16211 Pragma names are lower case
16212
16213 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16214 Pragma names are upper case
16215
16216 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16217 Pragma names are mixed case (this is the default)
16218
16219 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16220 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16221 Use @var{file} as a @emph{dictionary file} that defines
16222 the casing for a set of specified names,
16223 thereby overriding the effect on these names by
16224 any explicit or implicit
16225 ^-n^/NAME_CASING^ switch.
16226 To supply more than one dictionary file,
16227 use ^several @option{-D} switches^a list of files as options^.
16228
16229 @noindent
16230 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16231 to define the casing for the Ada predefined names and
16232 the names declared in the GNAT libraries.
16233
16234 @item ^-D-^/SPECIFIC_CASING^
16235 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16236 Do not use the default dictionary file;
16237 instead, use the casing
16238 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16239 dictionary file(s)
16240 @end table
16241
16242 @noindent
16243 The structure of a dictionary file, and details on the conventions
16244 used in the default dictionary file, are defined in @ref{Name Casing}.
16245
16246 The @option{^-D-^/SPECIFIC_CASING^} and
16247 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16248 compatible.
16249
16250 @node Construct Layout Control
16251 @subsection Construct Layout Control
16252 @cindex Layout control in @command{gnatpp}
16253
16254 @noindent
16255 This group of @command{gnatpp} switches controls the layout of comments and
16256 complex syntactic constructs.  See @ref{Formatting Comments} for details
16257 on their effect.
16258
16259 @table @option
16260 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16261 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16262 All the comments remain unchanged
16263
16264 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16265 GNAT-style comment line indentation (this is the default).
16266
16267 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16268 Reference-manual comment line indentation.
16269
16270 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16271 GNAT-style comment beginning
16272
16273 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16274 Reformat comment blocks
16275
16276 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16277 Keep unchanged special form comments
16278
16279 Reformat comment blocks
16280
16281 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16282 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16283 GNAT-style layout (this is the default)
16284
16285 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16286 Compact layout
16287
16288 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16289 Uncompact layout
16290
16291 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16292 @item ^-N^/NOTABS^
16293 All the VT characters are removed from the comment text. All the HT characters
16294 are expanded with the sequences of space characters to get to the next tab
16295 stops.
16296
16297 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16298 @item ^--no-separate-is^/NO_SEPARATE_IS^
16299 Do not place the keyword @code{is} on a separate line in a subprogram body in
16300 case if the spec occupies more then one line.
16301
16302 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16303 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16304 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16305 keyword @code{then} in IF statements on a separate line.
16306
16307 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16308 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16309 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16310 keyword @code{then} in IF statements on a separate line. This option is
16311 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16312
16313 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16314 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16315 Start each USE clause in a context clause from a separate line.
16316
16317 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16318 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16319 Use a separate line for a loop or block statement name, but do not use an extra
16320 indentation level for the statement itself.
16321
16322 @end table
16323
16324 @ifclear vms
16325 @noindent
16326 The @option{-c1} and @option{-c2} switches are incompatible.
16327 The @option{-c3} and @option{-c4} switches are compatible with each other and
16328 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16329 the other comment formatting switches.
16330
16331 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16332 @end ifclear
16333
16334 @ifset vms
16335 @noindent
16336 For the @option{/COMMENTS_LAYOUT} qualifier:
16337 @itemize @bullet
16338 @item
16339 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16340 @item
16341 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16342 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16343 @end itemize
16344
16345 @noindent
16346 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16347 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16348 @end ifset
16349
16350 @node General Text Layout Control
16351 @subsection General Text Layout Control
16352
16353 @noindent
16354 These switches allow control over line length and indentation.
16355
16356 @table @option
16357 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16358 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16359 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16360
16361 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16362 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16363 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16364
16365 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16366 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16367 Indentation level for continuation lines (relative to the line being
16368 continued), @var{nnn} from 1@dots{}9.
16369 The default
16370 value is one less then the (normal) indentation level, unless the
16371 indentation is set to 1 (in which case the default value for continuation
16372 line indentation is also 1)
16373 @end table
16374
16375 @node Other Formatting Options
16376 @subsection Other Formatting Options
16377
16378 @noindent
16379 These switches control the inclusion of missing end/exit labels, and
16380 the indentation level in @b{case} statements.
16381
16382 @table @option
16383 @item ^-e^/NO_MISSED_LABELS^
16384 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16385 Do not insert missing end/exit labels. An end label is the name of
16386 a construct that may optionally be repeated at the end of the
16387 construct's declaration;
16388 e.g., the names of packages, subprograms, and tasks.
16389 An exit label is the name of a loop that may appear as target
16390 of an exit statement within the loop.
16391 By default, @command{gnatpp} inserts these end/exit labels when
16392 they are absent from the original source. This option suppresses such
16393 insertion, so that the formatted source reflects the original.
16394
16395 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16396 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16397 Insert a Form Feed character after a pragma Page.
16398
16399 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16400 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16401 Do not use an additional indentation level for @b{case} alternatives
16402 and variants if there are @var{nnn} or more (the default
16403 value is 10).
16404 If @var{nnn} is 0, an additional indentation level is
16405 used for @b{case} alternatives and variants regardless of their number.
16406 @end table
16407
16408 @node Setting the Source Search Path
16409 @subsection Setting the Source Search Path
16410
16411 @noindent
16412 To define the search path for the input source file, @command{gnatpp}
16413 uses the same switches as the GNAT compiler, with the same effects.
16414
16415 @table @option
16416 @item ^-I^/SEARCH=^@var{dir}
16417 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16418 The same as the corresponding gcc switch
16419
16420 @item ^-I-^/NOCURRENT_DIRECTORY^
16421 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16422 The same as the corresponding gcc switch
16423
16424 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16425 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16426 The same as the corresponding gcc switch
16427
16428 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16429 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16430 The same as the corresponding gcc switch
16431
16432 @end table
16433
16434 @node Output File Control
16435 @subsection Output File Control
16436
16437 @noindent
16438 By default the output is sent to the file whose name is obtained by appending
16439 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16440 (if the file with this name already exists, it is unconditionally overwritten).
16441 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16442 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16443 as output file.
16444 The output may be redirected by the following switches:
16445
16446 @table @option
16447 @item ^-pipe^/STANDARD_OUTPUT^
16448 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16449 Send the output to @code{Standard_Output}
16450
16451 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16452 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16453 Write the output into @var{output_file}.
16454 If @var{output_file} already exists, @command{gnatpp} terminates without
16455 reading or processing the input file.
16456
16457 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16458 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16459 Write the output into @var{output_file}, overwriting the existing file
16460 (if one is present).
16461
16462 @item ^-r^/REPLACE^
16463 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16464 Replace the input source file with the reformatted output, and copy the
16465 original input source into the file whose name is obtained by appending the
16466 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16467 If a file with this name already exists, @command{gnatpp} terminates without
16468 reading or processing the input file.
16469
16470 @item ^-rf^/OVERRIDING_REPLACE^
16471 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16472 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16473 already exists, it is overwritten.
16474
16475 @item ^-rnb^/REPLACE_NO_BACKUP^
16476 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16477 Replace the input source file with the reformatted output without
16478 creating any backup copy of the input source.
16479
16480 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16481 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16482 Specifies the format of the reformatted output file. The @var{xxx}
16483 ^string specified with the switch^option^ may be either
16484 @itemize @bullet
16485 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16486 @item ``@option{^crlf^CRLF^}''
16487 the same as @option{^crlf^CRLF^}
16488 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16489 @item ``@option{^lf^LF^}''
16490 the same as @option{^unix^UNIX^}
16491 @end itemize
16492
16493 @item ^-W^/RESULT_ENCODING=^@var{e}
16494 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16495 Specify the wide character encoding method used to write the code in the
16496 result file
16497 @var{e} is one of the following:
16498
16499 @itemize @bullet
16500
16501 @item ^h^HEX^
16502 Hex encoding
16503
16504 @item ^u^UPPER^
16505 Upper half encoding
16506
16507 @item ^s^SHIFT_JIS^
16508 Shift/JIS encoding
16509
16510 @item ^e^EUC^
16511 EUC encoding
16512
16513 @item ^8^UTF8^
16514 UTF-8 encoding
16515
16516 @item ^b^BRACKETS^
16517 Brackets encoding (default value)
16518 @end itemize
16519
16520 @end table
16521
16522 @noindent
16523 Options @option{^-pipe^/STANDARD_OUTPUT^},
16524 @option{^-o^/OUTPUT^} and
16525 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16526 contains only one file to reformat.
16527 Option
16528 @option{^--eol^/END_OF_LINE^}
16529 and
16530 @option{^-W^/RESULT_ENCODING^}
16531 cannot be used together
16532 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16533
16534 @node Other gnatpp Switches
16535 @subsection Other @code{gnatpp} Switches
16536
16537 @noindent
16538 The additional @command{gnatpp} switches are defined in this subsection.
16539
16540 @table @option
16541 @item ^-files @var{filename}^/FILES=@var{output_file}^
16542 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16543 Take the argument source files from the specified file. This file should be an
16544 ordinary textual file containing file names separated by spaces or
16545 line breaks. You can use this switch more then once in the same call to
16546 @command{gnatpp}. You also can combine this switch with explicit list of
16547 files.
16548
16549 @item ^-v^/VERBOSE^
16550 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16551 Verbose mode;
16552 @command{gnatpp} generates version information and then
16553 a trace of the actions it takes to produce or obtain the ASIS tree.
16554
16555 @item ^-w^/WARNINGS^
16556 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16557 Warning mode;
16558 @command{gnatpp} generates a warning whenever it cannot provide
16559 a required layout in the result source.
16560 @end table
16561
16562 @node Formatting Rules
16563 @section Formatting Rules
16564
16565 @noindent
16566 The following subsections show how @command{gnatpp} treats ``white space'',
16567 comments, program layout, and name casing.
16568 They provide the detailed descriptions of the switches shown above.
16569
16570 @menu
16571 * White Space and Empty Lines::
16572 * Formatting Comments::
16573 * Construct Layout::
16574 * Name Casing::
16575 @end menu
16576
16577 @node White Space and Empty Lines
16578 @subsection White Space and Empty Lines
16579
16580 @noindent
16581 @command{gnatpp} does not have an option to control space characters.
16582 It will add or remove spaces according to the style illustrated by the
16583 examples in the @cite{Ada Reference Manual}.
16584
16585 The only format effectors
16586 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16587 that will appear in the output file are platform-specific line breaks,
16588 and also format effectors within (but not at the end of) comments.
16589 In particular, each horizontal tab character that is not inside
16590 a comment will be treated as a space and thus will appear in the
16591 output file as zero or more spaces depending on
16592 the reformatting of the line in which it appears.
16593 The only exception is a Form Feed character, which is inserted after a
16594 pragma @code{Page} when @option{-ff} is set.
16595
16596 The output file will contain no lines with trailing ``white space'' (spaces,
16597 format effectors).
16598
16599 Empty lines in the original source are preserved
16600 only if they separate declarations or statements.
16601 In such contexts, a
16602 sequence of two or more empty lines is replaced by exactly one empty line.
16603 Note that a blank line will be removed if it separates two ``comment blocks''
16604 (a comment block is a sequence of whole-line comments).
16605 In order to preserve a visual separation between comment blocks, use an
16606 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16607 Likewise, if for some reason you wish to have a sequence of empty lines,
16608 use a sequence of empty comments instead.
16609
16610 @node Formatting Comments
16611 @subsection Formatting Comments
16612
16613 @noindent
16614 Comments in Ada code are of two kinds:
16615 @itemize @bullet
16616 @item
16617 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16618 ``white space'') on a line
16619
16620 @item
16621 an @emph{end-of-line comment}, which follows some other Ada lexical element
16622 on the same line.
16623 @end itemize
16624
16625 @noindent
16626 The indentation of a whole-line comment is that of either
16627 the preceding or following line in
16628 the formatted source, depending on switch settings as will be described below.
16629
16630 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16631 between the end of the preceding Ada lexical element and the beginning
16632 of the comment as appear in the original source,
16633 unless either the comment has to be split to
16634 satisfy the line length limitation, or else the next line contains a
16635 whole line comment that is considered a continuation of this end-of-line
16636 comment (because it starts at the same position).
16637 In the latter two
16638 cases, the start of the end-of-line comment is moved right to the nearest
16639 multiple of the indentation level.
16640 This may result in a ``line overflow'' (the right-shifted comment extending
16641 beyond the maximum line length), in which case the comment is split as
16642 described below.
16643
16644 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16645 (GNAT-style comment line indentation)
16646 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16647 (reference-manual comment line indentation).
16648 With reference-manual style, a whole-line comment is indented as if it
16649 were a declaration or statement at the same place
16650 (i.e., according to the indentation of the preceding line(s)).
16651 With GNAT style, a whole-line comment that is immediately followed by an
16652 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16653 word @b{begin}, is indented based on the construct that follows it.
16654
16655 For example:
16656 @smallexample @c ada
16657 @cartouche
16658 if A then
16659     null;
16660        -- some comment
16661 else
16662    null;
16663 end if;
16664 @end cartouche
16665 @end smallexample
16666
16667 @noindent
16668 Reference-manual indentation produces:
16669
16670 @smallexample @c ada
16671 @cartouche
16672 if A then
16673    null;
16674    --  some comment
16675 else
16676    null;
16677 end if;
16678 @end cartouche
16679 @end smallexample
16680
16681 @noindent
16682 while GNAT-style indentation produces:
16683
16684 @smallexample @c ada
16685 @cartouche
16686 if A then
16687    null;
16688 --  some comment
16689 else
16690    null;
16691 end if;
16692 @end cartouche
16693 @end smallexample
16694
16695 @noindent
16696 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16697 (GNAT style comment beginning) has the following
16698 effect:
16699
16700 @itemize @bullet
16701 @item
16702 For each whole-line comment that does not end with two hyphens,
16703 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16704 to ensure that there are at least two spaces between these hyphens and the
16705 first non-blank character of the comment.
16706 @end itemize
16707
16708 @noindent
16709 For an end-of-line comment, if in the original source the next line is a
16710 whole-line comment that starts at the same position
16711 as the end-of-line comment,
16712 then the whole-line comment (and all whole-line comments
16713 that follow it and that start at the same position)
16714 will start at this position in the output file.
16715
16716 @noindent
16717 That is, if in the original source we have:
16718
16719 @smallexample @c ada
16720 @cartouche
16721 begin
16722 A := B + C;            --  B must be in the range Low1..High1
16723                        --  C must be in the range Low2..High2
16724              --B+C will be in the range Low1+Low2..High1+High2
16725 X := X + 1;
16726 @end cartouche
16727 @end smallexample
16728
16729 @noindent
16730 Then in the formatted source we get
16731
16732 @smallexample @c ada
16733 @cartouche
16734 begin
16735    A := B + C;            --  B must be in the range Low1..High1
16736                           --  C must be in the range Low2..High2
16737    --  B+C will be in the range Low1+Low2..High1+High2
16738    X := X + 1;
16739 @end cartouche
16740 @end smallexample
16741
16742 @noindent
16743 A comment that exceeds the line length limit will be split.
16744 Unless switch
16745 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16746 the line belongs to a reformattable block, splitting the line generates a
16747 @command{gnatpp} warning.
16748 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16749 comments may be reformatted in typical
16750 word processor style (that is, moving words between lines and putting as
16751 many words in a line as possible).
16752
16753 @noindent
16754 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16755 that has a special format (that is, a character that is neither a letter nor digit
16756 not white space nor line break immediately following the leading @code{--} of
16757 the comment) should be without any change moved from the argument source
16758 into reformatted source. This switch allows to preserve comments that are used
16759 as a special marks in the code (e.g.@: SPARK annotation).
16760
16761 @node Construct Layout
16762 @subsection Construct Layout
16763
16764 @noindent
16765 In several cases the suggested layout in the Ada Reference Manual includes
16766 an extra level of indentation that many programmers prefer to avoid. The
16767 affected cases include:
16768
16769 @itemize @bullet
16770
16771 @item Record type declaration (RM 3.8)
16772
16773 @item Record representation clause (RM 13.5.1)
16774
16775 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16776
16777 @item Block statement in case if a block has a statement identifier (RM 5.6)
16778 @end itemize
16779
16780 @noindent
16781 In compact mode (when GNAT style layout or compact layout is set),
16782 the pretty printer uses one level of indentation instead
16783 of two. This is achieved in the record definition and record representation
16784 clause cases by putting the @code{record} keyword on the same line as the
16785 start of the declaration or representation clause, and in the block and loop
16786 case by putting the block or loop header on the same line as the statement
16787 identifier.
16788
16789 @noindent
16790 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16791 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16792 layout on the one hand, and uncompact layout
16793 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16794 can be illustrated by the following examples:
16795
16796 @iftex
16797 @cartouche
16798 @multitable @columnfractions .5 .5
16799 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16800
16801 @item
16802 @smallexample @c ada
16803 type q is record
16804    a : integer;
16805    b : integer;
16806 end record;
16807 @end smallexample
16808 @tab
16809 @smallexample @c ada
16810 type q is
16811    record
16812       a : integer;
16813       b : integer;
16814    end record;
16815 @end smallexample
16816
16817 @item
16818 @smallexample @c ada
16819 for q use record
16820    a at 0 range  0 .. 31;
16821    b at 4 range  0 .. 31;
16822 end record;
16823 @end smallexample
16824 @tab
16825 @smallexample @c ada
16826 for q use
16827    record
16828       a at 0 range  0 .. 31;
16829       b at 4 range  0 .. 31;
16830    end record;
16831 @end smallexample
16832
16833 @item
16834 @smallexample @c ada
16835 Block : declare
16836    A : Integer := 3;
16837 begin
16838    Proc (A, A);
16839 end Block;
16840 @end smallexample
16841 @tab
16842 @smallexample @c ada
16843 Block :
16844    declare
16845       A : Integer := 3;
16846    begin
16847       Proc (A, A);
16848    end Block;
16849 @end smallexample
16850
16851 @item
16852 @smallexample @c ada
16853 Clear : for J in 1 .. 10 loop
16854    A (J) := 0;
16855 end loop Clear;
16856 @end smallexample
16857 @tab
16858 @smallexample @c ada
16859 Clear :
16860    for J in 1 .. 10 loop
16861       A (J) := 0;
16862    end loop Clear;
16863 @end smallexample
16864 @end multitable
16865 @end cartouche
16866 @end iftex
16867
16868 @ifnottex
16869 @smallexample
16870 @cartouche
16871 GNAT style, compact layout              Uncompact layout
16872
16873 type q is record                        type q is
16874    a : integer;                            record
16875    b : integer;                               a : integer;
16876 end record;                                   b : integer;
16877                                            end record;
16878
16879 for q use record                        for q use
16880    a at 0 range  0 .. 31;                  record
16881    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16882 end record;                                   b at 4 range  0 .. 31;
16883                                            end record;
16884
16885 Block : declare                         Block :
16886    A : Integer := 3;                       declare
16887 begin                                         A : Integer := 3;
16888    Proc (A, A);                            begin
16889 end Block;                                    Proc (A, A);
16890                                            end Block;
16891
16892 Clear : for J in 1 .. 10 loop           Clear :
16893    A (J) := 0;                             for J in 1 .. 10 loop
16894 end loop Clear;                               A (J) := 0;
16895                                            end loop Clear;
16896 @end cartouche
16897 @end smallexample
16898 @end ifnottex
16899
16900 @noindent
16901 A further difference between GNAT style layout and compact layout is that
16902 GNAT style layout inserts empty lines as separation for
16903 compound statements, return statements and bodies.
16904
16905 Note that the layout specified by
16906 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16907 for named block and loop statements overrides the layout defined by these
16908 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16909 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16910 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16911
16912 @node Name Casing
16913 @subsection Name Casing
16914
16915 @noindent
16916 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16917 the same casing as the corresponding defining identifier.
16918
16919 You control the casing for defining occurrences via the
16920 @option{^-n^/NAME_CASING^} switch.
16921 @ifclear vms
16922 With @option{-nD} (``as declared'', which is the default),
16923 @end ifclear
16924 @ifset vms
16925 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16926 @end ifset
16927 defining occurrences appear exactly as in the source file
16928 where they are declared.
16929 The other ^values for this switch^options for this qualifier^ ---
16930 @option{^-nU^UPPER_CASE^},
16931 @option{^-nL^LOWER_CASE^},
16932 @option{^-nM^MIXED_CASE^} ---
16933 result in
16934 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16935 If @command{gnatpp} changes the casing of a defining
16936 occurrence, it analogously changes the casing of all the
16937 usage occurrences of this name.
16938
16939 If the defining occurrence of a name is not in the source compilation unit
16940 currently being processed by @command{gnatpp}, the casing of each reference to
16941 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16942 switch (subject to the dictionary file mechanism described below).
16943 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16944 had affected the
16945 casing for the defining occurrence of the name.
16946
16947 Some names may need to be spelled with casing conventions that are not
16948 covered by the upper-, lower-, and mixed-case transformations.
16949 You can arrange correct casing by placing such names in a
16950 @emph{dictionary file},
16951 and then supplying a @option{^-D^/DICTIONARY^} switch.
16952 The casing of names from dictionary files overrides
16953 any @option{^-n^/NAME_CASING^} switch.
16954
16955 To handle the casing of Ada predefined names and the names from GNAT libraries,
16956 @command{gnatpp} assumes a default dictionary file.
16957 The name of each predefined entity is spelled with the same casing as is used
16958 for the entity in the @cite{Ada Reference Manual}.
16959 The name of each entity in the GNAT libraries is spelled with the same casing
16960 as is used in the declaration of that entity.
16961
16962 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16963 default dictionary file.
16964 Instead, the casing for predefined and GNAT-defined names will be established
16965 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16966 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16967 will appear as just shown,
16968 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16969 To ensure that even such names are rendered in uppercase,
16970 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16971 (or else, less conveniently, place these names in upper case in a dictionary
16972 file).
16973
16974 A dictionary file is
16975 a plain text file; each line in this file can be either a blank line
16976 (containing only space characters and ASCII.HT characters), an Ada comment
16977 line, or the specification of exactly one @emph{casing schema}.
16978
16979 A casing schema is a string that has the following syntax:
16980
16981 @smallexample
16982 @cartouche
16983   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16984
16985   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16986 @end cartouche
16987 @end smallexample
16988
16989 @noindent
16990 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16991 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16992
16993 The casing schema string can be followed by white space and/or an Ada-style
16994 comment; any amount of white space is allowed before the string.
16995
16996 If a dictionary file is passed as
16997 @ifclear vms
16998 the value of a @option{-D@var{file}} switch
16999 @end ifclear
17000 @ifset vms
17001 an option to the @option{/DICTIONARY} qualifier
17002 @end ifset
17003 then for every
17004 simple name and every identifier, @command{gnatpp} checks if the dictionary
17005 defines the casing for the name or for some of its parts (the term ``subword''
17006 is used below to denote the part of a name which is delimited by ``_'' or by
17007 the beginning or end of the word and which does not contain any ``_'' inside):
17008
17009 @itemize @bullet
17010 @item
17011 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17012 the casing defined by the dictionary; no subwords are checked for this word
17013
17014 @item
17015 for every subword @command{gnatpp} checks if the dictionary contains the
17016 corresponding string of the form @code{*@var{simple_identifier}*},
17017 and if it does, the casing of this @var{simple_identifier} is used
17018 for this subword
17019
17020 @item
17021 if the whole name does not contain any ``_'' inside, and if for this name
17022 the dictionary contains two entries - one of the form @var{identifier},
17023 and another - of the form *@var{simple_identifier}*, then the first one
17024 is applied to define the casing of this name
17025
17026 @item
17027 if more than one dictionary file is passed as @command{gnatpp} switches, each
17028 dictionary adds new casing exceptions and overrides all the existing casing
17029 exceptions set by the previous dictionaries
17030
17031 @item
17032 when @command{gnatpp} checks if the word or subword is in the dictionary,
17033 this check is not case sensitive
17034 @end itemize
17035
17036 @noindent
17037 For example, suppose we have the following source to reformat:
17038
17039 @smallexample @c ada
17040 @cartouche
17041 procedure test is
17042    name1 : integer := 1;
17043    name4_name3_name2 : integer := 2;
17044    name2_name3_name4 : Boolean;
17045    name1_var : Float;
17046 begin
17047    name2_name3_name4 := name4_name3_name2 > name1;
17048 end;
17049 @end cartouche
17050 @end smallexample
17051
17052 @noindent
17053 And suppose we have two dictionaries:
17054
17055 @smallexample
17056 @cartouche
17057 @i{dict1:}
17058    NAME1
17059    *NaMe3*
17060    *Name1*
17061 @end cartouche
17062
17063 @cartouche
17064 @i{dict2:}
17065   *NAME3*
17066 @end cartouche
17067 @end smallexample
17068
17069 @noindent
17070 If @command{gnatpp} is called with the following switches:
17071
17072 @smallexample
17073 @ifclear vms
17074 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17075 @end ifclear
17076 @ifset vms
17077 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17078 @end ifset
17079 @end smallexample
17080
17081 @noindent
17082 then we will get the following name casing in the @command{gnatpp} output:
17083
17084 @smallexample @c ada
17085 @cartouche
17086 procedure Test is
17087    NAME1             : Integer := 1;
17088    Name4_NAME3_Name2 : Integer := 2;
17089    Name2_NAME3_Name4 : Boolean;
17090    Name1_Var         : Float;
17091 begin
17092    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17093 end Test;
17094 @end cartouche
17095 @end smallexample
17096
17097 @c *********************************
17098 @node The GNAT Metric Tool gnatmetric
17099 @chapter The GNAT Metric Tool @command{gnatmetric}
17100 @findex gnatmetric
17101 @cindex Metric tool
17102
17103 @noindent
17104 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17105 for computing various program metrics.
17106 It takes an Ada source file as input and generates a file containing the
17107 metrics data as output. Various switches control which
17108 metrics are computed and output.
17109
17110 @command{gnatmetric} generates and uses the ASIS
17111 tree for the input source and thus requires the input to be syntactically and
17112 semantically legal.
17113 If this condition is not met, @command{gnatmetric} will generate
17114 an error message; no metric information for this file will be
17115 computed and reported.
17116
17117 If the compilation unit contained in the input source depends semantically
17118 upon units in files located outside the current directory, you have to provide
17119 the source search path when invoking @command{gnatmetric}.
17120 If it depends semantically upon units that are contained
17121 in files with names that do not follow the GNAT file naming rules, you have to
17122 provide the configuration file describing the corresponding naming scheme (see
17123 the description of the @command{gnatmetric} switches below.)
17124 Alternatively, you may use a project file and invoke @command{gnatmetric}
17125 through the @command{gnat} driver.
17126
17127 The @command{gnatmetric} command has the form
17128
17129 @smallexample
17130 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17131 @end smallexample
17132
17133 @noindent
17134 where
17135 @itemize @bullet
17136 @item
17137 @var{switches} specify the metrics to compute and define the destination for
17138 the output
17139
17140 @item
17141 Each @var{filename} is the name (including the extension) of a source
17142 file to process. ``Wildcards'' are allowed, and
17143 the file name may contain path information.
17144 If no @var{filename} is supplied, then the @var{switches} list must contain
17145 at least one
17146 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17147 Including both a @option{-files} switch and one or more
17148 @var{filename} arguments is permitted.
17149
17150 @item
17151 @samp{-cargs @var{gcc_switches}} is a list of switches for
17152 @command{gcc}. They will be passed on to all compiler invocations made by
17153 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17154 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17155 and use the @option{-gnatec} switch to set the configuration file.
17156 @end itemize
17157
17158 @menu
17159 * Switches for gnatmetric::
17160 @end menu
17161
17162 @node Switches for gnatmetric
17163 @section Switches for @command{gnatmetric}
17164
17165 @noindent
17166 The following subsections describe the various switches accepted by
17167 @command{gnatmetric}, organized by category.
17168
17169 @menu
17170 * Output Files Control::
17171 * Disable Metrics For Local Units::
17172 * Specifying a set of metrics to compute::
17173 * Other gnatmetric Switches::
17174 * Generate project-wide metrics::
17175 @end menu
17176
17177 @node Output Files Control
17178 @subsection Output File Control
17179 @cindex Output file control in @command{gnatmetric}
17180
17181 @noindent
17182 @command{gnatmetric} has two output formats. It can generate a
17183 textual (human-readable) form, and also XML. By default only textual
17184 output is generated.
17185
17186 When generating the output in textual form, @command{gnatmetric} creates
17187 for each Ada source file a corresponding text file
17188 containing the computed metrics, except for the case when the set of metrics
17189 specified by gnatmetric parameters consists only of metrics that are computed
17190 for the whole set of analyzed sources, but not for each Ada source.
17191 By default, this file is placed in the same directory as where the source
17192 file is located, and its name is obtained
17193 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17194 input file.
17195
17196 All the output information generated in XML format is placed in a single
17197 file. By default this file is placed in the current directory and has the
17198 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17199
17200 Some of the computed metrics are summed over the units passed to
17201 @command{gnatmetric}; for example, the total number of lines of code.
17202 By default this information is sent to @file{stdout}, but a file
17203 can be specified with the @option{-og} switch.
17204
17205 The following switches control the @command{gnatmetric} output:
17206
17207 @table @option
17208 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17209 @item ^-x^/XML^
17210 Generate the XML output
17211
17212 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17213 @item ^-xs^/XSD^
17214 Generate the XML output and the XML schema file that describes the structure
17215 of the XML metric report, this schema is assigned to the XML file. The schema
17216 file has the same name as the XML output file with @file{.xml} suffix replaced
17217 with @file{.xsd}
17218
17219 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17220 @item ^-nt^/NO_TEXT^
17221 Do not generate the output in text form (implies @option{^-x^/XML^})
17222
17223 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17224 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17225 Put textual files with detailed metrics into @var{output_dir}
17226
17227 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17228 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17229 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17230 in the name of the output file.
17231
17232 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17233 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17234 Put global metrics into @var{file_name}
17235
17236 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17237 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17238 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17239
17240 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17241 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17242 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17243 output includes the name(s) of the Ada source file(s) from which the metrics
17244 are computed.  By default each name includes the absolute path. The
17245 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17246 to exclude all directory information from the file names that are output.)
17247
17248 @end table
17249
17250 @node Disable Metrics For Local Units
17251 @subsection Disable Metrics For Local Units
17252 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17253
17254 @noindent
17255 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17256 one compilation
17257 unit per one source file. It computes line metrics for the whole source
17258 file, and it also computes syntax
17259 and complexity metrics for the file's outermost unit.
17260
17261 By default, @command{gnatmetric} will also compute all metrics for certain
17262 kinds of locally declared program units:
17263
17264 @itemize @bullet
17265 @item
17266 subprogram (and generic subprogram) bodies;
17267
17268 @item
17269 package (and generic package) specs and bodies;
17270
17271 @item
17272 task object and type specifications and bodies;
17273
17274 @item
17275 protected object and type specifications and bodies.
17276 @end itemize
17277
17278 @noindent
17279 These kinds of entities will be referred to as
17280 @emph{eligible local program units}, or simply @emph{eligible local units},
17281 @cindex Eligible local unit (for @command{gnatmetric})
17282 in the discussion below.
17283
17284 Note that a subprogram declaration, generic instantiation,
17285 or renaming declaration only receives metrics
17286 computation when it appear as the outermost entity
17287 in a source file.
17288
17289 Suppression of metrics computation for eligible local units can be
17290 obtained via the following switch:
17291
17292 @table @option
17293 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17294 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17295 Do not compute detailed metrics for eligible local program units
17296
17297 @end table
17298
17299 @node Specifying a set of metrics to compute
17300 @subsection Specifying a set of metrics to compute
17301
17302 @noindent
17303 By default all the metrics are computed and reported. The switches
17304 described in this subsection allow you to control, on an individual
17305 basis, whether metrics are computed and
17306 reported. If at least one positive metric
17307 switch is specified (that is, a switch that defines that a given
17308 metric or set of metrics is to be computed), then only
17309 explicitly specified metrics are reported.
17310
17311 @menu
17312 * Line Metrics Control::
17313 * Syntax Metrics Control::
17314 * Complexity Metrics Control::
17315 * Object-Oriented Metrics Control::
17316 @end menu
17317
17318 @node Line Metrics Control
17319 @subsubsection Line Metrics Control
17320 @cindex Line metrics control in @command{gnatmetric}
17321
17322 @noindent
17323 For any (legal) source file, and for each of its
17324 eligible local program units, @command{gnatmetric} computes the following
17325 metrics:
17326
17327 @itemize @bullet
17328 @item
17329 the total number of lines;
17330
17331 @item
17332 the total number of code lines (i.e., non-blank lines that are not comments)
17333
17334 @item
17335 the number of comment lines
17336
17337 @item
17338 the number of code lines containing end-of-line comments;
17339
17340 @item
17341 the comment percentage: the ratio between the number of lines that contain
17342 comments and the number of all non-blank lines, expressed as a percentage;
17343
17344 @item
17345 the number of empty lines and lines containing only space characters and/or
17346 format effectors (blank lines)
17347
17348 @item
17349 the average number of code lines in subprogram bodies, task bodies, entry
17350 bodies and statement sequences in package bodies (this metric is only computed
17351 across the whole set of the analyzed units)
17352
17353 @end itemize
17354
17355 @noindent
17356 @command{gnatmetric} sums the values of the line metrics for all the
17357 files being processed and then generates the cumulative results. The tool
17358 also computes for all the files being processed the average number of code
17359 lines in bodies.
17360
17361 You can use the following switches to select the specific line metrics
17362 to be computed and reported.
17363
17364 @table @option
17365 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17366
17367 @ifclear vms
17368 @cindex @option{--no-lines@var{x}}
17369 @end ifclear
17370
17371 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17372 Report all the line metrics
17373
17374 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17375 Do not report any of line metrics
17376
17377 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17378 Report the number of all lines
17379
17380 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17381 Do not report the number of all lines
17382
17383 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17384 Report the number of code lines
17385
17386 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17387 Do not report the number of code lines
17388
17389 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17390 Report the number of comment lines
17391
17392 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17393 Do not report the number of comment lines
17394
17395 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17396 Report the number of code lines containing
17397 end-of-line comments
17398
17399 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17400 Do not report the number of code lines containing
17401 end-of-line comments
17402
17403 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17404 Report the comment percentage in the program text
17405
17406 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17407 Do not report the comment percentage in the program text
17408
17409 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17410 Report the number of blank lines
17411
17412 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17413 Do not report the number of blank lines
17414
17415 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17416 Report the average number of code lines in subprogram bodies, task bodies,
17417 entry bodies and statement sequences in package bodies. The metric is computed
17418 and reported for the whole set of processed Ada sources only.
17419
17420 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17421 Do not report the average number of code lines in subprogram bodies,
17422 task bodies, entry bodies and statement sequences in package bodies.
17423
17424 @end table
17425
17426 @node Syntax Metrics Control
17427 @subsubsection Syntax Metrics Control
17428 @cindex Syntax metrics control in @command{gnatmetric}
17429
17430 @noindent
17431 @command{gnatmetric} computes various syntactic metrics for the
17432 outermost unit and for each eligible local unit:
17433
17434 @table @emph
17435 @item LSLOC (``Logical Source Lines Of Code'')
17436 The total number of declarations and the total number of statements
17437
17438 @item Maximal static nesting level of inner program units
17439 According to
17440 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17441 package, a task unit, a protected unit, a
17442 protected entry, a generic unit, or an explicitly declared subprogram other
17443 than an enumeration literal.''
17444
17445 @item Maximal nesting level of composite syntactic constructs
17446 This corresponds to the notion of the
17447 maximum nesting level in the GNAT built-in style checks
17448 (@pxref{Style Checking})
17449 @end table
17450
17451 @noindent
17452 For the outermost unit in the file, @command{gnatmetric} additionally computes
17453 the following metrics:
17454
17455 @table @emph
17456 @item Public subprograms
17457 This metric is computed for package specs. It is the
17458 number of subprograms and generic subprograms declared in the visible
17459 part (including the visible part of nested packages, protected objects, and
17460 protected types).
17461
17462 @item All subprograms
17463 This metric is computed for bodies and subunits. The
17464 metric is equal to a total number of subprogram bodies in the compilation
17465 unit.
17466 Neither generic instantiations nor renamings-as-a-body nor body stubs
17467 are counted. Any subprogram body is counted, independently of its nesting
17468 level and enclosing constructs. Generic bodies and bodies of protected
17469 subprograms are counted in the same way as ``usual'' subprogram bodies.
17470
17471 @item Public types
17472 This metric is computed for package specs and
17473 generic package declarations. It is the total number of types
17474 that can be referenced from outside this compilation unit, plus the
17475 number of types from all the visible parts of all the visible generic
17476 packages. Generic formal types are not counted.  Only types, not subtypes,
17477 are included.
17478
17479 @noindent
17480 Along with the total number of public types, the following
17481 types are counted and reported separately:
17482
17483 @itemize @bullet
17484 @item
17485 Abstract types
17486
17487 @item
17488 Root tagged types (abstract, non-abstract, private, non-private). Type
17489 extensions are @emph{not} counted
17490
17491 @item
17492 Private types (including private extensions)
17493
17494 @item
17495 Task types
17496
17497 @item
17498 Protected types
17499
17500 @end itemize
17501
17502 @item All types
17503 This metric is computed for any compilation unit. It is equal to the total
17504 number of the declarations of different types given in the compilation unit.
17505 The private and the corresponding full type declaration are counted as one
17506 type declaration. Incomplete type declarations and generic formal types
17507 are not counted.
17508 No distinction is made among different kinds of types (abstract,
17509 private etc.); the total number of types is computed and reported.
17510
17511 @end table
17512
17513 @noindent
17514 By default, all the syntax metrics are computed and reported. You can use the
17515 following switches to select specific syntax metrics.
17516
17517 @table @option
17518
17519 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17520
17521 @ifclear vms
17522 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17523 @end ifclear
17524
17525 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17526 Report all the syntax metrics
17527
17528 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17529 Do not report any of syntax metrics
17530
17531 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17532 Report the total number of declarations
17533
17534 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17535 Do not report the total number of declarations
17536
17537 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17538 Report the total number of statements
17539
17540 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17541 Do not report the total number of statements
17542
17543 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17544 Report the number of public subprograms in a compilation unit
17545
17546 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17547 Do not report the number of public subprograms in a compilation unit
17548
17549 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17550 Report the number of all the subprograms in a compilation unit
17551
17552 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17553 Do not report the number of all the subprograms in a compilation unit
17554
17555 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17556 Report the number of public types in a compilation unit
17557
17558 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17559 Do not report the number of public types in a compilation unit
17560
17561 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17562 Report the number of all the types in a compilation unit
17563
17564 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17565 Do not report the number of all the types in a compilation unit
17566
17567 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17568 Report the maximal program unit nesting level
17569
17570 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17571 Do not report the maximal program unit nesting level
17572
17573 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17574 Report the maximal construct nesting level
17575
17576 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17577 Do not report the maximal construct nesting level
17578
17579 @end table
17580
17581 @node Complexity Metrics Control
17582 @subsubsection Complexity Metrics Control
17583 @cindex Complexity metrics control in @command{gnatmetric}
17584
17585 @noindent
17586 For a program unit that is an executable body (a subprogram body (including
17587 generic bodies), task body, entry body or a package body containing
17588 its own statement sequence) @command{gnatmetric} computes the following
17589 complexity metrics:
17590
17591 @itemize @bullet
17592 @item
17593 McCabe cyclomatic complexity;
17594
17595 @item
17596 McCabe essential complexity;
17597
17598 @item
17599 maximal loop nesting level
17600
17601 @end itemize
17602
17603 @noindent
17604 The McCabe complexity metrics are defined
17605 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17606
17607 According to McCabe, both control statements and short-circuit control forms
17608 should be taken into account when computing cyclomatic complexity. For each
17609 body, we compute three metric values:
17610
17611 @itemize @bullet
17612 @item
17613 the complexity introduced by control
17614 statements only, without taking into account short-circuit forms,
17615
17616 @item
17617 the complexity introduced by short-circuit control forms only, and
17618
17619 @item
17620 the total
17621 cyclomatic complexity, which is the sum of these two values.
17622 @end itemize
17623
17624 @noindent
17625 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17626 the code in the exception handlers and in all the nested program units.
17627
17628 By default, all the complexity metrics are computed and reported.
17629 For more fine-grained control you can use
17630 the following switches:
17631
17632 @table @option
17633 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17634
17635 @ifclear vms
17636 @cindex @option{--no-complexity@var{x}}
17637 @end ifclear
17638
17639 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17640 Report all the complexity metrics
17641
17642 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17643 Do not report any of complexity metrics
17644
17645 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17646 Report the McCabe Cyclomatic Complexity
17647
17648 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17649 Do not report the McCabe Cyclomatic Complexity
17650
17651 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17652 Report the Essential Complexity
17653
17654 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17655 Do not report the Essential Complexity
17656
17657 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17658 Report maximal loop nesting level
17659
17660 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17661 Do not report maximal loop nesting level
17662
17663 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17664 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17665 task bodies, entry bodies and statement sequences in package bodies.
17666 The metric is computed and reported for whole set of processed Ada sources
17667 only.
17668
17669 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17670 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17671 bodies, task bodies, entry bodies and statement sequences in package bodies
17672
17673 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17674 @item ^-ne^/NO_EXITS_AS_GOTOS^
17675 Do not consider @code{exit} statements as @code{goto}s when
17676 computing Essential Complexity
17677
17678 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17679 Report the extra exit points for subprogram bodies. As an exit point, this
17680 metric counts @code{return} statements and raise statements in case when the
17681 raised exception is not handled in the same body. In case of a function this
17682 metric subtracts 1 from the number of exit points, because a function body
17683 must contain at least one @code{return} statement.
17684
17685 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17686 Do not report the extra exit points for subprogram bodies
17687 @end table
17688
17689
17690 @node Object-Oriented Metrics Control
17691 @subsubsection Object-Oriented Metrics Control
17692 @cindex Object-Oriented metrics control in @command{gnatmetric}
17693
17694 @noindent
17695 @cindex Coupling metrics (in in @command{gnatmetric})
17696 Coupling metrics are object-oriented metrics that measure the
17697 dependencies between a given class (or a group of classes) and the
17698 ``external world'' (that is, the other classes in the program). In this
17699 subsection the term ``class'' is used in its
17700 traditional object-oriented programming sense
17701 (an instantiable module that contains data and/or method members).
17702 A @emph{category} (of classes)
17703 is a group of closely related classes that are reused and/or
17704 modified together.
17705
17706 A class @code{K}'s @emph{efferent coupling} is the number of classes
17707 that @code{K} depends upon.
17708 A category's efferent coupling is the number of classes outside the
17709 category that the classes inside the category depend upon.
17710
17711 A class @code{K}'s @emph{afferent coupling} is the number of classes
17712 that depend upon @code{K}.
17713 A category's afferent coupling is the number of classes outside the
17714 category that depend on classes belonging to the category.
17715
17716 Ada's implementation of the object-oriented paradigm does not use the
17717 traditional class notion, so the definition of the coupling
17718 metrics for Ada maps the class and class category notions
17719 onto Ada constructs.
17720
17721 For the coupling metrics, several kinds of modules -- a library package,
17722 a library generic package, and a library generic package instantiation --
17723 that define a tagged type or an interface type are
17724 considered to be a class. A category consists of a library package (or
17725 a library generic package) that defines a tagged or an interface type,
17726 together with all its descendant (generic) packages that define tagged
17727 or interface types. For any package counted as a class,
17728 its body and subunits (if any) are considered
17729 together with its spec when counting the dependencies, and coupling
17730 metrics are reported for spec units only. For dependencies
17731 between classes, the Ada semantic dependencies are considered.
17732 For coupling metrics, only dependencies on units that are considered as
17733 classes, are considered.
17734
17735 When computing coupling metrics, @command{gnatmetric} counts only
17736 dependencies between units that are arguments of the gnatmetric call.
17737 Coupling metrics are program-wide (or project-wide) metrics, so to
17738 get a valid result, you should call @command{gnatmetric} for
17739 the whole set of sources that make up your program. It can be done
17740 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17741 option (see See @ref{The GNAT Driver and Project Files} for details.
17742
17743 By default, all the coupling metrics are disabled. You can use the following
17744 switches to specify the coupling metrics to be computed and reported:
17745
17746 @table @option
17747
17748 @ifclear vms
17749 @cindex @option{--package@var{x}} (@command{gnatmetric})
17750 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17751 @cindex @option{--category@var{x}} (@command{gnatmetric})
17752 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17753 @end ifclear
17754
17755 @ifset vms
17756 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17757 @end ifset
17758
17759 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17760 Report all the coupling metrics
17761
17762 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17763 Do not report any of  metrics
17764
17765 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17766 Report package efferent coupling
17767
17768 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17769 Do not report package efferent coupling
17770
17771 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17772 Report package afferent coupling
17773
17774 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17775 Do not report package afferent coupling
17776
17777 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17778 Report category efferent coupling
17779
17780 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17781 Do not report category efferent coupling
17782
17783 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17784 Report category afferent coupling
17785
17786 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17787 Do not report category afferent coupling
17788
17789 @end table
17790
17791 @node Other gnatmetric Switches
17792 @subsection Other @code{gnatmetric} Switches
17793
17794 @noindent
17795 Additional @command{gnatmetric} switches are as follows:
17796
17797 @table @option
17798 @item ^-files @var{filename}^/FILES=@var{filename}^
17799 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17800 Take the argument source files from the specified file. This file should be an
17801 ordinary text file containing file names separated by spaces or
17802 line breaks. You can use this switch more then once in the same call to
17803 @command{gnatmetric}. You also can combine this switch with
17804 an explicit list of files.
17805
17806 @item ^-v^/VERBOSE^
17807 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17808 Verbose mode;
17809 @command{gnatmetric} generates version information and then
17810 a trace of sources being processed.
17811
17812 @item ^-dv^/DEBUG_OUTPUT^
17813 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17814 Debug mode;
17815 @command{gnatmetric} generates various messages useful to understand what
17816 happens during the metrics computation
17817
17818 @item ^-q^/QUIET^
17819 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17820 Quiet mode.
17821 @end table
17822
17823 @node Generate project-wide metrics
17824 @subsection Generate project-wide metrics
17825
17826 In order to compute metrics on all units of a given project, you can use
17827 the @command{gnat} driver along with the @option{-P} option:
17828 @smallexample
17829    gnat metric -Pproj
17830 @end smallexample
17831
17832 @noindent
17833 If the project @code{proj} depends upon other projects, you can compute
17834 the metrics on the project closure using the @option{-U} option:
17835 @smallexample
17836    gnat metric -Pproj -U
17837 @end smallexample
17838
17839 @noindent
17840 Finally, if not all the units are relevant to a particular main
17841 program in the project closure, you can generate metrics for the set
17842 of units needed to create a given main program (unit closure) using
17843 the @option{-U} option followed by the name of the main unit:
17844 @smallexample
17845    gnat metric -Pproj -U main
17846 @end smallexample
17847
17848
17849 @c ***********************************
17850 @node File Name Krunching Using gnatkr
17851 @chapter File Name Krunching Using @code{gnatkr}
17852 @findex gnatkr
17853
17854 @noindent
17855 This chapter discusses the method used by the compiler to shorten
17856 the default file names chosen for Ada units so that they do not
17857 exceed the maximum length permitted. It also describes the
17858 @code{gnatkr} utility that can be used to determine the result of
17859 applying this shortening.
17860 @menu
17861 * About gnatkr::
17862 * Using gnatkr::
17863 * Krunching Method::
17864 * Examples of gnatkr Usage::
17865 @end menu
17866
17867 @node About gnatkr
17868 @section About @code{gnatkr}
17869
17870 @noindent
17871 The default file naming rule in GNAT
17872 is that the file name must be derived from
17873 the unit name. The exact default rule is as follows:
17874 @itemize @bullet
17875 @item
17876 Take the unit name and replace all dots by hyphens.
17877 @item
17878 If such a replacement occurs in the
17879 second character position of a name, and the first character is
17880 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17881 then replace the dot by the character
17882 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17883 instead of a minus.
17884 @end itemize
17885 The reason for this exception is to avoid clashes
17886 with the standard names for children of System, Ada, Interfaces,
17887 and GNAT, which use the prefixes
17888 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17889 respectively.
17890
17891 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17892 switch of the compiler activates a ``krunching''
17893 circuit that limits file names to nn characters (where nn is a decimal
17894 integer). For example, using OpenVMS,
17895 where the maximum file name length is
17896 39, the value of nn is usually set to 39, but if you want to generate
17897 a set of files that would be usable if ported to a system with some
17898 different maximum file length, then a different value can be specified.
17899 The default value of 39 for OpenVMS need not be specified.
17900
17901 The @code{gnatkr} utility can be used to determine the krunched name for
17902 a given file, when krunched to a specified maximum length.
17903
17904 @node Using gnatkr
17905 @section Using @code{gnatkr}
17906
17907 @noindent
17908 The @code{gnatkr} command has the form
17909
17910 @ifclear vms
17911 @smallexample
17912 $ gnatkr @var{name} @ovar{length}
17913 @end smallexample
17914 @end ifclear
17915
17916 @ifset vms
17917 @smallexample
17918 $ gnatkr @var{name} /COUNT=nn
17919 @end smallexample
17920 @end ifset
17921
17922 @noindent
17923 @var{name} is the uncrunched file name, derived from the name of the unit
17924 in the standard manner described in the previous section (i.e., in particular
17925 all dots are replaced by hyphens). The file name may or may not have an
17926 extension (defined as a suffix of the form period followed by arbitrary
17927 characters other than period). If an extension is present then it will
17928 be preserved in the output. For example, when krunching @file{hellofile.ads}
17929 to eight characters, the result will be hellofil.ads.
17930
17931 Note: for compatibility with previous versions of @code{gnatkr} dots may
17932 appear in the name instead of hyphens, but the last dot will always be
17933 taken as the start of an extension. So if @code{gnatkr} is given an argument
17934 such as @file{Hello.World.adb} it will be treated exactly as if the first
17935 period had been a hyphen, and for example krunching to eight characters
17936 gives the result @file{hellworl.adb}.
17937
17938 Note that the result is always all lower case (except on OpenVMS where it is
17939 all upper case). Characters of the other case are folded as required.
17940
17941 @var{length} represents the length of the krunched name. The default
17942 when no argument is given is ^8^39^ characters. A length of zero stands for
17943 unlimited, in other words do not chop except for system files where the
17944 implied crunching length is always eight characters.
17945
17946 @noindent
17947 The output is the krunched name. The output has an extension only if the
17948 original argument was a file name with an extension.
17949
17950 @node Krunching Method
17951 @section Krunching Method
17952
17953 @noindent
17954 The initial file name is determined by the name of the unit that the file
17955 contains. The name is formed by taking the full expanded name of the
17956 unit and replacing the separating dots with hyphens and
17957 using ^lowercase^uppercase^
17958 for all letters, except that a hyphen in the second character position is
17959 replaced by a ^tilde^dollar sign^ if the first character is
17960 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17961 The extension is @code{.ads} for a
17962 spec and @code{.adb} for a body.
17963 Krunching does not affect the extension, but the file name is shortened to
17964 the specified length by following these rules:
17965
17966 @itemize @bullet
17967 @item
17968 The name is divided into segments separated by hyphens, tildes or
17969 underscores and all hyphens, tildes, and underscores are
17970 eliminated. If this leaves the name short enough, we are done.
17971
17972 @item
17973 If the name is too long, the longest segment is located (left-most
17974 if there are two of equal length), and shortened by dropping
17975 its last character. This is repeated until the name is short enough.
17976
17977 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17978 to fit the name into 8 characters as required by some operating systems.
17979
17980 @smallexample
17981 our-strings-wide_fixed 22
17982 our strings wide fixed 19
17983 our string  wide fixed 18
17984 our strin   wide fixed 17
17985 our stri    wide fixed 16
17986 our stri    wide fixe  15
17987 our str     wide fixe  14
17988 our str     wid  fixe  13
17989 our str     wid  fix   12
17990 ou  str     wid  fix   11
17991 ou  st      wid  fix   10
17992 ou  st      wi   fix   9
17993 ou  st      wi   fi    8
17994 Final file name: oustwifi.adb
17995 @end smallexample
17996
17997 @item
17998 The file names for all predefined units are always krunched to eight
17999 characters. The krunching of these predefined units uses the following
18000 special prefix replacements:
18001
18002 @table @file
18003 @item ada-
18004 replaced by @file{^a^A^-}
18005
18006 @item gnat-
18007 replaced by @file{^g^G^-}
18008
18009 @item interfaces-
18010 replaced by @file{^i^I^-}
18011
18012 @item system-
18013 replaced by @file{^s^S^-}
18014 @end table
18015
18016 These system files have a hyphen in the second character position. That
18017 is why normal user files replace such a character with a
18018 ^tilde^dollar sign^, to
18019 avoid confusion with system file names.
18020
18021 As an example of this special rule, consider
18022 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18023
18024 @smallexample
18025 ada-strings-wide_fixed 22
18026 a-  strings wide fixed 18
18027 a-  string  wide fixed 17
18028 a-  strin   wide fixed 16
18029 a-  stri    wide fixed 15
18030 a-  stri    wide fixe  14
18031 a-  str     wide fixe  13
18032 a-  str     wid  fixe  12
18033 a-  str     wid  fix   11
18034 a-  st      wid  fix   10
18035 a-  st      wi   fix   9
18036 a-  st      wi   fi    8
18037 Final file name: a-stwifi.adb
18038 @end smallexample
18039 @end itemize
18040
18041 Of course no file shortening algorithm can guarantee uniqueness over all
18042 possible unit names, and if file name krunching is used then it is your
18043 responsibility to ensure that no name clashes occur. The utility
18044 program @code{gnatkr} is supplied for conveniently determining the
18045 krunched name of a file.
18046
18047 @node Examples of gnatkr Usage
18048 @section Examples of @code{gnatkr} Usage
18049
18050 @smallexample
18051 @iftex
18052 @leftskip=0cm
18053 @end iftex
18054 @ifclear vms
18055 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18056 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18057 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18058 $ gnatkr grandparent-parent-child     --> grparchi
18059 @end ifclear
18060 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18061 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18062 @end smallexample
18063
18064 @node Preprocessing Using gnatprep
18065 @chapter Preprocessing Using @code{gnatprep}
18066 @findex gnatprep
18067
18068 @noindent
18069 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18070 preprocessing.
18071 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18072 special GNAT features.
18073 For further discussion of conditional compilation in general, see
18074 @ref{Conditional Compilation}.
18075
18076 @menu
18077 * Preprocessing Symbols::
18078 * Using gnatprep::
18079 * Switches for gnatprep::
18080 * Form of Definitions File::
18081 * Form of Input Text for gnatprep::
18082 @end menu
18083
18084 @node Preprocessing Symbols
18085 @section Preprocessing Symbols
18086
18087 @noindent
18088 Preprocessing symbols are defined in definition files and referred to in
18089 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18090 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18091 all characters need to be in the ASCII set (no accented letters).
18092
18093 @node Using gnatprep
18094 @section Using @code{gnatprep}
18095
18096 @noindent
18097 To call @code{gnatprep} use
18098
18099 @smallexample
18100 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18101 @end smallexample
18102
18103 @noindent
18104 where
18105 @table @var
18106 @item switches
18107 is an optional sequence of switches as described in the next section.
18108
18109 @item infile
18110 is the full name of the input file, which is an Ada source
18111 file containing preprocessor directives.
18112
18113 @item outfile
18114 is the full name of the output file, which is an Ada source
18115 in standard Ada form. When used with GNAT, this file name will
18116 normally have an ads or adb suffix.
18117
18118 @item deffile
18119 is the full name of a text file containing definitions of
18120 preprocessing symbols to be referenced by the preprocessor. This argument is
18121 optional, and can be replaced by the use of the @option{-D} switch.
18122
18123 @end table
18124
18125 @node Switches for gnatprep
18126 @section Switches for @code{gnatprep}
18127
18128 @table @option
18129 @c !sort!
18130
18131 @item ^-b^/BLANK_LINES^
18132 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18133 Causes both preprocessor lines and the lines deleted by
18134 preprocessing to be replaced by blank lines in the output source file,
18135 preserving line numbers in the output file.
18136
18137 @item ^-c^/COMMENTS^
18138 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18139 Causes both preprocessor lines and the lines deleted
18140 by preprocessing to be retained in the output source as comments marked
18141 with the special string @code{"--! "}. This option will result in line numbers
18142 being preserved in the output file.
18143
18144 @item ^-C^/REPLACE_IN_COMMENTS^
18145 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18146 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18147 If this option is specified, then comments are scanned and any $symbol
18148 substitutions performed as in program text. This is particularly useful
18149 when structured comments are used (e.g., when writing programs in the
18150 SPARK dialect of Ada). Note that this switch is not available when
18151 doing integrated preprocessing (it would be useless in this context
18152 since comments are ignored by the compiler in any case).
18153
18154 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18155 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18156 Defines a new preprocessing symbol, associated with value. If no value is given
18157 on the command line, then symbol is considered to be @code{True}. This switch
18158 can be used in place of a definition file.
18159
18160 @ifset vms
18161 @item /REMOVE
18162 @cindex @option{/REMOVE} (@command{gnatprep})
18163 This is the default setting which causes lines deleted by preprocessing
18164 to be entirely removed from the output file.
18165 @end ifset
18166
18167 @item ^-r^/REFERENCE^
18168 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18169 Causes a @code{Source_Reference} pragma to be generated that
18170 references the original input file, so that error messages will use
18171 the file name of this original file. The use of this switch implies
18172 that preprocessor lines are not to be removed from the file, so its
18173 use will force @option{^-b^/BLANK_LINES^} mode if
18174 @option{^-c^/COMMENTS^}
18175 has not been specified explicitly.
18176
18177 Note that if the file to be preprocessed contains multiple units, then
18178 it will be necessary to @code{gnatchop} the output file from
18179 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18180 in the preprocessed file, it will be respected by
18181 @code{gnatchop ^-r^/REFERENCE^}
18182 so that the final chopped files will correctly refer to the original
18183 input source file for @code{gnatprep}.
18184
18185 @item ^-s^/SYMBOLS^
18186 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18187 Causes a sorted list of symbol names and values to be
18188 listed on the standard output file.
18189
18190 @item ^-u^/UNDEFINED^
18191 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18192 Causes undefined symbols to be treated as having the value FALSE in the context
18193 of a preprocessor test. In the absence of this option, an undefined symbol in
18194 a @code{#if} or @code{#elsif} test will be treated as an error.
18195
18196 @end table
18197
18198 @ifclear vms
18199 @noindent
18200 Note: if neither @option{-b} nor @option{-c} is present,
18201 then preprocessor lines and
18202 deleted lines are completely removed from the output, unless -r is
18203 specified, in which case -b is assumed.
18204 @end ifclear
18205
18206 @node Form of Definitions File
18207 @section Form of Definitions File
18208
18209 @noindent
18210 The definitions file contains lines of the form
18211
18212 @smallexample
18213 symbol := value
18214 @end smallexample
18215
18216 @noindent
18217 where symbol is a preprocessing symbol, and value is one of the following:
18218
18219 @itemize @bullet
18220 @item
18221 Empty, corresponding to a null substitution
18222 @item
18223 A string literal using normal Ada syntax
18224 @item
18225 Any sequence of characters from the set
18226 (letters, digits, period, underline).
18227 @end itemize
18228
18229 @noindent
18230 Comment lines may also appear in the definitions file, starting with
18231 the usual @code{--},
18232 and comments may be added to the definitions lines.
18233
18234 @node Form of Input Text for gnatprep
18235 @section Form of Input Text for @code{gnatprep}
18236
18237 @noindent
18238 The input text may contain preprocessor conditional inclusion lines,
18239 as well as general symbol substitution sequences.
18240
18241 The preprocessor conditional inclusion commands have the form
18242
18243 @smallexample
18244 @group
18245 @cartouche
18246 #if @i{expression} @r{[}then@r{]}
18247    lines
18248 #elsif @i{expression} @r{[}then@r{]}
18249    lines
18250 #elsif @i{expression} @r{[}then@r{]}
18251    lines
18252 @dots{}
18253 #else
18254    lines
18255 #end if;
18256 @end cartouche
18257 @end group
18258 @end smallexample
18259
18260 @noindent
18261 In this example, @i{expression} is defined by the following grammar:
18262 @smallexample
18263 @i{expression} ::=  <symbol>
18264 @i{expression} ::=  <symbol> = "<value>"
18265 @i{expression} ::=  <symbol> = <symbol>
18266 @i{expression} ::=  <symbol> 'Defined
18267 @i{expression} ::=  not @i{expression}
18268 @i{expression} ::=  @i{expression} and @i{expression}
18269 @i{expression} ::=  @i{expression} or @i{expression}
18270 @i{expression} ::=  @i{expression} and then @i{expression}
18271 @i{expression} ::=  @i{expression} or else @i{expression}
18272 @i{expression} ::=  ( @i{expression} )
18273 @end smallexample
18274
18275 The following restriction exists: it is not allowed to have "and" or "or"
18276 following "not" in the same expression without parentheses. For example, this
18277 is not allowed:
18278
18279 @smallexample
18280    not X or Y
18281 @end smallexample
18282
18283 This should be one of the following:
18284
18285 @smallexample
18286    (not X) or Y
18287    not (X or Y)
18288 @end smallexample
18289
18290 @noindent
18291 For the first test (@i{expression} ::= <symbol>) the symbol must have
18292 either the value true or false, that is to say the right-hand of the
18293 symbol definition must be one of the (case-insensitive) literals
18294 @code{True} or @code{False}. If the value is true, then the
18295 corresponding lines are included, and if the value is false, they are
18296 excluded.
18297
18298 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18299 the symbol has been defined in the definition file or by a @option{-D}
18300 switch on the command line. Otherwise, the test is false.
18301
18302 The equality tests are case insensitive, as are all the preprocessor lines.
18303
18304 If the symbol referenced is not defined in the symbol definitions file,
18305 then the effect depends on whether or not switch @option{-u}
18306 is specified. If so, then the symbol is treated as if it had the value
18307 false and the test fails. If this switch is not specified, then
18308 it is an error to reference an undefined symbol. It is also an error to
18309 reference a symbol that is defined with a value other than @code{True}
18310 or @code{False}.
18311
18312 The use of the @code{not} operator inverts the sense of this logical test.
18313 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18314 operators, without parentheses. For example, "if not X or Y then" is not
18315 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18316
18317 The @code{then} keyword is optional as shown
18318
18319 The @code{#} must be the first non-blank character on a line, but
18320 otherwise the format is free form. Spaces or tabs may appear between
18321 the @code{#} and the keyword. The keywords and the symbols are case
18322 insensitive as in normal Ada code. Comments may be used on a
18323 preprocessor line, but other than that, no other tokens may appear on a
18324 preprocessor line. Any number of @code{elsif} clauses can be present,
18325 including none at all. The @code{else} is optional, as in Ada.
18326
18327 The @code{#} marking the start of a preprocessor line must be the first
18328 non-blank character on the line, i.e., it must be preceded only by
18329 spaces or horizontal tabs.
18330
18331 Symbol substitution outside of preprocessor lines is obtained by using
18332 the sequence
18333
18334 @smallexample
18335 $symbol
18336 @end smallexample
18337
18338 @noindent
18339 anywhere within a source line, except in a comment or within a
18340 string literal. The identifier
18341 following the @code{$} must match one of the symbols defined in the symbol
18342 definition file, and the result is to substitute the value of the
18343 symbol in place of @code{$symbol} in the output file.
18344
18345 Note that although the substitution of strings within a string literal
18346 is not possible, it is possible to have a symbol whose defined value is
18347 a string literal. So instead of setting XYZ to @code{hello} and writing:
18348
18349 @smallexample
18350 Header : String := "$XYZ";
18351 @end smallexample
18352
18353 @noindent
18354 you should set XYZ to @code{"hello"} and write:
18355
18356 @smallexample
18357 Header : String := $XYZ;
18358 @end smallexample
18359
18360 @noindent
18361 and then the substitution will occur as desired.
18362
18363 @ifset vms
18364 @node The GNAT Run-Time Library Builder gnatlbr
18365 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18366 @findex gnatlbr
18367 @cindex Library builder
18368
18369 @noindent
18370 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18371 supplied configuration pragmas.
18372
18373 @menu
18374 * Running gnatlbr::
18375 * Switches for gnatlbr::
18376 * Examples of gnatlbr Usage::
18377 @end menu
18378
18379 @node Running gnatlbr
18380 @section Running @code{gnatlbr}
18381
18382 @noindent
18383 The @code{gnatlbr} command has the form
18384
18385 @smallexample
18386 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18387 @end smallexample
18388
18389 @node Switches for gnatlbr
18390 @section Switches for @code{gnatlbr}
18391
18392 @noindent
18393 @code{gnatlbr} recognizes the following switches:
18394
18395 @table @option
18396 @c !sort!
18397 @item /CREATE=directory
18398 @cindex @code{/CREATE} (@code{gnatlbr})
18399 Create the new run-time library in the specified directory.
18400
18401 @item /SET=directory
18402 @cindex @code{/SET} (@code{gnatlbr})
18403 Make the library in the specified directory the current run-time library.
18404
18405 @item /DELETE=directory
18406 @cindex @code{/DELETE} (@code{gnatlbr})
18407 Delete the run-time library in the specified directory.
18408
18409 @item /CONFIG=file
18410 @cindex @code{/CONFIG} (@code{gnatlbr})
18411 With /CREATE: Use the configuration pragmas in the specified file when
18412 building the library.
18413
18414 With /SET: Use the configuration pragmas in the specified file when
18415 compiling.
18416
18417 @end table
18418
18419 @node Examples of gnatlbr Usage
18420 @section Example of @code{gnatlbr} Usage
18421
18422 @smallexample
18423 Contents of VAXFLOAT.ADC:
18424 pragma Float_Representation (VAX_Float);
18425
18426 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18427
18428 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18429
18430 @end smallexample
18431 @end ifset
18432
18433 @node The GNAT Library Browser gnatls
18434 @chapter The GNAT Library Browser @code{gnatls}
18435 @findex gnatls
18436 @cindex Library browser
18437
18438 @noindent
18439 @code{gnatls} is a tool that outputs information about compiled
18440 units. It gives the relationship between objects, unit names and source
18441 files. It can also be used to check the source dependencies of a unit
18442 as well as various characteristics.
18443
18444 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18445 driver (see @ref{The GNAT Driver and Project Files}).
18446
18447 @menu
18448 * Running gnatls::
18449 * Switches for gnatls::
18450 * Examples of gnatls Usage::
18451 @end menu
18452
18453 @node Running gnatls
18454 @section Running @code{gnatls}
18455
18456 @noindent
18457 The @code{gnatls} command has the form
18458
18459 @smallexample
18460 $ gnatls switches @var{object_or_ali_file}
18461 @end smallexample
18462
18463 @noindent
18464 The main argument is the list of object or @file{ali} files
18465 (@pxref{The Ada Library Information Files})
18466 for which information is requested.
18467
18468 In normal mode, without additional option, @code{gnatls} produces a
18469 four-column listing. Each line represents information for a specific
18470 object. The first column gives the full path of the object, the second
18471 column gives the name of the principal unit in this object, the third
18472 column gives the status of the source and the fourth column gives the
18473 full path of the source representing this unit.
18474 Here is a simple example of use:
18475
18476 @smallexample
18477 $ gnatls *.o
18478 ^./^[]^demo1.o            demo1            DIF demo1.adb
18479 ^./^[]^demo2.o            demo2             OK demo2.adb
18480 ^./^[]^hello.o            h1                OK hello.adb
18481 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18482 ^./^[]^instr.o            instr             OK instr.adb
18483 ^./^[]^tef.o              tef              DIF tef.adb
18484 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18485 ^./^[]^tgef.o             tgef             DIF tgef.adb
18486 @end smallexample
18487
18488 @noindent
18489 The first line can be interpreted as follows: the main unit which is
18490 contained in
18491 object file @file{demo1.o} is demo1, whose main source is in
18492 @file{demo1.adb}. Furthermore, the version of the source used for the
18493 compilation of demo1 has been modified (DIF). Each source file has a status
18494 qualifier which can be:
18495
18496 @table @code
18497 @item OK (unchanged)
18498 The version of the source file used for the compilation of the
18499 specified unit corresponds exactly to the actual source file.
18500
18501 @item MOK (slightly modified)
18502 The version of the source file used for the compilation of the
18503 specified unit differs from the actual source file but not enough to
18504 require recompilation. If you use gnatmake with the qualifier
18505 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18506 MOK will not be recompiled.
18507
18508 @item DIF (modified)
18509 No version of the source found on the path corresponds to the source
18510 used to build this object.
18511
18512 @item ??? (file not found)
18513 No source file was found for this unit.
18514
18515 @item HID (hidden,  unchanged version not first on PATH)
18516 The version of the source that corresponds exactly to the source used
18517 for compilation has been found on the path but it is hidden by another
18518 version of the same source that has been modified.
18519
18520 @end table
18521
18522 @node Switches for gnatls
18523 @section Switches for @code{gnatls}
18524
18525 @noindent
18526 @code{gnatls} recognizes the following switches:
18527
18528 @table @option
18529 @c !sort!
18530 @cindex @option{--version} @command{gnatls}
18531 Display Copyright and version, then exit disregarding all other options.
18532
18533 @item --help
18534 @cindex @option{--help} @command{gnatls}
18535 If @option{--version} was not used, display usage, then exit disregarding
18536 all other options.
18537
18538 @item ^-a^/ALL_UNITS^
18539 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18540 Consider all units, including those of the predefined Ada library.
18541 Especially useful with @option{^-d^/DEPENDENCIES^}.
18542
18543 @item ^-d^/DEPENDENCIES^
18544 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18545 List sources from which specified units depend on.
18546
18547 @item ^-h^/OUTPUT=OPTIONS^
18548 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18549 Output the list of options.
18550
18551 @item ^-o^/OUTPUT=OBJECTS^
18552 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18553 Only output information about object files.
18554
18555 @item ^-s^/OUTPUT=SOURCES^
18556 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18557 Only output information about source files.
18558
18559 @item ^-u^/OUTPUT=UNITS^
18560 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18561 Only output information about compilation units.
18562
18563 @item ^-files^/FILES^=@var{file}
18564 @cindex @option{^-files^/FILES^} (@code{gnatls})
18565 Take as arguments the files listed in text file @var{file}.
18566 Text file @var{file} may contain empty lines that are ignored.
18567 Each nonempty line should contain the name of an existing file.
18568 Several such switches may be specified simultaneously.
18569
18570 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18571 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18572 @itemx ^-I^/SEARCH=^@var{dir}
18573 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18574 @itemx -nostdinc
18575 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18576 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18577 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18578 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18579 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18580 flags (@pxref{Switches for gnatmake}).
18581
18582 @item --RTS=@var{rts-path}
18583 @cindex @option{--RTS} (@code{gnatls})
18584 Specifies the default location of the runtime library. Same meaning as the
18585 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18586
18587 @item ^-v^/OUTPUT=VERBOSE^
18588 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18589 Verbose mode. Output the complete source, object and project paths. Do not use
18590 the default column layout but instead use long format giving as much as
18591 information possible on each requested units, including special
18592 characteristics such as:
18593
18594 @table @code
18595 @item  Preelaborable
18596 The unit is preelaborable in the Ada sense.
18597
18598 @item No_Elab_Code
18599 No elaboration code has been produced by the compiler for this unit.
18600
18601 @item Pure
18602 The unit is pure in the Ada sense.
18603
18604 @item Elaborate_Body
18605 The unit contains a pragma Elaborate_Body.
18606
18607 @item Remote_Types
18608 The unit contains a pragma Remote_Types.
18609
18610 @item Shared_Passive
18611 The unit contains a pragma Shared_Passive.
18612
18613 @item Predefined
18614 This unit is part of the predefined environment and cannot be modified
18615 by the user.
18616
18617 @item Remote_Call_Interface
18618 The unit contains a pragma Remote_Call_Interface.
18619
18620 @end table
18621
18622 @end table
18623
18624 @node Examples of gnatls Usage
18625 @section Example of @code{gnatls} Usage
18626 @ifclear vms
18627
18628 @noindent
18629 Example of using the verbose switch. Note how the source and
18630 object paths are affected by the -I switch.
18631
18632 @smallexample
18633 $ gnatls -v -I.. demo1.o
18634
18635 GNATLS 5.03w (20041123-34)
18636 Copyright 1997-2004 Free Software Foundation, Inc.
18637
18638 Source Search Path:
18639    <Current_Directory>
18640    ../
18641    /home/comar/local/adainclude/
18642
18643 Object Search Path:
18644    <Current_Directory>
18645    ../
18646    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18647
18648 Project Search Path:
18649    <Current_Directory>
18650    /home/comar/local/lib/gnat/
18651
18652 ./demo1.o
18653    Unit =>
18654      Name   => demo1
18655      Kind   => subprogram body
18656      Flags  => No_Elab_Code
18657      Source => demo1.adb    modified
18658 @end smallexample
18659
18660 @noindent
18661 The following is an example of use of the dependency list.
18662 Note the use of the -s switch
18663 which gives a straight list of source files. This can be useful for
18664 building specialized scripts.
18665
18666 @smallexample
18667 $ gnatls -d demo2.o
18668 ./demo2.o   demo2        OK demo2.adb
18669                          OK gen_list.ads
18670                          OK gen_list.adb
18671                          OK instr.ads
18672                          OK instr-child.ads
18673
18674 $ gnatls -d -s -a demo1.o
18675 demo1.adb
18676 /home/comar/local/adainclude/ada.ads
18677 /home/comar/local/adainclude/a-finali.ads
18678 /home/comar/local/adainclude/a-filico.ads
18679 /home/comar/local/adainclude/a-stream.ads
18680 /home/comar/local/adainclude/a-tags.ads
18681 gen_list.ads
18682 gen_list.adb
18683 /home/comar/local/adainclude/gnat.ads
18684 /home/comar/local/adainclude/g-io.ads
18685 instr.ads
18686 /home/comar/local/adainclude/system.ads
18687 /home/comar/local/adainclude/s-exctab.ads
18688 /home/comar/local/adainclude/s-finimp.ads
18689 /home/comar/local/adainclude/s-finroo.ads
18690 /home/comar/local/adainclude/s-secsta.ads
18691 /home/comar/local/adainclude/s-stalib.ads
18692 /home/comar/local/adainclude/s-stoele.ads
18693 /home/comar/local/adainclude/s-stratt.ads
18694 /home/comar/local/adainclude/s-tasoli.ads
18695 /home/comar/local/adainclude/s-unstyp.ads
18696 /home/comar/local/adainclude/unchconv.ads
18697 @end smallexample
18698 @end ifclear
18699
18700 @ifset vms
18701 @smallexample
18702 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18703
18704 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18705 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18706 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18707 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18708 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18709 demo1.adb
18710 gen_list.ads
18711 gen_list.adb
18712 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18713 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18714 instr.ads
18715 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18716 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18717 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18718 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18719 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18720 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18721 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18722 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18723 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18724 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18725 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18726 @end smallexample
18727 @end ifset
18728
18729 @node Cleaning Up Using gnatclean
18730 @chapter Cleaning Up Using @code{gnatclean}
18731 @findex gnatclean
18732 @cindex Cleaning tool
18733
18734 @noindent
18735 @code{gnatclean} is a tool that allows the deletion of files produced by the
18736 compiler, binder and linker, including ALI files, object files, tree files,
18737 expanded source files, library files, interface copy source files, binder
18738 generated files and executable files.
18739
18740 @menu
18741 * Running gnatclean::
18742 * Switches for gnatclean::
18743 @c * Examples of gnatclean Usage::
18744 @end menu
18745
18746 @node Running gnatclean
18747 @section Running @code{gnatclean}
18748
18749 @noindent
18750 The @code{gnatclean} command has the form:
18751
18752 @smallexample
18753 $ gnatclean switches @var{names}
18754 @end smallexample
18755
18756 @noindent
18757 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18758 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18759 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18760
18761 @noindent
18762 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18763 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18764 the linker. In informative-only mode, specified by switch
18765 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18766 normal mode is listed, but no file is actually deleted.
18767
18768 @node Switches for gnatclean
18769 @section Switches for @code{gnatclean}
18770
18771 @noindent
18772 @code{gnatclean} recognizes the following switches:
18773
18774 @table @option
18775 @c !sort!
18776 @cindex @option{--version} @command{gnatclean}
18777 Display Copyright and version, then exit disregarding all other options.
18778
18779 @item --help
18780 @cindex @option{--help} @command{gnatclean}
18781 If @option{--version} was not used, display usage, then exit disregarding
18782 all other options.
18783
18784 @item ^-c^/COMPILER_FILES_ONLY^
18785 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18786 Only attempt to delete the files produced by the compiler, not those produced
18787 by the binder or the linker. The files that are not to be deleted are library
18788 files, interface copy files, binder generated files and executable files.
18789
18790 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18791 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18792 Indicate that ALI and object files should normally be found in directory
18793 @var{dir}.
18794
18795 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18796 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18797 When using project files, if some errors or warnings are detected during
18798 parsing and verbose mode is not in effect (no use of switch
18799 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18800 file, rather than its simple file name.
18801
18802 @item ^-h^/HELP^
18803 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18804 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18805
18806 @item ^-n^/NODELETE^
18807 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18808 Informative-only mode. Do not delete any files. Output the list of the files
18809 that would have been deleted if this switch was not specified.
18810
18811 @item ^-P^/PROJECT_FILE=^@var{project}
18812 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18813 Use project file @var{project}. Only one such switch can be used.
18814 When cleaning a project file, the files produced by the compilation of the
18815 immediate sources or inherited sources of the project files are to be
18816 deleted. This is not depending on the presence or not of executable names
18817 on the command line.
18818
18819 @item ^-q^/QUIET^
18820 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18821 Quiet output. If there are no errors, do not output anything, except in
18822 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18823 (switch ^-n^/NODELETE^).
18824
18825 @item ^-r^/RECURSIVE^
18826 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18827 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18828 clean all imported and extended project files, recursively. If this switch
18829 is not specified, only the files related to the main project file are to be
18830 deleted. This switch has no effect if no project file is specified.
18831
18832 @item ^-v^/VERBOSE^
18833 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18834 Verbose mode.
18835
18836 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18837 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18838 Indicates the verbosity of the parsing of GNAT project files.
18839 @xref{Switches Related to Project Files}.
18840
18841 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18842 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18843 Indicates that external variable @var{name} has the value @var{value}.
18844 The Project Manager will use this value for occurrences of
18845 @code{external(name)} when parsing the project file.
18846 @xref{Switches Related to Project Files}.
18847
18848 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18849 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18850 When searching for ALI and object files, look in directory
18851 @var{dir}.
18852
18853 @item ^-I^/SEARCH=^@var{dir}
18854 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18855 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18856
18857 @item ^-I-^/NOCURRENT_DIRECTORY^
18858 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18859 @cindex Source files, suppressing search
18860 Do not look for ALI or object files in the directory
18861 where @code{gnatclean} was invoked.
18862
18863 @end table
18864
18865 @c @node Examples of gnatclean Usage
18866 @c @section Examples of @code{gnatclean} Usage
18867
18868 @ifclear vms
18869 @node GNAT and Libraries
18870 @chapter GNAT and Libraries
18871 @cindex Library, building, installing, using
18872
18873 @noindent
18874 This chapter describes how to build and use libraries with GNAT, and also shows
18875 how to recompile the GNAT run-time library. You should be familiar with the
18876 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18877 chapter.
18878
18879 @menu
18880 * Introduction to Libraries in GNAT::
18881 * General Ada Libraries::
18882 * Stand-alone Ada Libraries::
18883 * Rebuilding the GNAT Run-Time Library::
18884 @end menu
18885
18886 @node Introduction to Libraries in GNAT
18887 @section Introduction to Libraries in GNAT
18888
18889 @noindent
18890 A library is, conceptually, a collection of objects which does not have its
18891 own main thread of execution, but rather provides certain services to the
18892 applications that use it. A library can be either statically linked with the
18893 application, in which case its code is directly included in the application,
18894 or, on platforms that support it, be dynamically linked, in which case
18895 its code is shared by all applications making use of this library.
18896
18897 GNAT supports both types of libraries.
18898 In the static case, the compiled code can be provided in different ways. The
18899 simplest approach is to provide directly the set of objects resulting from
18900 compilation of the library source files. Alternatively, you can group the
18901 objects into an archive using whatever commands are provided by the operating
18902 system. For the latter case, the objects are grouped into a shared library.
18903
18904 In the GNAT environment, a library has three types of components:
18905 @itemize @bullet
18906 @item
18907 Source files.
18908 @item
18909 @file{ALI} files.
18910 @xref{The Ada Library Information Files}.
18911 @item
18912 Object files, an archive or a shared library.
18913 @end itemize
18914
18915 @noindent
18916 A GNAT library may expose all its source files, which is useful for
18917 documentation purposes. Alternatively, it may expose only the units needed by
18918 an external user to make use of the library. That is to say, the specs
18919 reflecting the library services along with all the units needed to compile
18920 those specs, which can include generic bodies or any body implementing an
18921 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18922 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18923
18924 All compilation units comprising an application, including those in a library,
18925 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18926 computes the elaboration order from the @file{ALI} files and this is why they
18927 constitute a mandatory part of GNAT libraries.
18928 @emph{Stand-alone libraries} are the exception to this rule because a specific
18929 library elaboration routine is produced independently of the application(s)
18930 using the library.
18931
18932 @node General Ada Libraries
18933 @section General Ada Libraries
18934
18935 @menu
18936 * Building a library::
18937 * Installing a library::
18938 * Using a library::
18939 @end menu
18940
18941 @node Building a library
18942 @subsection Building a library
18943
18944 @noindent
18945 The easiest way to build a library is to use the Project Manager,
18946 which supports a special type of project called a @emph{Library Project}
18947 (@pxref{Library Projects}).
18948
18949 A project is considered a library project, when two project-level attributes
18950 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18951 control different aspects of library configuration, additional optional
18952 project-level attributes can be specified:
18953 @table @code
18954 @item Library_Kind
18955 This attribute controls whether the library is to be static or dynamic
18956
18957 @item Library_Version
18958 This attribute specifies the library version; this value is used
18959 during dynamic linking of shared libraries to determine if the currently
18960 installed versions of the binaries are compatible.
18961
18962 @item Library_Options
18963 @item Library_GCC
18964 These attributes specify additional low-level options to be used during
18965 library generation, and redefine the actual application used to generate
18966 library.
18967 @end table
18968
18969 @noindent
18970 The GNAT Project Manager takes full care of the library maintenance task,
18971 including recompilation of the source files for which objects do not exist
18972 or are not up to date, assembly of the library archive, and installation of
18973 the library (i.e., copying associated source, object and @file{ALI} files
18974 to the specified location).
18975
18976 Here is a simple library project file:
18977 @smallexample @c ada
18978 project My_Lib is
18979    for Source_Dirs use ("src1", "src2");
18980    for Object_Dir use "obj";
18981    for Library_Name use "mylib";
18982    for Library_Dir use "lib";
18983    for Library_Kind use "dynamic";
18984 end My_lib;
18985 @end smallexample
18986
18987 @noindent
18988 and the compilation command to build and install the library:
18989
18990 @smallexample @c ada
18991   $ gnatmake -Pmy_lib
18992 @end smallexample
18993
18994 @noindent
18995 It is not entirely trivial to perform manually all the steps required to
18996 produce a library. We recommend that you use the GNAT Project Manager
18997 for this task. In special cases where this is not desired, the necessary
18998 steps are discussed below.
18999
19000 There are various possibilities for compiling the units that make up the
19001 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19002 with a conventional script. For simple libraries, it is also possible to create
19003 a dummy main program which depends upon all the packages that comprise the
19004 interface of the library. This dummy main program can then be given to
19005 @command{gnatmake}, which will ensure that all necessary objects are built.
19006
19007 After this task is accomplished, you should follow the standard procedure
19008 of the underlying operating system to produce the static or shared library.
19009
19010 Here is an example of such a dummy program:
19011 @smallexample @c ada
19012 @group
19013 with My_Lib.Service1;
19014 with My_Lib.Service2;
19015 with My_Lib.Service3;
19016 procedure My_Lib_Dummy is
19017 begin
19018    null;
19019 end;
19020 @end group
19021 @end smallexample
19022
19023 @noindent
19024 Here are the generic commands that will build an archive or a shared library.
19025
19026 @smallexample
19027 # compiling the library
19028 $ gnatmake -c my_lib_dummy.adb
19029
19030 # we don't need the dummy object itself
19031 $ rm my_lib_dummy.o my_lib_dummy.ali
19032
19033 # create an archive with the remaining objects
19034 $ ar rc libmy_lib.a *.o
19035 # some systems may require "ranlib" to be run as well
19036
19037 # or create a shared library
19038 $ gcc -shared -o libmy_lib.so *.o
19039 # some systems may require the code to have been compiled with -fPIC
19040
19041 # remove the object files that are now in the library
19042 $ rm *.o
19043
19044 # Make the ALI files read-only so that gnatmake will not try to
19045 # regenerate the objects that are in the library
19046 $ chmod -w *.ali
19047 @end smallexample
19048
19049 @noindent
19050 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19051 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19052 be accessed by the directive @option{-l@var{xxx}} at link time.
19053
19054 @node Installing a library
19055 @subsection Installing a library
19056 @cindex @code{ADA_PROJECT_PATH}
19057 @cindex @code{GPR_PROJECT_PATH}
19058
19059 @noindent
19060 If you use project files, library installation is part of the library build
19061 process. Thus no further action is needed in order to make use of the
19062 libraries that are built as part of the general application build. A usable
19063 version of the library is installed in the directory specified by the
19064 @code{Library_Dir} attribute of the library project file.
19065
19066 You may want to install a library in a context different from where the library
19067 is built. This situation arises with third party suppliers, who may want
19068 to distribute a library in binary form where the user is not expected to be
19069 able to recompile the library. The simplest option in this case is to provide
19070 a project file slightly different from the one used to build the library, by
19071 using the @code{externally_built} attribute. For instance, the project
19072 file used to build the library in the previous section can be changed into the
19073 following one when the library is installed:
19074
19075 @smallexample @c projectfile
19076 project My_Lib is
19077    for Source_Dirs use ("src1", "src2");
19078    for Library_Name use "mylib";
19079    for Library_Dir use "lib";
19080    for Library_Kind use "dynamic";
19081    for Externally_Built use "true";
19082 end My_lib;
19083 @end smallexample
19084
19085 @noindent
19086 This project file assumes that the directories @file{src1},
19087 @file{src2}, and @file{lib} exist in
19088 the directory containing the project file. The @code{externally_built}
19089 attribute makes it clear to the GNAT builder that it should not attempt to
19090 recompile any of the units from this library. It allows the library provider to
19091 restrict the source set to the minimum necessary for clients to make use of the
19092 library as described in the first section of this chapter. It is the
19093 responsibility of the library provider to install the necessary sources, ALI
19094 files and libraries in the directories mentioned in the project file. For
19095 convenience, the user's library project file should be installed in a location
19096 that will be searched automatically by the GNAT
19097 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19098 environment variable (@pxref{Importing Projects}), and also the default GNAT
19099 library location that can be queried with @command{gnatls -v} and is usually of
19100 the form $gnat_install_root/lib/gnat.
19101
19102 When project files are not an option, it is also possible, but not recommended,
19103 to install the library so that the sources needed to use the library are on the
19104 Ada source path and the ALI files & libraries be on the Ada Object path (see
19105 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19106 administrator can place general-purpose libraries in the default compiler
19107 paths, by specifying the libraries' location in the configuration files
19108 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19109 must be located in the GNAT installation tree at the same place as the gcc spec
19110 file. The location of the gcc spec file can be determined as follows:
19111 @smallexample
19112 $ gcc -v
19113 @end smallexample
19114
19115 @noindent
19116 The configuration files mentioned above have a simple format: each line
19117 must contain one unique directory name.
19118 Those names are added to the corresponding path
19119 in their order of appearance in the file. The names can be either absolute
19120 or relative; in the latter case, they are relative to where theses files
19121 are located.
19122
19123 The files @file{ada_source_path} and @file{ada_object_path} might not be
19124 present in a
19125 GNAT installation, in which case, GNAT will look for its run-time library in
19126 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19127 objects and @file{ALI} files). When the files exist, the compiler does not
19128 look in @file{adainclude} and @file{adalib}, and thus the
19129 @file{ada_source_path} file
19130 must contain the location for the GNAT run-time sources (which can simply
19131 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19132 contain the location for the GNAT run-time objects (which can simply
19133 be @file{adalib}).
19134
19135 You can also specify a new default path to the run-time library at compilation
19136 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19137 the run-time library you want your program to be compiled with. This switch is
19138 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19139 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19140
19141 It is possible to install a library before or after the standard GNAT
19142 library, by reordering the lines in the configuration files. In general, a
19143 library must be installed before the GNAT library if it redefines
19144 any part of it.
19145
19146 @node Using a library
19147 @subsection Using a library
19148
19149 @noindent Once again, the project facility greatly simplifies the use of
19150 libraries. In this context, using a library is just a matter of adding a
19151 @code{with} clause in the user project. For instance, to make use of the
19152 library @code{My_Lib} shown in examples in earlier sections, you can
19153 write:
19154
19155 @smallexample @c projectfile
19156 with "my_lib";
19157 project My_Proj is
19158   @dots{}
19159 end My_Proj;
19160 @end smallexample
19161
19162 Even if you have a third-party, non-Ada library, you can still use GNAT's
19163 Project Manager facility to provide a wrapper for it. For example, the
19164 following project, when @code{with}ed by your main project, will link with the
19165 third-party library @file{liba.a}:
19166
19167 @smallexample @c projectfile
19168 @group
19169 project Liba is
19170    for Externally_Built use "true";
19171    for Source_Files use ();
19172    for Library_Dir use "lib";
19173    for Library_Name use "a";
19174    for Library_Kind use "static";
19175 end Liba;
19176 @end group
19177 @end smallexample
19178 This is an alternative to the use of @code{pragma Linker_Options}. It is
19179 especially interesting in the context of systems with several interdependent
19180 static libraries where finding a proper linker order is not easy and best be
19181 left to the tools having visibility over project dependence information.
19182
19183 @noindent
19184 In order to use an Ada library manually, you need to make sure that this
19185 library is on both your source and object path
19186 (see @ref{Search Paths and the Run-Time Library (RTL)}
19187 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19188 in an archive or a shared library, you need to specify the desired
19189 library at link time.
19190
19191 For example, you can use the library @file{mylib} installed in
19192 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19193
19194 @smallexample
19195 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19196   -largs -lmy_lib
19197 @end smallexample
19198
19199 @noindent
19200 This can be expressed more simply:
19201 @smallexample
19202 $ gnatmake my_appl
19203 @end smallexample
19204 @noindent
19205 when the following conditions are met:
19206 @itemize @bullet
19207 @item
19208 @file{/dir/my_lib_src} has been added by the user to the environment
19209 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19210 @file{ada_source_path}
19211 @item
19212 @file{/dir/my_lib_obj} has been added by the user to the environment
19213 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19214 @file{ada_object_path}
19215 @item
19216 a pragma @code{Linker_Options} has been added to one of the sources.
19217 For example:
19218
19219 @smallexample @c ada
19220 pragma Linker_Options ("-lmy_lib");
19221 @end smallexample
19222 @end itemize
19223
19224 @node Stand-alone Ada Libraries
19225 @section Stand-alone Ada Libraries
19226 @cindex Stand-alone library, building, using
19227
19228 @menu
19229 * Introduction to Stand-alone Libraries::
19230 * Building a Stand-alone Library::
19231 * Creating a Stand-alone Library to be used in a non-Ada context::
19232 * Restrictions in Stand-alone Libraries::
19233 @end menu
19234
19235 @node Introduction to Stand-alone Libraries
19236 @subsection Introduction to Stand-alone Libraries
19237
19238 @noindent
19239 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19240 necessary code to
19241 elaborate the Ada units that are included in the library. In contrast with
19242 an ordinary library, which consists of all sources, objects and @file{ALI}
19243 files of the
19244 library, a SAL may specify a restricted subset of compilation units
19245 to serve as a library interface. In this case, the fully
19246 self-sufficient set of files will normally consist of an objects
19247 archive, the sources of interface units' specs, and the @file{ALI}
19248 files of interface units.
19249 If an interface spec contains a generic unit or an inlined subprogram,
19250 the body's
19251 source must also be provided; if the units that must be provided in the source
19252 form depend on other units, the source and @file{ALI} files of those must
19253 also be provided.
19254
19255 The main purpose of a SAL is to minimize the recompilation overhead of client
19256 applications when a new version of the library is installed. Specifically,
19257 if the interface sources have not changed, client applications do not need to
19258 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19259 version, controlled by @code{Library_Version} attribute, is not changed,
19260 then the clients do not need to be relinked.
19261
19262 SALs also allow the library providers to minimize the amount of library source
19263 text exposed to the clients.  Such ``information hiding'' might be useful or
19264 necessary for various reasons.
19265
19266 Stand-alone libraries are also well suited to be used in an executable whose
19267 main routine is not written in Ada.
19268
19269 @node Building a Stand-alone Library
19270 @subsection Building a Stand-alone Library
19271
19272 @noindent
19273 GNAT's Project facility provides a simple way of building and installing
19274 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19275 To be a Stand-alone Library Project, in addition to the two attributes
19276 that make a project a Library Project (@code{Library_Name} and
19277 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19278 @code{Library_Interface} must be defined.  For example:
19279
19280 @smallexample @c projectfile
19281 @group
19282    for Library_Dir use "lib_dir";
19283    for Library_Name use "dummy";
19284    for Library_Interface use ("int1", "int1.child");
19285 @end group
19286 @end smallexample
19287
19288 @noindent
19289 Attribute @code{Library_Interface} has a non-empty string list value,
19290 each string in the list designating a unit contained in an immediate source
19291 of the project file.
19292
19293 When a Stand-alone Library is built, first the binder is invoked to build
19294 a package whose name depends on the library name
19295 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19296 This binder-generated package includes initialization and
19297 finalization procedures whose
19298 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19299 in the example
19300 above). The object corresponding to this package is included in the library.
19301
19302 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19303 calling of these procedures if a static SAL is built, or if a shared SAL
19304 is built
19305 with the project-level attribute @code{Library_Auto_Init} set to
19306 @code{"false"}.
19307
19308 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19309 (those that are listed in attribute @code{Library_Interface}) are copied to
19310 the Library Directory. As a consequence, only the Interface Units may be
19311 imported from Ada units outside of the library. If other units are imported,
19312 the binding phase will fail.
19313
19314 The attribute @code{Library_Src_Dir} may be specified for a
19315 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19316 single string value. Its value must be the path (absolute or relative to the
19317 project directory) of an existing directory. This directory cannot be the
19318 object directory or one of the source directories, but it can be the same as
19319 the library directory. The sources of the Interface
19320 Units of the library that are needed by an Ada client of the library will be
19321 copied to the designated directory, called the Interface Copy directory.
19322 These sources include the specs of the Interface Units, but they may also
19323 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19324 are used, or when there is a generic unit in the spec. Before the sources
19325 are copied to the Interface Copy directory, an attempt is made to delete all
19326 files in the Interface Copy directory.
19327
19328 Building stand-alone libraries by hand is somewhat tedious, but for those
19329 occasions when it is necessary here are the steps that you need to perform:
19330 @itemize @bullet
19331 @item
19332 Compile all library sources.
19333
19334 @item
19335 Invoke the binder with the switch @option{-n} (No Ada main program),
19336 with all the @file{ALI} files of the interfaces, and
19337 with the switch @option{-L} to give specific names to the @code{init}
19338 and @code{final} procedures.  For example:
19339 @smallexample
19340   gnatbind -n int1.ali int2.ali -Lsal1
19341 @end smallexample
19342
19343 @item
19344 Compile the binder generated file:
19345 @smallexample
19346   gcc -c b~int2.adb
19347 @end smallexample
19348
19349 @item
19350 Link the dynamic library with all the necessary object files,
19351 indicating to the linker the names of the @code{init} (and possibly
19352 @code{final}) procedures for automatic initialization (and finalization).
19353 The built library should be placed in a directory different from
19354 the object directory.
19355
19356 @item
19357 Copy the @code{ALI} files of the interface to the library directory,
19358 add in this copy an indication that it is an interface to a SAL
19359 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19360 with letter ``P'') and make the modified copy of the @file{ALI} file
19361 read-only.
19362 @end itemize
19363
19364 @noindent
19365 Using SALs is not different from using other libraries
19366 (see @ref{Using a library}).
19367
19368 @node Creating a Stand-alone Library to be used in a non-Ada context
19369 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19370
19371 @noindent
19372 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19373 a non-Ada context.
19374
19375 The only extra step required is to ensure that library interface subprograms
19376 are compatible with the main program, by means of @code{pragma Export}
19377 or @code{pragma Convention}.
19378
19379 Here is an example of simple library interface for use with C main program:
19380
19381 @smallexample @c ada
19382 package Interface is
19383
19384    procedure Do_Something;
19385    pragma Export (C, Do_Something, "do_something");
19386
19387    procedure Do_Something_Else;
19388    pragma Export (C, Do_Something_Else, "do_something_else");
19389
19390 end Interface;
19391 @end smallexample
19392
19393 @noindent
19394 On the foreign language side, you must provide a ``foreign'' view of the
19395 library interface; remember that it should contain elaboration routines in
19396 addition to interface subprograms.
19397
19398 The example below shows the content of @code{mylib_interface.h} (note
19399 that there is no rule for the naming of this file, any name can be used)
19400 @smallexample
19401 /* the library elaboration procedure */
19402 extern void mylibinit (void);
19403
19404 /* the library finalization procedure */
19405 extern void mylibfinal (void);
19406
19407 /* the interface exported by the library */
19408 extern void do_something (void);
19409 extern void do_something_else (void);
19410 @end smallexample
19411
19412 @noindent
19413 Libraries built as explained above can be used from any program, provided
19414 that the elaboration procedures (named @code{mylibinit} in the previous
19415 example) are called before the library services are used. Any number of
19416 libraries can be used simultaneously, as long as the elaboration
19417 procedure of each library is called.
19418
19419 Below is an example of a C program that uses the @code{mylib} library.
19420
19421 @smallexample
19422 #include "mylib_interface.h"
19423
19424 int
19425 main (void)
19426 @{
19427    /* First, elaborate the library before using it */
19428    mylibinit ();
19429
19430    /* Main program, using the library exported entities */
19431    do_something ();
19432    do_something_else ();
19433
19434    /* Library finalization at the end of the program */
19435    mylibfinal ();
19436    return 0;
19437 @}
19438 @end smallexample
19439
19440 @noindent
19441 Note that invoking any library finalization procedure generated by
19442 @code{gnatbind} shuts down the Ada run-time environment.
19443 Consequently, the
19444 finalization of all Ada libraries must be performed at the end of the program.
19445 No call to these libraries or to the Ada run-time library should be made
19446 after the finalization phase.
19447
19448 @node Restrictions in Stand-alone Libraries
19449 @subsection Restrictions in Stand-alone Libraries
19450
19451 @noindent
19452 The pragmas listed below should be used with caution inside libraries,
19453 as they can create incompatibilities with other Ada libraries:
19454 @itemize @bullet
19455 @item pragma @code{Locking_Policy}
19456 @item pragma @code{Queuing_Policy}
19457 @item pragma @code{Task_Dispatching_Policy}
19458 @item pragma @code{Unreserve_All_Interrupts}
19459 @end itemize
19460
19461 @noindent
19462 When using a library that contains such pragmas, the user must make sure
19463 that all libraries use the same pragmas with the same values. Otherwise,
19464 @code{Program_Error} will
19465 be raised during the elaboration of the conflicting
19466 libraries. The usage of these pragmas and its consequences for the user
19467 should therefore be well documented.
19468
19469 Similarly, the traceback in the exception occurrence mechanism should be
19470 enabled or disabled in a consistent manner across all libraries.
19471 Otherwise, Program_Error will be raised during the elaboration of the
19472 conflicting libraries.
19473
19474 If the @code{Version} or @code{Body_Version}
19475 attributes are used inside a library, then you need to
19476 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19477 libraries, so that version identifiers can be properly computed.
19478 In practice these attributes are rarely used, so this is unlikely
19479 to be a consideration.
19480
19481 @node  Rebuilding the GNAT Run-Time Library
19482 @section Rebuilding the GNAT Run-Time Library
19483 @cindex GNAT Run-Time Library, rebuilding
19484 @cindex Building the GNAT Run-Time Library
19485 @cindex Rebuilding the GNAT Run-Time Library
19486 @cindex Run-Time Library, rebuilding
19487
19488 @noindent
19489 It may be useful to recompile the GNAT library in various contexts, the
19490 most important one being the use of partition-wide configuration pragmas
19491 such as @code{Normalize_Scalars}. A special Makefile called
19492 @code{Makefile.adalib} is provided to that effect and can be found in
19493 the directory containing the GNAT library. The location of this
19494 directory depends on the way the GNAT environment has been installed and can
19495 be determined by means of the command:
19496
19497 @smallexample
19498 $ gnatls -v
19499 @end smallexample
19500
19501 @noindent
19502 The last entry in the object search path usually contains the
19503 gnat library. This Makefile contains its own documentation and in
19504 particular the set of instructions needed to rebuild a new library and
19505 to use it.
19506
19507 @node Using the GNU make Utility
19508 @chapter Using the GNU @code{make} Utility
19509 @findex make
19510
19511 @noindent
19512 This chapter offers some examples of makefiles that solve specific
19513 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19514 make, make, GNU @code{make}}), nor does it try to replace the
19515 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19516
19517 All the examples in this section are specific to the GNU version of
19518 make. Although @command{make} is a standard utility, and the basic language
19519 is the same, these examples use some advanced features found only in
19520 @code{GNU make}.
19521
19522 @menu
19523 * Using gnatmake in a Makefile::
19524 * Automatically Creating a List of Directories::
19525 * Generating the Command Line Switches::
19526 * Overcoming Command Line Length Limits::
19527 @end menu
19528
19529 @node Using gnatmake in a Makefile
19530 @section Using gnatmake in a Makefile
19531 @findex makefile
19532 @cindex GNU make
19533
19534 @noindent
19535 Complex project organizations can be handled in a very powerful way by
19536 using GNU make combined with gnatmake. For instance, here is a Makefile
19537 which allows you to build each subsystem of a big project into a separate
19538 shared library. Such a makefile allows you to significantly reduce the link
19539 time of very big applications while maintaining full coherence at
19540 each step of the build process.
19541
19542 The list of dependencies are handled automatically by
19543 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19544 the appropriate directories.
19545
19546 Note that you should also read the example on how to automatically
19547 create the list of directories
19548 (@pxref{Automatically Creating a List of Directories})
19549 which might help you in case your project has a lot of subdirectories.
19550
19551 @smallexample
19552 @iftex
19553 @leftskip=0cm
19554 @font@heightrm=cmr8
19555 @heightrm
19556 @end iftex
19557 ## This Makefile is intended to be used with the following directory
19558 ## configuration:
19559 ##  - The sources are split into a series of csc (computer software components)
19560 ##    Each of these csc is put in its own directory.
19561 ##    Their name are referenced by the directory names.
19562 ##    They will be compiled into shared library (although this would also work
19563 ##    with static libraries
19564 ##  - The main program (and possibly other packages that do not belong to any
19565 ##    csc is put in the top level directory (where the Makefile is).
19566 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19567 ##                    \_ second_csc (sources) __ lib (will contain the library)
19568 ##                    \_ @dots{}
19569 ## Although this Makefile is build for shared library, it is easy to modify
19570 ## to build partial link objects instead (modify the lines with -shared and
19571 ## gnatlink below)
19572 ##
19573 ## With this makefile, you can change any file in the system or add any new
19574 ## file, and everything will be recompiled correctly (only the relevant shared
19575 ## objects will be recompiled, and the main program will be re-linked).
19576
19577 # The list of computer software component for your project. This might be
19578 # generated automatically.
19579 CSC_LIST=aa bb cc
19580
19581 # Name of the main program (no extension)
19582 MAIN=main
19583
19584 # If we need to build objects with -fPIC, uncomment the following line
19585 #NEED_FPIC=-fPIC
19586
19587 # The following variable should give the directory containing libgnat.so
19588 # You can get this directory through 'gnatls -v'. This is usually the last
19589 # directory in the Object_Path.
19590 GLIB=@dots{}
19591
19592 # The directories for the libraries
19593 # (This macro expands the list of CSC to the list of shared libraries, you
19594 # could simply use the expanded form:
19595 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19596 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19597
19598 $@{MAIN@}: objects $@{LIB_DIR@}
19599     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19600     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19601
19602 objects::
19603     # recompile the sources
19604     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19605
19606 # Note: In a future version of GNAT, the following commands will be simplified
19607 # by a new tool, gnatmlib
19608 $@{LIB_DIR@}:
19609     mkdir -p $@{dir $@@ @}
19610     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19611     cd $@{dir $@@ @} && cp -f ../*.ali .
19612
19613 # The dependencies for the modules
19614 # Note that we have to force the expansion of *.o, since in some cases
19615 # make won't be able to do it itself.
19616 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19617 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19618 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19619
19620 # Make sure all of the shared libraries are in the path before starting the
19621 # program
19622 run::
19623     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19624
19625 clean::
19626     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19627     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19628     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19629     $@{RM@} *.o *.ali $@{MAIN@}
19630 @end smallexample
19631
19632 @node Automatically Creating a List of Directories
19633 @section Automatically Creating a List of Directories
19634
19635 @noindent
19636 In most makefiles, you will have to specify a list of directories, and
19637 store it in a variable. For small projects, it is often easier to
19638 specify each of them by hand, since you then have full control over what
19639 is the proper order for these directories, which ones should be
19640 included.
19641
19642 However, in larger projects, which might involve hundreds of
19643 subdirectories, it might be more convenient to generate this list
19644 automatically.
19645
19646 The example below presents two methods. The first one, although less
19647 general, gives you more control over the list. It involves wildcard
19648 characters, that are automatically expanded by @command{make}. Its
19649 shortcoming is that you need to explicitly specify some of the
19650 organization of your project, such as for instance the directory tree
19651 depth, whether some directories are found in a separate tree, @enddots{}
19652
19653 The second method is the most general one. It requires an external
19654 program, called @command{find}, which is standard on all Unix systems. All
19655 the directories found under a given root directory will be added to the
19656 list.
19657
19658 @smallexample
19659 @iftex
19660 @leftskip=0cm
19661 @font@heightrm=cmr8
19662 @heightrm
19663 @end iftex
19664 # The examples below are based on the following directory hierarchy:
19665 # All the directories can contain any number of files
19666 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19667 #                       ->  ab
19668 #                       ->  ac
19669 #                ->  b  ->  ba  ->  baa
19670 #                       ->  bb
19671 #                       ->  bc
19672 # This Makefile creates a variable called DIRS, that can be reused any time
19673 # you need this list (see the other examples in this section)
19674
19675 # The root of your project's directory hierarchy
19676 ROOT_DIRECTORY=.
19677
19678 ####
19679 # First method: specify explicitly the list of directories
19680 # This allows you to specify any subset of all the directories you need.
19681 ####
19682
19683 DIRS := a/aa/ a/ab/ b/ba/
19684
19685 ####
19686 # Second method: use wildcards
19687 # Note that the argument(s) to wildcard below should end with a '/'.
19688 # Since wildcards also return file names, we have to filter them out
19689 # to avoid duplicate directory names.
19690 # We thus use make's @code{dir} and @code{sort} functions.
19691 # It sets DIRs to the following value (note that the directories aaa and baa
19692 # are not given, unless you change the arguments to wildcard).
19693 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19694 ####
19695
19696 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19697                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19698
19699 ####
19700 # Third method: use an external program
19701 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19702 # This is the most complete command: it sets DIRs to the following value:
19703 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19704 ####
19705
19706 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19707
19708 @end smallexample
19709
19710 @node Generating the Command Line Switches
19711 @section Generating the Command Line Switches
19712
19713 @noindent
19714 Once you have created the list of directories as explained in the
19715 previous section (@pxref{Automatically Creating a List of Directories}),
19716 you can easily generate the command line arguments to pass to gnatmake.
19717
19718 For the sake of completeness, this example assumes that the source path
19719 is not the same as the object path, and that you have two separate lists
19720 of directories.
19721
19722 @smallexample
19723 # see "Automatically creating a list of directories" to create
19724 # these variables
19725 SOURCE_DIRS=
19726 OBJECT_DIRS=
19727
19728 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19729 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19730
19731 all:
19732         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19733 @end smallexample
19734
19735 @node Overcoming Command Line Length Limits
19736 @section Overcoming Command Line Length Limits
19737
19738 @noindent
19739 One problem that might be encountered on big projects is that many
19740 operating systems limit the length of the command line. It is thus hard to give
19741 gnatmake the list of source and object directories.
19742
19743 This example shows how you can set up environment variables, which will
19744 make @command{gnatmake} behave exactly as if the directories had been
19745 specified on the command line, but have a much higher length limit (or
19746 even none on most systems).
19747
19748 It assumes that you have created a list of directories in your Makefile,
19749 using one of the methods presented in
19750 @ref{Automatically Creating a List of Directories}.
19751 For the sake of completeness, we assume that the object
19752 path (where the ALI files are found) is different from the sources patch.
19753
19754 Note a small trick in the Makefile below: for efficiency reasons, we
19755 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19756 expanded immediately by @code{make}. This way we overcome the standard
19757 make behavior which is to expand the variables only when they are
19758 actually used.
19759
19760 On Windows, if you are using the standard Windows command shell, you must
19761 replace colons with semicolons in the assignments to these variables.
19762
19763 @smallexample
19764 @iftex
19765 @leftskip=0cm
19766 @font@heightrm=cmr8
19767 @heightrm
19768 @end iftex
19769 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19770 # This is the same thing as putting the -I arguments on the command line.
19771 # (the equivalent of using -aI on the command line would be to define
19772 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19773 # You can of course have different values for these variables.
19774 #
19775 # Note also that we need to keep the previous values of these variables, since
19776 # they might have been set before running 'make' to specify where the GNAT
19777 # library is installed.
19778
19779 # see "Automatically creating a list of directories" to create these
19780 # variables
19781 SOURCE_DIRS=
19782 OBJECT_DIRS=
19783
19784 empty:=
19785 space:=$@{empty@} $@{empty@}
19786 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19787 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19788 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19789 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19790 export ADA_INCLUDE_PATH
19791 export ADA_OBJECT_PATH
19792
19793 all:
19794         gnatmake main_unit
19795 @end smallexample
19796 @end ifclear
19797
19798 @node Memory Management Issues
19799 @chapter Memory Management Issues
19800
19801 @noindent
19802 This chapter describes some useful memory pools provided in the GNAT library
19803 and in particular the GNAT Debug Pool facility, which can be used to detect
19804 incorrect uses of access values (including ``dangling references'').
19805 @ifclear vms
19806 It also describes the @command{gnatmem} tool, which can be used to track down
19807 ``memory leaks''.
19808 @end ifclear
19809
19810 @menu
19811 * Some Useful Memory Pools::
19812 * The GNAT Debug Pool Facility::
19813 @ifclear vms
19814 * The gnatmem Tool::
19815 @end ifclear
19816 @end menu
19817
19818 @node Some Useful Memory Pools
19819 @section Some Useful Memory Pools
19820 @findex Memory Pool
19821 @cindex storage, pool
19822
19823 @noindent
19824 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19825 storage pool. Allocations use the standard system call @code{malloc} while
19826 deallocations use the standard system call @code{free}. No reclamation is
19827 performed when the pool goes out of scope. For performance reasons, the
19828 standard default Ada allocators/deallocators do not use any explicit storage
19829 pools but if they did, they could use this storage pool without any change in
19830 behavior. That is why this storage pool is used  when the user
19831 manages to make the default implicit allocator explicit as in this example:
19832 @smallexample @c ada
19833    type T1 is access Something;
19834     -- no Storage pool is defined for T2
19835    type T2 is access Something_Else;
19836    for T2'Storage_Pool use T1'Storage_Pool;
19837    -- the above is equivalent to
19838    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19839 @end smallexample
19840
19841 @noindent
19842 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19843 pool. The allocation strategy is similar to @code{Pool_Local}'s
19844 except that the all
19845 storage allocated with this pool is reclaimed when the pool object goes out of
19846 scope. This pool provides a explicit mechanism similar to the implicit one
19847 provided by several Ada 83 compilers for allocations performed through a local
19848 access type and whose purpose was to reclaim memory when exiting the
19849 scope of a given local access. As an example, the following program does not
19850 leak memory even though it does not perform explicit deallocation:
19851
19852 @smallexample @c ada
19853 with System.Pool_Local;
19854 procedure Pooloc1 is
19855    procedure Internal is
19856       type A is access Integer;
19857       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19858       for A'Storage_Pool use X;
19859       v : A;
19860    begin
19861       for I in  1 .. 50 loop
19862          v := new Integer;
19863       end loop;
19864    end Internal;
19865 begin
19866    for I in  1 .. 100 loop
19867       Internal;
19868    end loop;
19869 end Pooloc1;
19870 @end smallexample
19871
19872 @noindent
19873 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19874 @code{Storage_Size} is specified for an access type.
19875 The whole storage for the pool is
19876 allocated at once, usually on the stack at the point where the access type is
19877 elaborated. It is automatically reclaimed when exiting the scope where the
19878 access type is defined. This package is not intended to be used directly by the
19879 user and it is implicitly used for each such declaration:
19880
19881 @smallexample @c ada
19882    type T1 is access Something;
19883    for T1'Storage_Size use 10_000;
19884 @end smallexample
19885
19886 @node The GNAT Debug Pool Facility
19887 @section The GNAT Debug Pool Facility
19888 @findex Debug Pool
19889 @cindex storage, pool, memory corruption
19890
19891 @noindent
19892 The use of unchecked deallocation and unchecked conversion can easily
19893 lead to incorrect memory references. The problems generated by such
19894 references are usually difficult to tackle because the symptoms can be
19895 very remote from the origin of the problem. In such cases, it is
19896 very helpful to detect the problem as early as possible. This is the
19897 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19898
19899 In order to use the GNAT specific debugging pool, the user must
19900 associate a debug pool object with each of the access types that may be
19901 related to suspected memory problems. See Ada Reference Manual 13.11.
19902 @smallexample @c ada
19903 type Ptr is access Some_Type;
19904 Pool : GNAT.Debug_Pools.Debug_Pool;
19905 for Ptr'Storage_Pool use Pool;
19906 @end smallexample
19907
19908 @noindent
19909 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19910 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19911 allow the user to redefine allocation and deallocation strategies. They
19912 also provide a checkpoint for each dereference, through the use of
19913 the primitive operation @code{Dereference} which is implicitly called at
19914 each dereference of an access value.
19915
19916 Once an access type has been associated with a debug pool, operations on
19917 values of the type may raise four distinct exceptions,
19918 which correspond to four potential kinds of memory corruption:
19919 @itemize @bullet
19920 @item
19921 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19922 @item
19923 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19924 @item
19925 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19926 @item
19927 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19928 @end itemize
19929
19930 @noindent
19931 For types associated with a Debug_Pool, dynamic allocation is performed using
19932 the standard GNAT allocation routine. References to all allocated chunks of
19933 memory are kept in an internal dictionary. Several deallocation strategies are
19934 provided, whereupon the user can choose to release the memory to the system,
19935 keep it allocated for further invalid access checks, or fill it with an easily
19936 recognizable pattern for debug sessions. The memory pattern is the old IBM
19937 hexadecimal convention: @code{16#DEADBEEF#}.
19938
19939 See the documentation in the file g-debpoo.ads for more information on the
19940 various strategies.
19941
19942 Upon each dereference, a check is made that the access value denotes a
19943 properly allocated memory location. Here is a complete example of use of
19944 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19945 @smallexample @c ada
19946 @iftex
19947 @leftskip=0cm
19948 @end iftex
19949 with Gnat.Io; use Gnat.Io;
19950 with Unchecked_Deallocation;
19951 with Unchecked_Conversion;
19952 with GNAT.Debug_Pools;
19953 with System.Storage_Elements;
19954 with Ada.Exceptions; use Ada.Exceptions;
19955 procedure Debug_Pool_Test is
19956
19957    type T is access Integer;
19958    type U is access all T;
19959
19960    P : GNAT.Debug_Pools.Debug_Pool;
19961    for T'Storage_Pool use P;
19962
19963    procedure Free is new Unchecked_Deallocation (Integer, T);
19964    function UC is new Unchecked_Conversion (U, T);
19965    A, B : aliased T;
19966
19967    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19968
19969 begin
19970    Info (P);
19971    A := new Integer;
19972    B := new Integer;
19973    B := A;
19974    Info (P);
19975    Free (A);
19976    begin
19977       Put_Line (Integer'Image(B.all));
19978    exception
19979       when E : others => Put_Line ("raised: " & Exception_Name (E));
19980    end;
19981    begin
19982       Free (B);
19983    exception
19984       when E : others => Put_Line ("raised: " & Exception_Name (E));
19985    end;
19986    B := UC(A'Access);
19987    begin
19988       Put_Line (Integer'Image(B.all));
19989    exception
19990       when E : others => Put_Line ("raised: " & Exception_Name (E));
19991    end;
19992    begin
19993       Free (B);
19994    exception
19995       when E : others => Put_Line ("raised: " & Exception_Name (E));
19996    end;
19997    Info (P);
19998 end Debug_Pool_Test;
19999 @end smallexample
20000
20001 @noindent
20002 The debug pool mechanism provides the following precise diagnostics on the
20003 execution of this erroneous program:
20004 @smallexample
20005 Debug Pool info:
20006   Total allocated bytes :  0
20007   Total deallocated bytes :  0
20008   Current Water Mark:  0
20009   High Water Mark:  0
20010
20011 Debug Pool info:
20012   Total allocated bytes :  8
20013   Total deallocated bytes :  0
20014   Current Water Mark:  8
20015   High Water Mark:  8
20016
20017 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20018 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20019 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20020 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20021 Debug Pool info:
20022   Total allocated bytes :  8
20023   Total deallocated bytes :  4
20024   Current Water Mark:  4
20025   High Water Mark:  8
20026 @end smallexample
20027
20028 @ifclear vms
20029 @node The gnatmem Tool
20030 @section The @command{gnatmem} Tool
20031 @findex gnatmem
20032
20033 @noindent
20034 The @code{gnatmem} utility monitors dynamic allocation and
20035 deallocation activity in a program, and displays information about
20036 incorrect deallocations and possible sources of memory leaks.
20037 It is designed to work in association with a static runtime library
20038 only and in this context provides three types of information:
20039 @itemize @bullet
20040 @item
20041 General information concerning memory management, such as the total
20042 number of allocations and deallocations, the amount of allocated
20043 memory and the high water mark, i.e.@: the largest amount of allocated
20044 memory in the course of program execution.
20045
20046 @item
20047 Backtraces for all incorrect deallocations, that is to say deallocations
20048 which do not correspond to a valid allocation.
20049
20050 @item
20051 Information on each allocation that is potentially the origin of a memory
20052 leak.
20053 @end itemize
20054
20055 @menu
20056 * Running gnatmem::
20057 * Switches for gnatmem::
20058 * Example of gnatmem Usage::
20059 @end menu
20060
20061 @node Running gnatmem
20062 @subsection Running @code{gnatmem}
20063
20064 @noindent
20065 @code{gnatmem} makes use of the output created by the special version of
20066 allocation and deallocation routines that record call information. This
20067 allows to obtain accurate dynamic memory usage history at a minimal cost to
20068 the execution speed. Note however, that @code{gnatmem} is not supported on
20069 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20070 Solaris and Windows NT/2000/XP (x86).
20071
20072 @noindent
20073 The @code{gnatmem} command has the form
20074
20075 @smallexample
20076    $ gnatmem @ovar{switches} user_program
20077 @end smallexample
20078
20079 @noindent
20080 The program must have been linked with the instrumented version of the
20081 allocation and deallocation routines. This is done by linking with the
20082 @file{libgmem.a} library. For correct symbolic backtrace information,
20083 the user program should be compiled with debugging options
20084 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20085
20086 @smallexample
20087 $ gnatmake -g my_program -largs -lgmem
20088 @end smallexample
20089
20090 @noindent
20091 As library @file{libgmem.a} contains an alternate body for package
20092 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20093 when an executable is linked with library @file{libgmem.a}. It is then not
20094 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20095
20096 @noindent
20097 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20098 This file contains information about all allocations and deallocations
20099 performed by the program. It is produced by the instrumented allocations and
20100 deallocations routines and will be used by @code{gnatmem}.
20101
20102 In order to produce symbolic backtrace information for allocations and
20103 deallocations performed by the GNAT run-time library, you need to use a
20104 version of that library that has been compiled with the @option{-g} switch
20105 (see @ref{Rebuilding the GNAT Run-Time Library}).
20106
20107 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20108 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20109 @option{-i} switch, gnatmem will assume that this file can be found in the
20110 current directory. For example, after you have executed @file{my_program},
20111 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20112
20113 @smallexample
20114 $ gnatmem my_program
20115 @end smallexample
20116
20117 @noindent
20118 This will produce the output with the following format:
20119
20120 *************** debut cc
20121 @smallexample
20122 $ gnatmem my_program
20123
20124 Global information
20125 ------------------
20126    Total number of allocations        :  45
20127    Total number of deallocations      :   6
20128    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20129    High Water Mark                    :  11.40 Kilobytes
20130
20131 .
20132 .
20133 .
20134 Allocation Root # 2
20135 -------------------
20136  Number of non freed allocations    :  11
20137  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20138  High Water Mark                    :   1.27 Kilobytes
20139  Backtrace                          :
20140    my_program.adb:23 my_program.alloc
20141 .
20142 .
20143 .
20144 @end smallexample
20145
20146 The first block of output gives general information. In this case, the
20147 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20148 Unchecked_Deallocation routine occurred.
20149
20150 @noindent
20151 Subsequent paragraphs display  information on all allocation roots.
20152 An allocation root is a specific point in the execution of the program
20153 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20154 construct. This root is represented by an execution backtrace (or subprogram
20155 call stack). By default the backtrace depth for allocations roots is 1, so
20156 that a root corresponds exactly to a source location. The backtrace can
20157 be made deeper, to make the root more specific.
20158
20159 @node Switches for gnatmem
20160 @subsection Switches for @code{gnatmem}
20161
20162 @noindent
20163 @code{gnatmem} recognizes the following switches:
20164
20165 @table @option
20166
20167 @item -q
20168 @cindex @option{-q} (@code{gnatmem})
20169 Quiet. Gives the minimum output needed to identify the origin of the
20170 memory leaks. Omits statistical information.
20171
20172 @item @var{N}
20173 @cindex @var{N} (@code{gnatmem})
20174 N is an integer literal (usually between 1 and 10) which controls the
20175 depth of the backtraces defining allocation root. The default value for
20176 N is 1. The deeper the backtrace, the more precise the localization of
20177 the root. Note that the total number of roots can depend on this
20178 parameter. This parameter must be specified @emph{before} the name of the
20179 executable to be analyzed, to avoid ambiguity.
20180
20181 @item -b n
20182 @cindex @option{-b} (@code{gnatmem})
20183 This switch has the same effect as just depth parameter.
20184
20185 @item -i @var{file}
20186 @cindex @option{-i} (@code{gnatmem})
20187 Do the @code{gnatmem} processing starting from @file{file}, rather than
20188 @file{gmem.out} in the current directory.
20189
20190 @item -m n
20191 @cindex @option{-m} (@code{gnatmem})
20192 This switch causes @code{gnatmem} to mask the allocation roots that have less
20193 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20194 examine even the roots that didn't result in leaks.
20195
20196 @item -s order
20197 @cindex @option{-s} (@code{gnatmem})
20198 This switch causes @code{gnatmem} to sort the allocation roots according to the
20199 specified order of sort criteria, each identified by a single letter. The
20200 currently supported criteria are @code{n, h, w} standing respectively for
20201 number of unfreed allocations, high watermark, and final watermark
20202 corresponding to a specific root. The default order is @code{nwh}.
20203
20204 @end table
20205
20206 @node Example of gnatmem Usage
20207 @subsection Example of @code{gnatmem} Usage
20208
20209 @noindent
20210 The following example shows the use of @code{gnatmem}
20211 on a simple memory-leaking program.
20212 Suppose that we have the following Ada program:
20213
20214 @smallexample @c ada
20215 @group
20216 @cartouche
20217 with Unchecked_Deallocation;
20218 procedure Test_Gm is
20219
20220    type T is array (1..1000) of Integer;
20221    type Ptr is access T;
20222    procedure Free is new Unchecked_Deallocation (T, Ptr);
20223    A : Ptr;
20224
20225    procedure My_Alloc is
20226    begin
20227       A := new T;
20228    end My_Alloc;
20229
20230    procedure My_DeAlloc is
20231       B : Ptr := A;
20232    begin
20233       Free (B);
20234    end My_DeAlloc;
20235
20236 begin
20237    My_Alloc;
20238    for I in 1 .. 5 loop
20239       for J in I .. 5 loop
20240          My_Alloc;
20241       end loop;
20242       My_Dealloc;
20243    end loop;
20244 end;
20245 @end cartouche
20246 @end group
20247 @end smallexample
20248
20249 @noindent
20250 The program needs to be compiled with debugging option and linked with
20251 @code{gmem} library:
20252
20253 @smallexample
20254 $ gnatmake -g test_gm -largs -lgmem
20255 @end smallexample
20256
20257 @noindent
20258 Then we execute the program as usual:
20259
20260 @smallexample
20261 $ test_gm
20262 @end smallexample
20263
20264 @noindent
20265 Then @code{gnatmem} is invoked simply with
20266 @smallexample
20267 $ gnatmem test_gm
20268 @end smallexample
20269
20270 @noindent
20271 which produces the following output (result may vary on different platforms):
20272
20273 @smallexample
20274 Global information
20275 ------------------
20276    Total number of allocations        :  18
20277    Total number of deallocations      :   5
20278    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20279    High Water Mark                    :  56.90 Kilobytes
20280
20281 Allocation Root # 1
20282 -------------------
20283  Number of non freed allocations    :  11
20284  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20285  High Water Mark                    :  46.88 Kilobytes
20286  Backtrace                          :
20287    test_gm.adb:11 test_gm.my_alloc
20288
20289 Allocation Root # 2
20290 -------------------
20291  Number of non freed allocations    :   1
20292  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20293  High Water Mark                    :  10.02 Kilobytes
20294  Backtrace                          :
20295    s-secsta.adb:81 system.secondary_stack.ss_init
20296
20297 Allocation Root # 3
20298 -------------------
20299  Number of non freed allocations    :   1
20300  Final Water Mark (non freed mem)   :  12 Bytes
20301  High Water Mark                    :  12 Bytes
20302  Backtrace                          :
20303    s-secsta.adb:181 system.secondary_stack.ss_init
20304 @end smallexample
20305
20306 @noindent
20307 Note that the GNAT run time contains itself a certain number of
20308 allocations that have no  corresponding deallocation,
20309 as shown here for root #2 and root
20310 #3. This is a normal behavior when the number of non-freed allocations
20311 is one, it allocates dynamic data structures that the run time needs for
20312 the complete lifetime of the program. Note also that there is only one
20313 allocation root in the user program with a single line back trace:
20314 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20315 program shows that 'My_Alloc' is called at 2 different points in the
20316 source (line 21 and line 24). If those two allocation roots need to be
20317 distinguished, the backtrace depth parameter can be used:
20318
20319 @smallexample
20320 $ gnatmem 3 test_gm
20321 @end smallexample
20322
20323 @noindent
20324 which will give the following output:
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    :  10
20337  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20338  High Water Mark                    :  42.97 Kilobytes
20339  Backtrace                          :
20340    test_gm.adb:11 test_gm.my_alloc
20341    test_gm.adb:24 test_gm
20342    b_test_gm.c:52 main
20343
20344 Allocation Root # 2
20345 -------------------
20346  Number of non freed allocations    :   1
20347  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20348  High Water Mark                    :  10.02 Kilobytes
20349  Backtrace                          :
20350    s-secsta.adb:81  system.secondary_stack.ss_init
20351    s-secsta.adb:283 <system__secondary_stack___elabb>
20352    b_test_gm.c:33   adainit
20353
20354 Allocation Root # 3
20355 -------------------
20356  Number of non freed allocations    :   1
20357  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20358  High Water Mark                    :   3.91 Kilobytes
20359  Backtrace                          :
20360    test_gm.adb:11 test_gm.my_alloc
20361    test_gm.adb:21 test_gm
20362    b_test_gm.c:52 main
20363
20364 Allocation Root # 4
20365 -------------------
20366  Number of non freed allocations    :   1
20367  Final Water Mark (non freed mem)   :  12 Bytes
20368  High Water Mark                    :  12 Bytes
20369  Backtrace                          :
20370    s-secsta.adb:181 system.secondary_stack.ss_init
20371    s-secsta.adb:283 <system__secondary_stack___elabb>
20372    b_test_gm.c:33   adainit
20373 @end smallexample
20374
20375 @noindent
20376 The allocation root #1 of the first example has been split in 2 roots #1
20377 and #3 thanks to the more precise associated backtrace.
20378
20379 @end ifclear
20380
20381 @node Stack Related Facilities
20382 @chapter Stack Related Facilities
20383
20384 @noindent
20385 This chapter describes some useful tools associated with stack
20386 checking and analysis. In
20387 particular, it deals with dynamic and static stack usage measurements.
20388
20389 @menu
20390 * Stack Overflow Checking::
20391 * Static Stack Usage Analysis::
20392 * Dynamic Stack Usage Analysis::
20393 @end menu
20394
20395 @node Stack Overflow Checking
20396 @section Stack Overflow Checking
20397 @cindex Stack Overflow Checking
20398 @cindex -fstack-check
20399
20400 @noindent
20401 For most operating systems, @command{gcc} does not perform stack overflow
20402 checking by default. This means that if the main environment task or
20403 some other task exceeds the available stack space, then unpredictable
20404 behavior will occur. Most native systems offer some level of protection by
20405 adding a guard page at the end of each task stack. This mechanism is usually
20406 not enough for dealing properly with stack overflow situations because
20407 a large local variable could ``jump'' above the guard page.
20408 Furthermore, when the
20409 guard page is hit, there may not be any space left on the stack for executing
20410 the exception propagation code. Enabling stack checking avoids
20411 such situations.
20412
20413 To activate stack checking, compile all units with the gcc option
20414 @option{-fstack-check}. For example:
20415
20416 @smallexample
20417 gcc -c -fstack-check package1.adb
20418 @end smallexample
20419
20420 @noindent
20421 Units compiled with this option will generate extra instructions to check
20422 that any use of the stack (for procedure calls or for declaring local
20423 variables in declare blocks) does not exceed the available stack space.
20424 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20425
20426 For declared tasks, the stack size is controlled by the size
20427 given in an applicable @code{Storage_Size} pragma or by the value specified
20428 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20429 the default size as defined in the GNAT runtime otherwise.
20430
20431 For the environment task, the stack size depends on
20432 system defaults and is unknown to the compiler. Stack checking
20433 may still work correctly if a fixed
20434 size stack is allocated, but this cannot be guaranteed.
20435 @ifclear vms
20436 To ensure that a clean exception is signalled for stack
20437 overflow, set the environment variable
20438 @env{GNAT_STACK_LIMIT} to indicate the maximum
20439 stack area that can be used, as in:
20440 @cindex GNAT_STACK_LIMIT
20441
20442 @smallexample
20443 SET GNAT_STACK_LIMIT 1600
20444 @end smallexample
20445
20446 @noindent
20447 The limit is given in kilobytes, so the above declaration would
20448 set the stack limit of the environment task to 1.6 megabytes.
20449 Note that the only purpose of this usage is to limit the amount
20450 of stack used by the environment task. If it is necessary to
20451 increase the amount of stack for the environment task, then this
20452 is an operating systems issue, and must be addressed with the
20453 appropriate operating systems commands.
20454 @end ifclear
20455 @ifset vms
20456 To have a fixed size stack in the environment task, the stack must be put
20457 in the P0 address space and its size specified.  Use these switches to
20458 create a p0 image:
20459
20460 @smallexample
20461 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20462 @end smallexample
20463
20464 @noindent
20465 The quotes are required to keep case.  The number after @samp{STACK=} is the
20466 size of the environmental task stack in pagelets (512 bytes).  In this example
20467 the stack size is about 2 megabytes.
20468
20469 @noindent
20470 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20471 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20472 more details about the @option{/p0image} qualifier and the @option{stack}
20473 option.
20474 @end ifset
20475
20476 @node Static Stack Usage Analysis
20477 @section Static Stack Usage Analysis
20478 @cindex Static Stack Usage Analysis
20479 @cindex -fstack-usage
20480
20481 @noindent
20482 A unit compiled with @option{-fstack-usage} will generate an extra file
20483 that specifies
20484 the maximum amount of stack used, on a per-function basis.
20485 The file has the same
20486 basename as the target object file with a @file{.su} extension.
20487 Each line of this file is made up of three fields:
20488
20489 @itemize
20490 @item
20491 The name of the function.
20492 @item
20493 A number of bytes.
20494 @item
20495 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20496 @end itemize
20497
20498 The second field corresponds to the size of the known part of the function
20499 frame.
20500
20501 The qualifier @code{static} means that the function frame size
20502 is purely static.
20503 It usually means that all local variables have a static size.
20504 In this case, the second field is a reliable measure of the function stack
20505 utilization.
20506
20507 The qualifier @code{dynamic} means that the function frame size is not static.
20508 It happens mainly when some local variables have a dynamic size. When this
20509 qualifier appears alone, the second field is not a reliable measure
20510 of the function stack analysis. When it is qualified with  @code{bounded}, it
20511 means that the second field is a reliable maximum of the function stack
20512 utilization.
20513
20514 @node Dynamic Stack Usage Analysis
20515 @section Dynamic Stack Usage Analysis
20516
20517 @noindent
20518 It is possible to measure the maximum amount of stack used by a task, by
20519 adding a switch to @command{gnatbind}, as:
20520
20521 @smallexample
20522 $ gnatbind -u0 file
20523 @end smallexample
20524
20525 @noindent
20526 With this option, at each task termination, its stack usage is  output on
20527 @file{stderr}.
20528 It is not always convenient to output the stack usage when the program
20529 is still running. Hence, it is possible to delay this output until program
20530 termination. for a given number of tasks specified as the argument of the
20531 @option{-u} option. For instance:
20532
20533 @smallexample
20534 $ gnatbind -u100 file
20535 @end smallexample
20536
20537 @noindent
20538 will buffer the stack usage information of the first 100 tasks to terminate and
20539 output this info at program termination. Results are displayed in four
20540 columns:
20541
20542 @noindent
20543 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20544
20545 @noindent
20546 where:
20547
20548 @table @emph
20549 @item Index
20550 is a number associated with each task.
20551
20552 @item Task Name
20553 is the name of the task analyzed.
20554
20555 @item Stack Size
20556 is the maximum size for the stack.
20557
20558 @item Stack Usage
20559 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20560 is not entirely analyzed, and it's not possible to know exactly how
20561 much has actually been used. The report thus contains the theoretical stack usage
20562 (Value) and the possible variation (Variation) around this value.
20563
20564 @end table
20565
20566 @noindent
20567 The environment task stack, e.g., the stack that contains the main unit, is
20568 only processed when the environment variable GNAT_STACK_LIMIT is set.
20569
20570
20571 @c *********************************
20572 @c *            GNATCHECK          *
20573 @c *********************************
20574 @node Verifying Properties Using gnatcheck
20575 @chapter Verifying Properties Using @command{gnatcheck}
20576 @findex gnatcheck
20577 @cindex @command{gnatcheck}
20578
20579 @noindent
20580 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20581 of Ada source files according to a given set of semantic rules.
20582 @cindex ASIS
20583
20584 In order to check compliance with a given rule, @command{gnatcheck} has to
20585 semantically analyze the Ada sources.
20586 Therefore, checks can only be performed on
20587 legal Ada units. Moreover, when a unit depends semantically upon units located
20588 outside the current directory, the source search path has to be provided when
20589 calling @command{gnatcheck}, either through a specified project file or
20590 through @command{gnatcheck} switches as described below.
20591
20592 A number of rules are predefined in @command{gnatcheck} and are described
20593 later in this chapter.
20594 You can also add new rules, by modifying the @command{gnatcheck} code and
20595 rebuilding the tool. In order to add a simple rule making some local checks,
20596 a small amount of straightforward ASIS-based programming is usually needed.
20597
20598 Project support for @command{gnatcheck} is provided by the GNAT
20599 driver (see @ref{The GNAT Driver and Project Files}).
20600
20601 Invoking @command{gnatcheck} on the command line has the form:
20602
20603 @smallexample
20604 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20605       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20606       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20607 @end smallexample
20608
20609 @noindent
20610 where
20611 @itemize @bullet
20612 @item
20613 @var{switches} specify the general tool options
20614
20615 @item
20616 Each @var{filename} is the name (including the extension) of a source
20617 file to process. ``Wildcards'' are allowed, and
20618 the file name may contain path information.
20619
20620 @item
20621 Each @var{arg_list_filename} is the name (including the extension) of a text
20622 file containing the names of the source files to process, separated by spaces
20623 or line breaks.
20624
20625 @item
20626 @var{gcc_switches} is a list of switches for
20627 @command{gcc}. They will be passed on to all compiler invocations made by
20628 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20629 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20630 and use the @option{-gnatec} switch to set the configuration file.
20631
20632 @item
20633 @var{rule_options} is a list of options for controlling a set of
20634 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20635 @end itemize
20636
20637 @noindent
20638 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20639
20640 @menu
20641 * Format of the Report File::
20642 * General gnatcheck Switches::
20643 * gnatcheck Rule Options::
20644 * Adding the Results of Compiler Checks to gnatcheck Output::
20645 * Project-Wide Checks::
20646 * Predefined Rules::
20647 @end menu
20648
20649 @node Format of the Report File
20650 @section Format of the Report File
20651 @cindex Report file (for @code{gnatcheck})
20652
20653 @noindent
20654 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20655 rule violations.
20656 It also creates a text file  that
20657 contains the complete report of the last gnatcheck run. By default this file is
20658 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20659 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20660 location of the report file. This report contains:
20661 @itemize @bullet
20662 @item a list of the Ada source files being checked,
20663 @item a list of enabled and disabled rules,
20664 @item a list of the diagnostic messages, ordered in three different ways
20665 and collected in three separate
20666 sections. Section 1 contains the raw list of diagnostic messages. It
20667 corresponds to the output going to @file{stdout}. Section 2 contains
20668 messages ordered by rules.
20669 Section 3 contains messages ordered by source files.
20670 @end itemize
20671
20672 @node General gnatcheck Switches
20673 @section General @command{gnatcheck} Switches
20674
20675 @noindent
20676 The following switches control the general @command{gnatcheck} behavior
20677
20678 @table @option
20679 @c !sort!
20680 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20681 @item ^-a^/ALL^
20682 Process all units including those with read-only ALI files such as
20683 those from GNAT Run-Time library.
20684
20685 @ifclear vms
20686 @ignore
20687 @cindex @option{-d} (@command{gnatcheck})
20688 @item -d
20689 Debug mode
20690 @end ignore
20691
20692 @cindex @option{-dd} (@command{gnatcheck})
20693 @item -dd
20694 Progress indicator mode (for use in GPS)
20695 @end ifclear
20696
20697 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20698 @item ^-h^/HELP^
20699 List the predefined and user-defined rules. For more details see
20700 @ref{Predefined Rules}.
20701
20702 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20703 @item ^-l^/LOCS^
20704 Use full source locations references in the report file. For a construct from
20705 a generic instantiation a full source location is a chain from the location
20706 of this construct in the generic unit to the place where this unit is
20707 instantiated.
20708
20709 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20710 @item ^-log^/LOG^
20711 Duplicate all the output sent to Stderr into a log file. The log file is
20712 named @var{gnatcheck.log} and is located in the current directory.
20713
20714 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20715 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20716 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20717 the default value is 500. Zero means that there is no limitation on
20718 the number of diagnostic messages to be printed into Stdout.
20719
20720 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20721 @item ^-q^/QUIET^
20722 Quiet mode. All the diagnoses about rule violations are placed in the
20723 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20724
20725 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20726 @item ^-s^/SHORT^
20727 Short format of the report file (no version information, no list of applied
20728 rules, no list of checked sources is included)
20729
20730 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20731 @item ^-s1^/COMPILER_STYLE^
20732 Include the compiler-style section in the report file
20733
20734 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20735 @item ^-s2^/BY_RULES^
20736 Include the section containing diagnoses ordered by rules in the report file
20737
20738 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20739 @item ^-s3^/BY_FILES_BY_RULES^
20740 Include the section containing diagnoses ordered by files and then by rules
20741 in the report file
20742
20743 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20744 @item ^-t^/TIME^
20745 Print out execution time.
20746
20747 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20748 @item ^-v^/VERBOSE^
20749 Verbose mode; @command{gnatcheck} generates version information and then
20750 a trace of sources being processed.
20751
20752 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20753 @item ^-o ^/OUTPUT=^@var{report_file}
20754 Set name of report file file to @var{report_file} .
20755
20756 @end table
20757
20758 @noindent
20759 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20760 @option{^-s2^/BY_RULES^} or
20761 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20762 then the  @command{gnatcheck} report file will only contain sections
20763 explicitly denoted by these options.
20764
20765 @node gnatcheck Rule Options
20766 @section @command{gnatcheck} Rule Options
20767
20768 @noindent
20769 The following options control the processing performed by
20770 @command{gnatcheck}.
20771
20772 @table @option
20773 @cindex @option{+ALL} (@command{gnatcheck})
20774 @item +ALL
20775 Turn all the rule checks ON.
20776
20777 @cindex @option{-ALL} (@command{gnatcheck})
20778 @item -ALL
20779 Turn all the rule checks OFF.
20780
20781 @cindex @option{+R} (@command{gnatcheck})
20782 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20783 Turn on the check for a specified rule with the specified parameter, if any.
20784 @var{rule_id} must be the identifier of one of the currently implemented rules
20785 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20786 are not case-sensitive. The @var{param} item must
20787 be a string representing a valid parameter(s) for the specified rule.
20788 If it contains any space characters then this string must be enclosed in
20789 quotation marks.
20790
20791 @cindex @option{-R} (@command{gnatcheck})
20792 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20793 Turn off the check for a specified rule with the specified parameter, if any.
20794
20795 @cindex @option{-from} (@command{gnatcheck})
20796 @item -from=@var{rule_option_filename}
20797 Read the rule options from the text file @var{rule_option_filename}, referred as
20798 ``rule file'' below.
20799
20800 @end table
20801
20802 @noindent
20803 The default behavior is that all the rule checks are disabled.
20804
20805 A rule file is a text file containing a set of rule options.
20806 @cindex Rule file (for @code{gnatcheck})
20807 The file may contain empty lines and Ada-style comments (comment
20808 lines and end-of-line comments). The rule file has free format; that is,
20809 you do not have to start a new rule option on a new line.
20810
20811 A rule file may contain other @option{-from=@var{rule_option_filename}}
20812 options, each such option being replaced with the content of the
20813 corresponding rule file during the rule files processing. In case a
20814 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20815 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20816 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20817 the processing of rule files is interrupted and a part of their content
20818 is ignored.
20819
20820
20821 @node Adding the Results of Compiler Checks to gnatcheck Output
20822 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20823
20824 @noindent
20825 The @command{gnatcheck} tool can include in the generated diagnostic messages
20826 and in
20827 the report file the results of the checks performed by the compiler. Though
20828 disabled by default, this effect may be obtained by using @option{+R} with
20829 the following rule identifiers and parameters:
20830
20831 @table @option
20832 @item Restrictions
20833 To record restrictions violations (that are performed by the compiler if the
20834 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20835 use the rule named
20836 @code{Restrictions} with the same parameters as pragma
20837 @code{Restrictions} or @code{Restriction_Warnings}.
20838
20839 @item Style_Checks
20840 To record compiler style checks(@pxref{Style Checking}), use the rule named
20841 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20842 which enables all the standard style checks that corresponds to @option{-gnatyy}
20843 GNAT style check option, or a string that has exactly the same
20844 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20845 @code{Style_Checks} (for further information about this pragma,
20846 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}). For example,
20847 @code{+RStyle_Checks:O} rule option activates and adds to @command{gnatcheck}
20848 output the compiler style check that corresponds to
20849 @code{-gnatyO} style check option.
20850
20851 @item Warnings
20852 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20853 named @code{Warnings} with a parameter that is a valid
20854 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20855 (for further information about this pragma, @pxref{Pragma Warnings,,,
20856 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20857 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20858 all the specific warnings, but not suppresses the warning mode,
20859 and 'e' parameter, corresponding to @option{-gnatwe} that means
20860 "treat warnings as errors", does not have any effect.
20861
20862 @end table
20863
20864 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20865 option with the corresponding restriction name as a parameter. @code{-R} is
20866 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20867 warnings and style checks, use the corresponding warning and style options.
20868
20869 @node Project-Wide Checks
20870 @section Project-Wide Checks
20871 @cindex Project-wide checks (for @command{gnatcheck})
20872
20873 @noindent
20874 In order to perform checks on all units of a given project, you can use
20875 the GNAT driver along with the @option{-P} option:
20876 @smallexample
20877    gnat check -Pproj -rules -from=my_rules
20878 @end smallexample
20879
20880 @noindent
20881 If the project @code{proj} depends upon other projects, you can perform
20882 checks on the project closure using the @option{-U} option:
20883 @smallexample
20884    gnat check -Pproj -U -rules -from=my_rules
20885 @end smallexample
20886
20887 @noindent
20888 Finally, if not all the units are relevant to a particular main
20889 program in the project closure, you can perform checks for the set
20890 of units needed to create a given main program (unit closure) using
20891 the @option{-U} option followed by the name of the main unit:
20892 @smallexample
20893    gnat check -Pproj -U main -rules -from=my_rules
20894 @end smallexample
20895
20896
20897 @node Predefined Rules
20898 @section Predefined Rules
20899 @cindex Predefined rules (for @command{gnatcheck})
20900
20901 @ignore
20902 @c (Jan 2007) Since the global rules are still under development and are not
20903 @c documented, there is no point in explaining the difference between
20904 @c global and local rules
20905 @noindent
20906 A rule in @command{gnatcheck} is either local or global.
20907 A @emph{local rule} is a rule that applies to a well-defined section
20908 of a program and that can be checked by analyzing only this section.
20909 A @emph{global rule} requires analysis of some global properties of the
20910 whole program (mostly related to the program call graph).
20911 As of @value{NOW}, the implementation of global rules should be
20912 considered to be at a preliminary stage. You can use the
20913 @option{+GLOBAL} option to enable all the global rules, and the
20914 @option{-GLOBAL} rule option to disable all the global rules.
20915
20916 All the global rules in the list below are
20917 so indicated by marking them ``GLOBAL''.
20918 This +GLOBAL and -GLOBAL options are not
20919 included in the list of gnatcheck options above, because at the moment they
20920 are considered as a temporary debug options.
20921
20922 @command{gnatcheck} performs rule checks for generic
20923 instances only for global rules.  This limitation may be relaxed in a later
20924 release.
20925 @end ignore
20926
20927 @noindent
20928 The following subsections document the rules implemented in
20929 @command{gnatcheck}.
20930 The subsection title is the same as the rule identifier, which may be
20931 used as a parameter of the @option{+R} or @option{-R} options.
20932
20933
20934 @menu
20935 * Abstract_Type_Declarations::
20936 * Anonymous_Arrays::
20937 * Anonymous_Subtypes::
20938 * Blocks::
20939 * Boolean_Relational_Operators::
20940 @ignore
20941 * Ceiling_Violations::
20942 @end ignore
20943 * Controlled_Type_Declarations::
20944 * Declarations_In_Blocks::
20945 * Default_Parameters::
20946 * Discriminated_Records::
20947 * Enumeration_Ranges_In_CASE_Statements::
20948 * Exceptions_As_Control_Flow::
20949 * Exits_From_Conditional_Loops::
20950 * EXIT_Statements_With_No_Loop_Name::
20951 * Expanded_Loop_Exit_Names::
20952 * Explicit_Full_Discrete_Ranges::
20953 * Float_Equality_Checks::
20954 * Forbidden_Pragmas::
20955 * Function_Style_Procedures::
20956 * Generics_In_Subprograms::
20957 * GOTO_Statements::
20958 * Implicit_IN_Mode_Parameters::
20959 * Implicit_SMALL_For_Fixed_Point_Types::
20960 * Improperly_Located_Instantiations::
20961 * Improper_Returns::
20962 * Library_Level_Subprograms::
20963 * Local_Packages::
20964 @ignore
20965 * Improperly_Called_Protected_Entries::
20966 @end ignore
20967 * Metrics::
20968 * Misnamed_Identifiers::
20969 * Multiple_Entries_In_Protected_Definitions::
20970 * Name_Clashes::
20971 * Non_Qualified_Aggregates::
20972 * Non_Short_Circuit_Operators::
20973 * Non_SPARK_Attributes::
20974 * Non_Tagged_Derived_Types::
20975 * Non_Visible_Exceptions::
20976 * Numeric_Literals::
20977 * OTHERS_In_Aggregates::
20978 * OTHERS_In_CASE_Statements::
20979 * OTHERS_In_Exception_Handlers::
20980 * Outer_Loop_Exits::
20981 * Overloaded_Operators::
20982 * Overly_Nested_Control_Structures::
20983 * Parameters_Out_Of_Order::
20984 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20985 * Positional_Actuals_For_Defaulted_Parameters::
20986 * Positional_Components::
20987 * Positional_Generic_Parameters::
20988 * Positional_Parameters::
20989 * Predefined_Numeric_Types::
20990 * Raising_External_Exceptions::
20991 * Raising_Predefined_Exceptions::
20992 * Separate_Numeric_Error_Handlers::
20993 @ignore
20994 * Recursion::
20995 * Side_Effect_Functions::
20996 @end ignore
20997 * Slices::
20998 * Unassigned_OUT_Parameters::
20999 * Uncommented_BEGIN_In_Package_Bodies::
21000 * Unconditional_Exits::
21001 * Unconstrained_Array_Returns::
21002 * Universal_Ranges::
21003 * Unnamed_Blocks_And_Loops::
21004 @ignore
21005 * Unused_Subprograms::
21006 @end ignore
21007 * USE_PACKAGE_Clauses::
21008 * Volatile_Objects_Without_Address_Clauses::
21009 @end menu
21010
21011
21012 @node Abstract_Type_Declarations
21013 @subsection @code{Abstract_Type_Declarations}
21014 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21015
21016 @noindent
21017 Flag all declarations of abstract types. For an abstract private
21018 type, both the private and full type declarations are flagged.
21019
21020 This rule has no parameters.
21021
21022
21023 @node Anonymous_Arrays
21024 @subsection @code{Anonymous_Arrays}
21025 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21026
21027 @noindent
21028 Flag all anonymous array type definitions (by Ada semantics these can only
21029 occur in object declarations).
21030
21031 This rule has no parameters.
21032
21033 @node Anonymous_Subtypes
21034 @subsection @code{Anonymous_Subtypes}
21035 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21036
21037 @noindent
21038 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
21039 any instance of a subtype indication with a constraint, other than one
21040 that occurs immediately within a subtype declaration. Any use of a range
21041 other than as a constraint used immediately within a subtype declaration
21042 is considered as an anonymous subtype.
21043
21044 An effect of this rule is that @code{for} loops such as the following are
21045 flagged (since @code{1..N} is formally a ``range''):
21046
21047 @smallexample @c ada
21048 for I in 1 .. N loop
21049    @dots{}
21050 end loop;
21051 @end smallexample
21052
21053 @noindent
21054 Declaring an explicit subtype solves the problem:
21055
21056 @smallexample @c ada
21057 subtype S is Integer range 1..N;
21058 @dots{}
21059 for I in S loop
21060    @dots{}
21061 end loop;
21062 @end smallexample
21063
21064 @noindent
21065 This rule has no parameters.
21066
21067 @node Blocks
21068 @subsection @code{Blocks}
21069 @cindex @code{Blocks} rule (for @command{gnatcheck})
21070
21071 @noindent
21072 Flag each block statement.
21073
21074 This rule has no parameters.
21075
21076 @node Boolean_Relational_Operators
21077 @subsection @code{Boolean_Relational_Operators}
21078 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21079
21080 @noindent
21081 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21082 ``>='', ``='' and ``/='') for the predefined Boolean type.
21083 (This rule is useful in enforcing the SPARK language restrictions.)
21084
21085 Calls to predefined relational operators of any type derived from
21086 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21087 with these designators, and uses of operators that are renamings
21088 of the predefined relational operators for @code{Standard.Boolean},
21089 are likewise not detected.
21090
21091 This rule has no parameters.
21092
21093 @ignore
21094 @node Ceiling_Violations
21095 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
21096 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21097
21098 @noindent
21099 Flag invocations of a protected operation by a task whose priority exceeds
21100 the protected object's ceiling.
21101
21102 As of @value{NOW}, this rule has the following limitations:
21103
21104 @itemize @bullet
21105
21106 @item
21107  We consider only pragmas Priority and Interrupt_Priority as means to define
21108   a task/protected operation priority. We do not consider the effect of using
21109   Ada.Dynamic_Priorities.Set_Priority procedure;
21110
21111 @item
21112  We consider only base task priorities, and no priority inheritance. That is,
21113   we do not make a difference between calls issued during task activation and
21114   execution of the sequence of statements from task body;
21115
21116 @item
21117  Any situation when the priority of protected operation caller is set by a
21118   dynamic expression (that is, the corresponding Priority or
21119   Interrupt_Priority pragma has a non-static expression as an argument) we
21120   treat as a priority inconsistency (and, therefore, detect this situation).
21121 @end itemize
21122
21123 @noindent
21124 At the moment the notion of the main subprogram is not implemented in
21125 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21126 if this subprogram can be a main subprogram of a partition) changes the
21127 priority of an environment task. So if we have more then one such pragma in
21128 the set of processed sources, the pragma that is processed last, defines the
21129 priority of an environment task.
21130
21131 This rule has no parameters.
21132 @end ignore
21133
21134 @node Controlled_Type_Declarations
21135 @subsection @code{Controlled_Type_Declarations}
21136 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21137
21138 @noindent
21139 Flag all declarations of controlled types. A declaration of a private type
21140 is flagged if its full declaration declares a controlled type. A declaration
21141 of a derived type is flagged if its ancestor type is controlled. Subtype
21142 declarations are not checked. A declaration of a type that itself is not a
21143 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21144 component is not checked.
21145
21146 This rule has no parameters.
21147
21148
21149
21150 @node Declarations_In_Blocks
21151 @subsection @code{Declarations_In_Blocks}
21152 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21153
21154 @noindent
21155 Flag all block statements containing local declarations. A @code{declare}
21156 block with an empty @i{declarative_part} or with a @i{declarative part}
21157 containing only pragmas and/or @code{use} clauses is not flagged.
21158
21159 This rule has no parameters.
21160
21161
21162 @node Default_Parameters
21163 @subsection @code{Default_Parameters}
21164 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21165
21166 @noindent
21167 Flag all default expressions for subprogram parameters. Parameter
21168 declarations of formal and generic subprograms are also checked.
21169
21170 This rule has no parameters.
21171
21172
21173 @node Discriminated_Records
21174 @subsection @code{Discriminated_Records}
21175 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21176
21177 @noindent
21178 Flag all declarations of record types with discriminants. Only the
21179 declarations of record and record extension types are checked. Incomplete,
21180 formal, private, derived and private extension type declarations are not
21181 checked. Task and protected type declarations also are not checked.
21182
21183 This rule has no parameters.
21184
21185
21186 @node Enumeration_Ranges_In_CASE_Statements
21187 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21188 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21189
21190 @noindent
21191 Flag each use of a range of enumeration literals as a choice in a
21192 @code{case} statement.
21193 All forms for specifying a range (explicit ranges
21194 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21195 An enumeration range is
21196 flagged even if contains exactly one enumeration value or no values at all. A
21197 type derived from an enumeration type is considered as an enumeration type.
21198
21199 This rule helps prevent maintenance problems arising from adding an
21200 enumeration value to a type and having it implicitly handled by an existing
21201 @code{case} statement with an enumeration range that includes the new literal.
21202
21203 This rule has no parameters.
21204
21205
21206 @node Exceptions_As_Control_Flow
21207 @subsection @code{Exceptions_As_Control_Flow}
21208 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21209
21210 @noindent
21211 Flag each place where an exception is explicitly raised and handled in the
21212 same subprogram body. A @code{raise} statement in an exception handler,
21213 package body, task body or entry body is not flagged.
21214
21215 The rule has no parameters.
21216
21217 @node Exits_From_Conditional_Loops
21218 @subsection @code{Exits_From_Conditional_Loops}
21219 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21220
21221 @noindent
21222 Flag any exit statement if it transfers the control out of a @code{for} loop
21223 or a @code{while} loop. This includes cases when the @code{exit} statement
21224 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21225 in some @code{for} or @code{while} loop, but transfers the control from some
21226 outer (inconditional) @code{loop} statement.
21227
21228 The rule has no parameters.
21229
21230
21231 @node EXIT_Statements_With_No_Loop_Name
21232 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21233 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21234
21235 @noindent
21236 Flag each @code{exit} statement that does not specify the name of the loop
21237 being exited.
21238
21239 The rule has no parameters.
21240
21241
21242 @node Expanded_Loop_Exit_Names
21243 @subsection @code{Expanded_Loop_Exit_Names}
21244 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21245
21246 @noindent
21247 Flag all expanded loop names in @code{exit} statements.
21248
21249 This rule has no parameters.
21250
21251 @node Explicit_Full_Discrete_Ranges
21252 @subsection @code{Explicit_Full_Discrete_Ranges}
21253 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21254
21255 @noindent
21256 Flag each discrete range that has the form @code{A'First .. A'Last}.
21257
21258 This rule has no parameters.
21259
21260 @node Float_Equality_Checks
21261 @subsection @code{Float_Equality_Checks}
21262 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21263
21264 @noindent
21265 Flag all calls to the predefined equality operations for floating-point types.
21266 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21267 User-defined equality operations are not flagged, nor are ``@code{=}''
21268 and ``@code{/=}'' operations for fixed-point types.
21269
21270 This rule has no parameters.
21271
21272
21273 @node Forbidden_Pragmas
21274 @subsection @code{Forbidden_Pragmas}
21275 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21276
21277 @noindent
21278 Flag each use of the specified pragmas.  The pragmas to be detected
21279 are named in the rule's  parameters.
21280
21281 This rule has the following parameters:
21282
21283 @itemize @bullet
21284 @item For the @option{+R} option
21285
21286 @table @asis
21287 @item @emph{Pragma_Name}
21288 Adds the specified pragma to the set of pragmas to be
21289 checked and sets the checks for all the specified pragmas
21290 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21291 does not correspond to any pragma name defined in the Ada
21292 standard or to the name of a GNAT-specific pragma defined
21293 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21294 Manual}, it is treated as the name of unknown pragma.
21295
21296 @item @code{GNAT}
21297 All the GNAT-specific pragmas are detected; this sets
21298 the checks for all the specified pragmas ON.
21299
21300 @item @code{ALL}
21301 All pragmas are detected; this sets the rule ON.
21302 @end table
21303
21304 @item For the @option{-R} option
21305 @table @asis
21306 @item @emph{Pragma_Name}
21307 Removes the specified pragma from the set of pragmas to be
21308 checked without affecting checks for
21309 other pragmas. @emph{Pragma_Name} is treated as a name
21310 of a pragma. If it does not correspond to any pragma
21311 defined in the Ada standard or to any name defined in
21312 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21313 this option is treated as turning OFF detection of all unknown pragmas.
21314
21315 @item GNAT
21316 Turn OFF detection of all GNAT-specific pragmas
21317
21318 @item ALL
21319 Clear the list of the pragmas to be detected and
21320 turn the rule OFF.
21321 @end table
21322 @end itemize
21323
21324 @noindent
21325 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21326 the syntax of an Ada identifier and therefore can not be considered
21327 as a pragma name, a diagnostic message is generated and the corresponding
21328 parameter is ignored.
21329
21330 When more then one parameter is given in the same rule option, the parameters
21331 must be separated by a comma.
21332
21333 If more then one option for this rule is specified for the @command{gnatcheck}
21334 call, a new option overrides the previous one(s).
21335
21336 The @option{+R} option with no parameters turns the rule ON with the set of
21337 pragmas to be detected defined by the previous rule options.
21338 (By default this set is empty, so if the only option specified for the rule is
21339 @option{+RForbidden_Pragmas} (with
21340 no parameter), then the rule is enabled, but it does not detect anything).
21341 The @option{-R} option with no parameter turns the rule OFF, but it does not
21342 affect the set of pragmas to be detected.
21343
21344
21345
21346
21347 @node Function_Style_Procedures
21348 @subsection @code{Function_Style_Procedures}
21349 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21350
21351 @noindent
21352 Flag each procedure that can be rewritten as a function. A procedure can be
21353 converted into a function if it has exactly one parameter of mode @code{out}
21354 and no parameters of mode @code{in out}. Procedure declarations,
21355 formal procedure declarations, and generic procedure declarations are always
21356 checked. Procedure
21357 bodies and body stubs are flagged only if they do not have corresponding
21358 separate declarations. Procedure renamings and procedure instantiations are
21359 not flagged.
21360
21361 If a procedure can be rewritten as a function, but its @code{out} parameter is
21362 of a limited type, it is not flagged.
21363
21364 Protected procedures are not flagged. Null procedures also are not flagged.
21365
21366 This rule has no parameters.
21367
21368
21369 @node Generics_In_Subprograms
21370 @subsection @code{Generics_In_Subprograms}
21371 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21372
21373 @noindent
21374 Flag each declaration of a generic unit in a subprogram. Generic
21375 declarations in the bodies of generic subprograms are also flagged.
21376 A generic unit nested in another generic unit is not flagged.
21377 If a generic unit is
21378 declared in a local package that is declared in a subprogram body, the
21379 generic unit is flagged.
21380
21381 This rule has no parameters.
21382
21383
21384 @node GOTO_Statements
21385 @subsection @code{GOTO_Statements}
21386 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21387
21388 @noindent
21389 Flag each occurrence of a @code{goto} statement.
21390
21391 This rule has no parameters.
21392
21393
21394 @node Implicit_IN_Mode_Parameters
21395 @subsection @code{Implicit_IN_Mode_Parameters}
21396 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21397
21398 @noindent
21399 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21400 Note that @code{access} parameters, although they technically behave
21401 like @code{in} parameters, are not flagged.
21402
21403 This rule has no parameters.
21404
21405
21406 @node Implicit_SMALL_For_Fixed_Point_Types
21407 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21408 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21409
21410 @noindent
21411 Flag each fixed point type declaration that lacks an explicit
21412 representation  clause to define its @code{'Small} value.
21413 Since @code{'Small} can be  defined only for ordinary fixed point types,
21414 decimal fixed point type declarations are not checked.
21415
21416 This rule has no parameters.
21417
21418
21419 @node Improperly_Located_Instantiations
21420 @subsection @code{Improperly_Located_Instantiations}
21421 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21422
21423 @noindent
21424 Flag all generic instantiations in library-level package specs
21425 (including library generic packages) and in all subprogram bodies.
21426
21427 Instantiations in task and entry bodies are not flagged. Instantiations in the
21428 bodies of protected subprograms are flagged.
21429
21430 This rule has no parameters.
21431
21432
21433
21434 @node Improper_Returns
21435 @subsection @code{Improper_Returns}
21436 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21437
21438 @noindent
21439 Flag each explicit @code{return} statement in procedures, and
21440 multiple @code{return} statements in functions.
21441 Diagnostic messages are generated for all @code{return} statements
21442 in a procedure (thus each procedure must be written so that it
21443 returns implicitly at the end of its statement part),
21444 and for all @code{return} statements in a function after the first one.
21445 This rule supports the stylistic convention that each subprogram
21446 should have no more than one point of normal return.
21447
21448 This rule has no parameters.
21449
21450
21451 @node Library_Level_Subprograms
21452 @subsection @code{Library_Level_Subprograms}
21453 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21454
21455 @noindent
21456 Flag all library-level subprograms (including generic subprogram instantiations).
21457
21458 This rule has no parameters.
21459
21460
21461 @node Local_Packages
21462 @subsection @code{Local_Packages}
21463 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21464
21465 @noindent
21466 Flag all local packages declared in package and generic package
21467 specs.
21468 Local packages in bodies are not flagged.
21469
21470 This rule has no parameters.
21471
21472 @ignore
21473 @node Improperly_Called_Protected_Entries
21474 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21475 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21476
21477 @noindent
21478 Flag each protected entry that can be called from more than one task.
21479
21480 This rule has no parameters.
21481 @end ignore
21482
21483 @node Metrics
21484 @subsection @code{Metrics}
21485 @cindex @code{Metrics} rule (for @command{gnatcheck})
21486
21487 @noindent
21488 There is a set of checks based on computing a metric value and comparing the
21489 result with the specified upper (or lower, depending on a specific metric)
21490 value specified for a given metric. A construct is flagged if a given metric
21491 is applicable (can be computed) for it and the computed value is greater
21492 then (lover then) the specified upper (lower) bound.
21493
21494 The name of any metric-based rule consists of the prefix @code{Metrics_}
21495 followed by the name of the corresponding metric (see the table below).
21496 For @option{+R} option, each metric-based rule has a numeric parameter
21497 specifying the bound (integer or real, depending on a metric), @option{-R}
21498 option for metric rules does not have a parameter.
21499
21500 The following table shows the metric names for that the corresponding
21501 metrics-based checks are supported by gnatcheck, including the
21502 constraint that must be satisfied by the bound that is specified for the check
21503 and what bound - upper (U) or lower (L) - should be specified.
21504
21505 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21506 @ifnothtml
21507 @headitem Check Name @tab Description @tab Bounds Value
21508 @end ifnothtml
21509 @ifhtml
21510 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21511 @end ifhtml
21512 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21513 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21514 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21515 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21516 @end multitable
21517
21518 @noindent
21519 The meaning and the computed values for all these metrics are exactly
21520 the same as for the corresponding metrics in @command{gnatmetric}.
21521
21522 @emph{Example:} the rule
21523 @smallexample
21524 +RMetrics_Cyclomatic_Complexity : 7
21525 @end smallexample
21526 @noindent
21527 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21528
21529 To turn OFF the check for cyclomatic complexity metric, use the following option:
21530 @smallexample
21531 -RMetrics_Cyclomatic_Complexity
21532 @end smallexample
21533
21534 @node Misnamed_Identifiers
21535 @subsection @code{Misnamed_Identifiers}
21536 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21537
21538 @noindent
21539 Flag the declaration of each identifier that does not have a suffix
21540 corresponding to the kind of entity being declared.
21541 The following declarations are checked:
21542
21543 @itemize @bullet
21544 @item
21545 type declarations
21546
21547 @item
21548 subtype declarations
21549
21550 @item
21551 constant declarations (but not number declarations)
21552
21553 @item
21554 package renaming declarations (but not generic package renaming
21555 declarations)
21556 @end itemize
21557
21558 @noindent
21559 This rule may have parameters. When used without parameters, the rule enforces
21560 the following checks:
21561
21562 @itemize @bullet
21563 @item
21564 type-defining names end with @code{_T}, unless the type is an access type,
21565 in which case the suffix must be @code{_A}
21566 @item
21567 constant names end with @code{_C}
21568 @item
21569 names defining package renamings end with @code{_R}
21570 @end itemize
21571
21572 @noindent
21573 For a private or incomplete type declaration the following checks are
21574 made for the defining name suffix:
21575
21576 @itemize @bullet
21577 @item
21578 For an incomplete type declaration: if the corresponding full type
21579 declaration is available, the defining identifier from the full type
21580 declaration is checked, but the defining identifier from the incomplete type
21581 declaration is not; otherwise the defining identifier from the incomplete
21582 type declaration is checked against the suffix specified for type
21583 declarations.
21584
21585 @item
21586 For a private type declaration (including private extensions),  the defining
21587 identifier from the private type declaration is checked against the type
21588 suffix (even if the corresponding full declaration is an access type
21589 declaration), and the defining identifier from the corresponding full type
21590 declaration is not checked.
21591 @end itemize
21592
21593 @noindent
21594 For a deferred constant, the defining name in the corresponding full constant
21595 declaration is not checked.
21596
21597 Defining names of formal types are not checked.
21598
21599 The rule may have the following parameters:
21600
21601 @itemize @bullet
21602 @item
21603 For the @option{+R} option:
21604 @table @code
21605 @item Default
21606 Sets the default listed above for all the names to be checked.
21607
21608 @item Type_Suffix=@emph{string}
21609 Specifies the suffix for a type name.
21610
21611 @item Access_Suffix=@emph{string}
21612 Specifies the suffix for an access type name. If
21613 this parameter is set, it overrides for access
21614 types the suffix set by the @code{Type_Suffix} parameter.
21615 For access types, @emph{string} may have the following format:
21616 @emph{suffix1(suffix2)}. That means that an access type name
21617 should have the @emph{suffix1} suffix except for the case when
21618 the designated type is also an access type, in this case the
21619 type name should have the @emph{suffix1 & suffix2} suffix.
21620
21621 @item Class_Access_Suffix=@emph{string}
21622 Specifies the suffix for the name of an access type that points to some class-wide
21623 type. If this parameter is set, it overrides for such access
21624 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
21625 parameter.
21626
21627 @item Class_Subtype_Suffix=@emph{string}
21628 Specifies the suffix for the name of a subtype that denotes a class-wide type.
21629
21630 @item Constant_Suffix=@emph{string}
21631 Specifies the suffix for a constant name.
21632
21633 @item Renaming_Suffix=@emph{string}
21634 Specifies the suffix for a package renaming name.
21635 @end table
21636
21637 @item
21638 For the @option{-R} option:
21639 @table @code
21640 @item All_Suffixes
21641 Remove all the suffixes specified for the
21642 identifier suffix checks, whether by default or
21643 as specified by other rule parameters. All the
21644 checks for this rule are disabled as a result.
21645
21646 @item Type_Suffix
21647 Removes the suffix specified for types. This
21648 disables checks for types but does not disable
21649 any other checks for this rule (including the
21650 check for access type names if @code{Access_Suffix} is
21651 set).
21652
21653 @item Access_Suffix
21654 Removes the suffix specified for access types.
21655 This disables checks for access type names but
21656 does not disable any other checks for this rule.
21657 If @code{Type_Suffix} is set, access type names are
21658 checked as ordinary type names.
21659
21660 @item Class_Access_Suffix
21661 Removes the suffix specified for access types pointing to class-wide
21662 type. This disables specific checks for names of access types pointing to
21663 class-wide types but does not disable any other checks for this rule.
21664 If @code{Type_Suffix} is set, access type names are
21665 checked as ordinary type names. If @code{Access_Suffix} is set, these
21666 access types are checked as any other access type name.
21667
21668 @item Class_Subtype_Suffix=@emph{string}
21669 Removes the suffix specified for subtype names.
21670 This disables checks for subtype names but
21671 does not disable any other checks for this rule.
21672
21673 @item Constant_Suffix
21674 Removes the suffix specified for constants. This
21675 disables checks for constant names but does not
21676 disable any other checks for this rule.
21677
21678 @item Renaming_Suffix
21679 Removes the suffix specified for package
21680 renamings. This disables checks for package
21681 renamings but does not disable any other checks
21682 for this rule.
21683 @end table
21684 @end itemize
21685
21686 @noindent
21687 If more than one parameter is used, parameters must be separated by commas.
21688
21689 If more than one  option is specified for the @command{gnatcheck} invocation,
21690 a new option overrides the previous one(s).
21691
21692 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21693 checks for all the
21694 name suffixes specified by previous options used for this rule.
21695
21696 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21697 all the checks but keeps
21698 all the suffixes specified by previous options used for this rule.
21699
21700 The @emph{string} value must be a valid suffix for an Ada identifier (after
21701 trimming all the leading and trailing space characters, if any).
21702 Parameters are not case sensitive, except the @emph{string} part.
21703
21704 If any error is detected in a rule parameter, the parameter is ignored.
21705 In such a case the options that are set for the rule are not
21706 specified.
21707
21708
21709
21710 @node Multiple_Entries_In_Protected_Definitions
21711 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21712 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21713
21714 @noindent
21715 Flag each protected definition (i.e., each protected object/type declaration)
21716 that defines more than one entry.
21717 Diagnostic messages are generated for all the entry declarations
21718 except the first one. An entry family is counted as one entry. Entries from
21719 the private part of the protected definition are also checked.
21720
21721 This rule has no parameters.
21722
21723 @node Name_Clashes
21724 @subsection @code{Name_Clashes}
21725 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21726
21727 @noindent
21728 Check that certain names are not used as defining identifiers. To activate
21729 this rule, you need to supply a reference to the dictionary file(s) as a rule
21730 parameter(s) (more then one dictionary file can be specified). If no
21731 dictionary file is set, this rule will not cause anything to be flagged.
21732 Only defining occurrences, not references, are checked.
21733 The check is not case-sensitive.
21734
21735 This rule is enabled by default, but without setting any corresponding
21736 dictionary file(s); thus the default effect is to do no checks.
21737
21738 A dictionary file is a plain text file. The maximum line length for this file
21739 is 1024 characters.  If the line is longer then this limit, extra characters
21740 are ignored.
21741
21742 Each line can be either an empty line, a comment line, or a line containing
21743 a list of identifiers separated by space or HT characters.
21744 A comment is an Ada-style comment (from @code{--} to end-of-line).
21745 Identifiers must follow the Ada syntax for identifiers.
21746 A line containing one or more identifiers may end with a comment.
21747
21748 @node Non_Qualified_Aggregates
21749 @subsection @code{Non_Qualified_Aggregates}
21750 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21751
21752 @noindent
21753 Flag each non-qualified aggregate.
21754 A non-qualified aggregate is an
21755 aggregate that is not the expression of a qualified expression. A
21756 string literal is not considered an aggregate, but an array
21757 aggregate of a string type is considered as a normal aggregate.
21758 Aggregates of anonymous array types are not flagged.
21759
21760 This rule has no parameters.
21761
21762
21763 @node Non_Short_Circuit_Operators
21764 @subsection @code{Non_Short_Circuit_Operators}
21765 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21766
21767 @noindent
21768 Flag all calls to predefined @code{and} and @code{or} operators for
21769 any boolean type. Calls to
21770 user-defined @code{and} and @code{or} and to operators defined by renaming
21771 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21772 operators for modular types or boolean array types are not flagged.
21773
21774 This rule has no parameters.
21775
21776
21777
21778 @node Non_SPARK_Attributes
21779 @subsection @code{Non_SPARK_Attributes}
21780 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21781
21782 @noindent
21783 The SPARK language defines the following subset of Ada 95 attribute
21784 designators as those that can be used in SPARK programs. The use of
21785 any other attribute is flagged.
21786
21787 @itemize @bullet
21788 @item @code{'Adjacent}
21789 @item @code{'Aft}
21790 @item @code{'Base}
21791 @item @code{'Ceiling}
21792 @item @code{'Component_Size}
21793 @item @code{'Compose}
21794 @item @code{'Copy_Sign}
21795 @item @code{'Delta}
21796 @item @code{'Denorm}
21797 @item @code{'Digits}
21798 @item @code{'Exponent}
21799 @item @code{'First}
21800 @item @code{'Floor}
21801 @item @code{'Fore}
21802 @item @code{'Fraction}
21803 @item @code{'Last}
21804 @item @code{'Leading_Part}
21805 @item @code{'Length}
21806 @item @code{'Machine}
21807 @item @code{'Machine_Emax}
21808 @item @code{'Machine_Emin}
21809 @item @code{'Machine_Mantissa}
21810 @item @code{'Machine_Overflows}
21811 @item @code{'Machine_Radix}
21812 @item @code{'Machine_Rounds}
21813 @item @code{'Max}
21814 @item @code{'Min}
21815 @item @code{'Model}
21816 @item @code{'Model_Emin}
21817 @item @code{'Model_Epsilon}
21818 @item @code{'Model_Mantissa}
21819 @item @code{'Model_Small}
21820 @item @code{'Modulus}
21821 @item @code{'Pos}
21822 @item @code{'Pred}
21823 @item @code{'Range}
21824 @item @code{'Remainder}
21825 @item @code{'Rounding}
21826 @item @code{'Safe_First}
21827 @item @code{'Safe_Last}
21828 @item @code{'Scaling}
21829 @item @code{'Signed_Zeros}
21830 @item @code{'Size}
21831 @item @code{'Small}
21832 @item @code{'Succ}
21833 @item @code{'Truncation}
21834 @item @code{'Unbiased_Rounding}
21835 @item @code{'Val}
21836 @item @code{'Valid}
21837 @end itemize
21838
21839 @noindent
21840 This rule has no parameters.
21841
21842
21843 @node Non_Tagged_Derived_Types
21844 @subsection @code{Non_Tagged_Derived_Types}
21845 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21846
21847 @noindent
21848 Flag all derived type declarations that do not have a record extension part.
21849
21850 This rule has no parameters.
21851
21852
21853
21854 @node Non_Visible_Exceptions
21855 @subsection @code{Non_Visible_Exceptions}
21856 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21857
21858 @noindent
21859 Flag constructs leading to the possibility of propagating an exception
21860 out of the scope in which the exception is declared.
21861 Two cases are detected:
21862
21863 @itemize @bullet
21864 @item
21865 An exception declaration in a subprogram body, task body or block
21866 statement is flagged if the body or statement does not contain a handler for
21867 that exception or a handler with an @code{others} choice.
21868
21869 @item
21870 A @code{raise} statement in an exception handler of a subprogram body,
21871 task body or block statement is flagged if it (re)raises a locally
21872 declared exception.  This may occur under the following circumstances:
21873 @itemize @minus
21874 @item
21875 it explicitly raises a locally declared exception, or
21876 @item
21877 it does not specify an exception name (i.e., it is simply @code{raise;})
21878 and the enclosing handler contains a locally declared exception in its
21879 exception choices.
21880 @end itemize
21881 @end itemize
21882
21883 @noindent
21884 Renamings of local exceptions are not flagged.
21885
21886 This rule has no parameters.
21887
21888
21889 @node Numeric_Literals
21890 @subsection @code{Numeric_Literals}
21891 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21892
21893 @noindent
21894 Flag each use of a numeric literal in an index expression, and in any
21895 circumstance except for the following:
21896
21897 @itemize @bullet
21898 @item
21899 a literal occurring in the initialization expression for a constant
21900 declaration or a named number declaration, or
21901
21902 @item
21903 an integer literal that is less than or equal to a value
21904 specified by the @option{N} rule parameter.
21905 @end itemize
21906
21907 @noindent
21908 This rule may have the following parameters for the @option{+R} option:
21909
21910 @table @asis
21911 @item @emph{N}
21912 @emph{N} is an integer literal used as the maximal value that is not flagged
21913 (i.e., integer literals not exceeding this value are allowed)
21914
21915 @item @code{ALL}
21916 All integer literals are flagged
21917 @end table
21918
21919 @noindent
21920 If no parameters are set, the maximum unflagged value is 1.
21921
21922 The last specified check limit (or the fact that there is no limit at
21923 all) is used when multiple @option{+R} options appear.
21924
21925 The @option{-R} option for this rule has no parameters.
21926 It disables the rule but retains the last specified maximum unflagged value.
21927 If the @option{+R} option subsequently appears, this value is used as the
21928 threshold for the check.
21929
21930
21931 @node OTHERS_In_Aggregates
21932 @subsection @code{OTHERS_In_Aggregates}
21933 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21934
21935 @noindent
21936 Flag each use of an @code{others} choice in extension aggregates.
21937 In record and array aggregates, an @code{others} choice is flagged unless
21938 it is used to refer to all components, or to all but one component.
21939
21940 If, in case of a named array aggregate, there are two associations, one
21941 with an @code{others} choice and another with a discrete range, the
21942 @code{others} choice is flagged even if the discrete range specifies
21943 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21944
21945 This rule has no parameters.
21946
21947 @node OTHERS_In_CASE_Statements
21948 @subsection @code{OTHERS_In_CASE_Statements}
21949 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21950
21951 @noindent
21952 Flag any use of an @code{others} choice in a @code{case} statement.
21953
21954 This rule has no parameters.
21955
21956 @node OTHERS_In_Exception_Handlers
21957 @subsection @code{OTHERS_In_Exception_Handlers}
21958 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21959
21960 @noindent
21961 Flag any use of an @code{others} choice in an exception handler.
21962
21963 This rule has no parameters.
21964
21965
21966 @node Outer_Loop_Exits
21967 @subsection @code{Outer_Loop_Exits}
21968 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21969
21970 @noindent
21971 Flag each @code{exit} statement containing a loop name that is not the name
21972 of the immediately enclosing @code{loop} statement.
21973
21974 This rule has no parameters.
21975
21976
21977 @node Overloaded_Operators
21978 @subsection @code{Overloaded_Operators}
21979 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21980
21981 @noindent
21982 Flag each function declaration that overloads an operator symbol.
21983 A function body is checked only if the body does not have a
21984 separate spec. Formal functions are also checked. For a
21985 renaming declaration, only renaming-as-declaration is checked
21986
21987 This rule has no parameters.
21988
21989
21990 @node Overly_Nested_Control_Structures
21991 @subsection @code{Overly_Nested_Control_Structures}
21992 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21993
21994 @noindent
21995 Flag each control structure whose nesting level exceeds the value provided
21996 in the rule parameter.
21997
21998 The control structures checked are the following:
21999
22000 @itemize @bullet
22001 @item    @code{if} statement
22002 @item    @code{case} statement
22003 @item    @code{loop} statement
22004 @item    Selective accept statement
22005 @item    Timed entry call statement
22006 @item    Conditional entry call
22007 @item    Asynchronous select statement
22008 @end itemize
22009
22010 @noindent
22011 The rule has the following parameter for the @option{+R} option:
22012
22013 @table @emph
22014 @item N
22015 Positive integer specifying the maximal control structure nesting
22016 level that is not flagged
22017 @end table
22018
22019 @noindent
22020 If the parameter for the @option{+R} option is not specified or
22021 if it is not a positive integer, @option{+R} option is ignored.
22022
22023 If more then one  option is specified for the gnatcheck call, the later option and
22024 new parameter override the previous one(s).
22025
22026
22027 @node Parameters_Out_Of_Order
22028 @subsection @code{Parameters_Out_Of_Order}
22029 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22030
22031 @noindent
22032 Flag each subprogram and entry declaration whose formal parameters are not
22033 ordered according to the following scheme:
22034
22035 @itemize @bullet
22036
22037 @item @code{in} and @code{access} parameters first,
22038 then @code{in out} parameters,
22039 and then @code{out} parameters;
22040
22041 @item for @code{in} mode, parameters with default initialization expressions
22042 occur last
22043 @end itemize
22044
22045 @noindent
22046 Only the first violation of the described order is flagged.
22047
22048 The following constructs are checked:
22049
22050 @itemize @bullet
22051 @item   subprogram declarations (including null procedures);
22052 @item   generic subprogram declarations;
22053 @item   formal subprogram declarations;
22054 @item   entry declarations;
22055 @item   subprogram bodies and subprogram body stubs that do not
22056 have separate specifications
22057 @end itemize
22058
22059 @noindent
22060 Subprogram renamings are not checked.
22061
22062 This rule has no parameters.
22063
22064
22065 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22066 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22067 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22068
22069 @noindent
22070 Flag each generic actual parameter corresponding to a generic formal
22071 parameter with a default initialization, if positional notation is used.
22072
22073 This rule has no parameters.
22074
22075 @node Positional_Actuals_For_Defaulted_Parameters
22076 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22077 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22078
22079 @noindent
22080 Flag each actual parameter to a subprogram or entry call where the
22081 corresponding formal parameter has a default expression, if positional
22082 notation is used.
22083
22084 This rule has no parameters.
22085
22086 @node Positional_Components
22087 @subsection @code{Positional_Components}
22088 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22089
22090 @noindent
22091 Flag each array, record and extension aggregate that includes positional
22092 notation.
22093
22094 This rule has no parameters.
22095
22096
22097 @node Positional_Generic_Parameters
22098 @subsection @code{Positional_Generic_Parameters}
22099 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22100
22101 @noindent
22102 Flag each instantiation using positional parameter notation.
22103
22104 This rule has no parameters.
22105
22106
22107 @node Positional_Parameters
22108 @subsection @code{Positional_Parameters}
22109 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22110
22111 @noindent
22112 Flag each subprogram or entry call using positional parameter notation,
22113 except for the following:
22114
22115 @itemize @bullet
22116 @item
22117 Invocations of prefix or infix operators are not flagged
22118 @item
22119 If the called subprogram or entry has only one formal parameter,
22120 the call is not flagged;
22121 @item
22122 If a subprogram call uses the @emph{Object.Operation} notation, then
22123 @itemize @minus
22124 @item
22125 the first parameter (that is, @emph{Object}) is not flagged;
22126 @item
22127 if the called subprogram has only two parameters, the second parameter
22128 of the call is not flagged;
22129 @end itemize
22130 @end itemize
22131
22132 @noindent
22133 This rule has no parameters.
22134
22135
22136
22137
22138 @node Predefined_Numeric_Types
22139 @subsection @code{Predefined_Numeric_Types}
22140 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22141
22142 @noindent
22143 Flag each explicit use of the name of any numeric type or subtype defined
22144 in package @code{Standard}.
22145
22146 The rationale for this rule is to detect when the
22147 program may depend on platform-specific characteristics of the implementation
22148 of the predefined numeric types. Note that this rule is over-pessimistic;
22149 for example, a program that uses @code{String} indexing
22150 likely needs a variable of type @code{Integer}.
22151 Another example is the flagging of predefined numeric types with explicit
22152 constraints:
22153
22154 @smallexample @c ada
22155     subtype My_Integer is Integer range Left .. Right;
22156     Vy_Var : My_Integer;
22157 @end smallexample
22158
22159 @noindent
22160 This rule detects only numeric types and subtypes defined in
22161 @code{Standard}. The use of numeric types and subtypes defined in other
22162 predefined packages (such as @code{System.Any_Priority} or
22163 @code{Ada.Text_IO.Count}) is not flagged
22164
22165 This rule has no parameters.
22166
22167
22168
22169 @node Raising_External_Exceptions
22170 @subsection @code{Raising_External_Exceptions}
22171 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22172
22173 @noindent
22174 Flag any @code{raise} statement, in a program unit declared in a library
22175 package or in a generic library package, for an exception that is
22176 neither a predefined exception nor an exception that is also declared (or
22177 renamed) in the visible part of the package.
22178
22179 This rule has no parameters.
22180
22181
22182
22183 @node Raising_Predefined_Exceptions
22184 @subsection @code{Raising_Predefined_Exceptions}
22185 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22186
22187 @noindent
22188 Flag each @code{raise} statement that raises a predefined exception
22189 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22190 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22191
22192 This rule has no parameters.
22193
22194 @node Separate_Numeric_Error_Handlers
22195 @subsection @code{Separate_Numeric_Error_Handlers}
22196 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22197
22198 @noindent
22199 Flags each exception handler that contains a choice for
22200 the predefined @code{Constraint_Error} exception, but does not contain
22201 the choice for the predefined @code{Numeric_Error} exception, or
22202 that contains the choice for @code{Numeric_Error}, but does not contain the
22203 choice for @code{Constraint_Error}.
22204
22205 This rule has no parameters.
22206
22207 @ignore
22208 @node Recursion
22209 @subsection @code{Recursion} (under construction, GLOBAL)
22210 @cindex @code{Recursion} rule (for @command{gnatcheck})
22211
22212 @noindent
22213 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22214 calls, of recursive subprograms are detected.
22215
22216 This rule has no parameters.
22217 @end ignore
22218
22219 @ignore
22220 @node Side_Effect_Functions
22221 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22222 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22223
22224 @noindent
22225 Flag functions with side effects.
22226
22227 We define a side effect as changing any data object that is not local for the
22228 body of this function.
22229
22230 At the moment, we do NOT consider a side effect any input-output operations
22231 (changing a state or a content of any file).
22232
22233 We do not consider protected functions for this rule (???)
22234
22235 There are the following sources of side effect:
22236
22237 @enumerate
22238 @item Explicit (or direct) side-effect:
22239
22240 @itemize @bullet
22241 @item
22242 direct assignment to a non-local variable;
22243
22244 @item
22245 direct call to an entity that is known to change some data object that is
22246      not local for the body of this function (Note, that if F1 calls F2 and F2
22247      does have a side effect, this does not automatically mean that F1 also
22248      have a side effect, because it may be the case that F2 is declared in
22249      F1's body and it changes some data object that is global for F2, but
22250      local for F1);
22251 @end itemize
22252
22253 @item Indirect side-effect:
22254 @itemize @bullet
22255 @item
22256 Subprogram calls implicitly issued by:
22257 @itemize @bullet
22258 @item
22259 computing initialization expressions from type declarations as a part
22260          of object elaboration or allocator evaluation;
22261 @item
22262 computing implicit parameters of subprogram or entry calls or generic
22263          instantiations;
22264 @end itemize
22265
22266 @item
22267 activation of a task that change some non-local data object (directly or
22268      indirectly);
22269
22270 @item
22271 elaboration code of a package that is a result of a package instantiation;
22272
22273 @item
22274 controlled objects;
22275 @end itemize
22276
22277 @item Situations when we can suspect a side-effect, but the full static check
22278 is either impossible or too hard:
22279 @itemize @bullet
22280 @item
22281 assignment to access variables or to the objects pointed by access
22282      variables;
22283
22284 @item
22285 call to a subprogram pointed by access-to-subprogram value
22286
22287 @item
22288 dispatching calls;
22289 @end itemize
22290 @end enumerate
22291
22292 @noindent
22293 This rule has no parameters.
22294 @end ignore
22295
22296 @node Slices
22297 @subsection @code{Slices}
22298 @cindex @code{Slices} rule (for @command{gnatcheck})
22299
22300 @noindent
22301 Flag all uses of array slicing
22302
22303 This rule has no parameters.
22304
22305
22306 @node Unassigned_OUT_Parameters
22307 @subsection @code{Unassigned_OUT_Parameters}
22308 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22309
22310 @noindent
22311 Flags procedures' @code{out} parameters that are not assigned, and
22312 identifies the contexts in which the assignments are missing.
22313
22314 An @code{out} parameter is flagged in the statements in the procedure
22315 body's handled sequence of statements (before the procedure body's
22316 @code{exception} part, if any) if this sequence of statements contains
22317 no assignments to the parameter.
22318
22319 An @code{out} parameter is flagged in an exception handler in the exception
22320 part of the procedure body's handled sequence of statements if the handler
22321 contains no assignment to the parameter.
22322
22323 Bodies of generic procedures are also considered.
22324
22325 The following are treated as assignments to an @code{out} parameter:
22326
22327 @itemize @bullet
22328 @item
22329 an assignment statement, with the parameter or some component as the target;
22330
22331 @item
22332 passing the parameter (or one of its components) as an @code{out} or
22333 @code{in out} parameter.
22334 @end itemize
22335
22336 @noindent
22337 This rule does not have any parameters.
22338
22339
22340
22341 @node Uncommented_BEGIN_In_Package_Bodies
22342 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22343 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22344
22345 @noindent
22346 Flags each package body with declarations and a statement part that does not
22347 include a trailing comment on the line containing the @code{begin} keyword;
22348 this trailing comment needs to specify the package name and nothing else.
22349 The @code{begin} is not flagged if the package body does not
22350 contain any declarations.
22351
22352 If the @code{begin} keyword is placed on the
22353 same line as the last declaration or the first statement, it is flagged
22354 independently of whether the line contains a trailing comment. The
22355 diagnostic message is attached to the line containing the first statement.
22356
22357 This rule has no parameters.
22358
22359 @node Unconditional_Exits
22360 @subsection @code{Unconditional_Exits}
22361 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22362
22363 @noindent
22364 Flag unconditional @code{exit} statements.
22365
22366 This rule has no parameters.
22367
22368 @node Unconstrained_Array_Returns
22369 @subsection @code{Unconstrained_Array_Returns}
22370 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22371
22372 @noindent
22373 Flag each function returning an unconstrained array. Function declarations,
22374 function bodies (and body stubs) having no separate specifications,
22375 and generic function instantiations are checked.
22376 Generic function declarations, function calls and function renamings are
22377 not checked.
22378
22379 This rule has no parameters.
22380
22381 @node Universal_Ranges
22382 @subsection @code{Universal_Ranges}
22383 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22384
22385 @noindent
22386 Flag discrete ranges that are a part of an index constraint, constrained
22387 array definition, or @code{for}-loop parameter specification, and whose bounds
22388 are both of type @i{universal_integer}. Ranges that have at least one
22389 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22390 or an expression of non-universal type) are not flagged.
22391
22392 This rule has no parameters.
22393
22394
22395 @node Unnamed_Blocks_And_Loops
22396 @subsection @code{Unnamed_Blocks_And_Loops}
22397 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22398
22399 @noindent
22400 Flag each unnamed block statement and loop statement.
22401
22402 The rule has no parameters.
22403
22404
22405
22406 @ignore
22407 @node Unused_Subprograms
22408 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22409 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22410
22411 @noindent
22412 Flag all unused subprograms.
22413
22414 This rule has no parameters.
22415 @end ignore
22416
22417
22418
22419
22420 @node USE_PACKAGE_Clauses
22421 @subsection @code{USE_PACKAGE_Clauses}
22422 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22423
22424 @noindent
22425 Flag all @code{use} clauses for packages; @code{use type} clauses are
22426 not flagged.
22427
22428 This rule has no parameters.
22429
22430
22431
22432 @node Volatile_Objects_Without_Address_Clauses
22433 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22434 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22435
22436 @noindent
22437 Flag each volatile object that does not have an address clause.
22438
22439 The following check is made: if the pragma @code{Volatile} is applied to a
22440 data object or to its type, then an address clause must
22441 be supplied for this object.
22442
22443 This rule does not check the components of data objects,
22444 array components that are volatile as a result of the pragma
22445 @code{Volatile_Components}, or objects that are volatile because
22446 they are atomic as a result of pragmas @code{Atomic} or
22447 @code{Atomic_Components}.
22448
22449 Only variable declarations, and not constant declarations, are checked.
22450
22451 This rule has no parameters.
22452
22453
22454 @c *********************************
22455 @node Creating Sample Bodies Using gnatstub
22456 @chapter Creating Sample Bodies Using @command{gnatstub}
22457 @findex gnatstub
22458
22459 @noindent
22460 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22461 for library unit declarations.
22462
22463 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22464 driver (see @ref{The GNAT Driver and Project Files}).
22465
22466 To create a body stub, @command{gnatstub} has to compile the library
22467 unit declaration. Therefore, bodies can be created only for legal
22468 library units. Moreover, if a library unit depends semantically upon
22469 units located outside the current directory, you have to provide
22470 the source search path when calling @command{gnatstub}, see the description
22471 of @command{gnatstub} switches below.
22472
22473 By default, all the program unit body stubs generated by @code{gnatstub}
22474 raise the predefined @code{Program_Error} exception, which will catch
22475 accidental calls of generated stubs. This behavior can be changed with
22476 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22477
22478 @menu
22479 * Running gnatstub::
22480 * Switches for gnatstub::
22481 @end menu
22482
22483 @node Running gnatstub
22484 @section Running @command{gnatstub}
22485
22486 @noindent
22487 @command{gnatstub} has the command-line interface of the form
22488
22489 @smallexample
22490 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22491 @end smallexample
22492
22493 @noindent
22494 where
22495 @table @var
22496 @item filename
22497 is the name of the source file that contains a library unit declaration
22498 for which a body must be created. The file name may contain the path
22499 information.
22500 The file name does not have to follow the GNAT file name conventions. If the
22501 name
22502 does not follow GNAT file naming conventions, the name of the body file must
22503 be provided
22504 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22505 If the file name follows the GNAT file naming
22506 conventions and the name of the body file is not provided,
22507 @command{gnatstub}
22508 creates the name
22509 of the body file from the argument file name by replacing the @file{.ads}
22510 suffix
22511 with the @file{.adb} suffix.
22512
22513 @item directory
22514 indicates the directory in which the body stub is to be placed (the default
22515 is the
22516 current directory)
22517
22518 @item switches
22519 is an optional sequence of switches as described in the next section
22520 @end table
22521
22522 @node Switches for gnatstub
22523 @section Switches for @command{gnatstub}
22524
22525 @table @option
22526 @c !sort!
22527
22528 @item ^-f^/FULL^
22529 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22530 If the destination directory already contains a file with the name of the
22531 body file
22532 for the argument spec file, replace it with the generated body stub.
22533
22534 @item ^-hs^/HEADER=SPEC^
22535 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22536 Put the comment header (i.e., all the comments preceding the
22537 compilation unit) from the source of the library unit declaration
22538 into the body stub.
22539
22540 @item ^-hg^/HEADER=GENERAL^
22541 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22542 Put a sample comment header into the body stub.
22543
22544 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22545 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22546 Use the content of the file as the comment header for a generated body stub.
22547
22548 @ifclear vms
22549 @item -IDIR
22550 @cindex @option{-IDIR} (@command{gnatstub})
22551 @itemx -I-
22552 @cindex @option{-I-} (@command{gnatstub})
22553 @end ifclear
22554 @ifset vms
22555 @item /NOCURRENT_DIRECTORY
22556 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22557 @end ifset
22558 ^These switches have ^This switch has^ the same meaning as in calls to
22559 @command{gcc}.
22560 ^They define ^It defines ^ the source search path in the call to
22561 @command{gcc} issued
22562 by @command{gnatstub} to compile an argument source file.
22563
22564 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22565 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22566 This switch has the same meaning as in calls to @command{gcc}.
22567 It defines the additional configuration file to be passed to the call to
22568 @command{gcc} issued
22569 by @command{gnatstub} to compile an argument source file.
22570
22571 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22572 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22573 (@var{n} is a non-negative integer). Set the maximum line length in the
22574 body stub to @var{n}; the default is 79. The maximum value that can be
22575 specified is 32767. Note that in the special case of configuration
22576 pragma files, the maximum is always 32767 regardless of whether or
22577 not this switch appears.
22578
22579 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22580 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22581 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22582 the generated body sample to @var{n}.
22583 The default indentation is 3.
22584
22585 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22586 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22587 Order local bodies alphabetically. (By default local bodies are ordered
22588 in the same way as the corresponding local specs in the argument spec file.)
22589
22590 @item ^-i^/INDENTATION=^@var{n}
22591 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22592 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22593
22594 @item ^-k^/TREE_FILE=SAVE^
22595 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22596 Do not remove the tree file (i.e., the snapshot of the compiler internal
22597 structures used by @command{gnatstub}) after creating the body stub.
22598
22599 @item ^-l^/LINE_LENGTH=^@var{n}
22600 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22601 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22602
22603 @item ^--no-exception^/NO_EXCEPTION^
22604 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22605 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22606 This is not always possible for function stubs.
22607
22608 @item ^-o ^/BODY=^@var{body-name}
22609 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22610 Body file name.  This should be set if the argument file name does not
22611 follow
22612 the GNAT file naming
22613 conventions. If this switch is omitted the default name for the body will be
22614 obtained
22615 from the argument file name according to the GNAT file naming conventions.
22616
22617 @item ^-q^/QUIET^
22618 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22619 Quiet mode: do not generate a confirmation when a body is
22620 successfully created, and do not generate a message when a body is not
22621 required for an
22622 argument unit.
22623
22624 @item ^-r^/TREE_FILE=REUSE^
22625 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22626 Reuse the tree file (if it exists) instead of creating it.  Instead of
22627 creating the tree file for the library unit declaration, @command{gnatstub}
22628 tries to find it in the current directory and use it for creating
22629 a body. If the tree file is not found, no body is created. This option
22630 also implies @option{^-k^/SAVE^}, whether or not
22631 the latter is set explicitly.
22632
22633 @item ^-t^/TREE_FILE=OVERWRITE^
22634 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22635 Overwrite the existing tree file.  If the current directory already
22636 contains the file which, according to the GNAT file naming rules should
22637 be considered as a tree file for the argument source file,
22638 @command{gnatstub}
22639 will refuse to create the tree file needed to create a sample body
22640 unless this option is set.
22641
22642 @item ^-v^/VERBOSE^
22643 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22644 Verbose mode: generate version information.
22645
22646 @end table
22647
22648 @c *********************************
22649 @node Generating Ada Bindings for C and C++ headers
22650 @chapter Generating Ada Bindings for C and C++ headers
22651 @findex binding
22652
22653 @noindent
22654 GNAT now comes with a new experimental binding generator for C and C++
22655 headers which is intended to do 95% of the tedious work of generating
22656 Ada specs from C or C++ header files. Note that this still is a work in
22657 progress, not designed to generate 100% correct Ada specs.
22658
22659 The code generated is using the Ada 2005 syntax, which makes it
22660 easier to interface with other languages than previous versions of Ada.
22661
22662 @menu
22663 * Running the binding generator::
22664 * Generating bindings for C++ headers::
22665 * Switches::
22666 @end menu
22667
22668 @node Running the binding generator
22669 @section Running the binding generator
22670
22671 @noindent
22672 The binding generator is part of the @command{gcc} compiler and can be
22673 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
22674 spec files for the header files specified on the command line, and all
22675 header files needed by these files transitivitely. For example:
22676
22677 @smallexample
22678 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
22679 $ gcc -c -gnat05 *.ads
22680 @end smallexample
22681
22682 will generate, under GNU/Linux, the following files: @file{time_h.ads},
22683 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
22684 correspond to the files @file{/usr/include/time.h},
22685 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
22686 mode these Ada specs.
22687
22688 The @code{-C} switch tells @command{gcc} to extract comments from headers,
22689 and will attempt to generate corresponding Ada comments.
22690
22691 If you want to generate a single Ada file and not the transitive closure, you
22692 can use instead the @option{-fdump-ada-spec-slim} switch.
22693
22694 Note that we recommend when possible to use the @command{g++} driver to
22695 generate bindings, even for most C headers, since this will in general
22696 generate better Ada specs. For generating bindings for C++ headers, it is
22697 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
22698 is equivalent in this case. If @command{g++} cannot work on your C headers
22699 because of incompatibilities between C and C++, then you can fallback to
22700 @command{gcc} instead.
22701
22702 For an example of better bindings generated from the C++ front-end,
22703 the name of the parameters (when available) are actually ignored by the C
22704 front-end. Consider the following C header:
22705
22706 @smallexample
22707 extern void foo (int variable);
22708 @end smallexample
22709
22710 with the C front-end, @code{variable} is ignored, and the above is handled as:
22711
22712 @smallexample
22713 extern void foo (int);
22714 @end smallexample
22715
22716 generating a generic:
22717
22718 @smallexample
22719 procedure foo (param1 : int);
22720 @end smallexample
22721
22722 with the C++ front-end, the name is available, and we generate:
22723
22724 @smallexample
22725 procedure foo (variable : int);
22726 @end smallexample
22727
22728 In some cases, the generated bindings will be more complete or more meaningful
22729 when defining some macros, which you can do via the @option{-D} switch. This
22730 is for example the case with @file{Xlib.h} under GNU/Linux:
22731
22732 @smallexample
22733 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
22734 @end smallexample
22735
22736 The above will generate more complete bindings than a straight call without
22737 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
22738
22739 In other cases, it is not possible to parse a header file in a stand alone
22740 manner, because other include files need to be included first. In this
22741 case, the solution is to create a small header file including the needed
22742 @code{#include} and possible @code{#define} directives. For example, to
22743 generate Ada bindings for @file{readline/readline.h}, you need to first
22744 include @file{stdio.h}, so you can create a file with the following two
22745 lines in e.g. @file{readline1.h}:
22746
22747 @smallexample
22748 #include <stdio.h>
22749 #include <readline/readline.h>
22750 @end smallexample
22751
22752 and then generate Ada bindings from this file:
22753
22754 @smallexample
22755 $ g++ -c -fdump-ada-spec readline1.h
22756 @end smallexample
22757
22758 @node Generating bindings for C++ headers
22759 @section Generating bindings for C++ headers
22760
22761 @noindent
22762 Generating bindings for C++ headers is done using the same options, always
22763 with the @command{g++} compiler.
22764
22765 In this mode, C++ classes will be mapped to Ada tagged types, constructors
22766 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
22767 multiple inheritance of abstract classes will be mapped to Ada interfaces
22768 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
22769 information on interfacing to C++).
22770
22771 For example, given the following C++ header file:
22772
22773 @smallexample
22774 @group
22775 @cartouche
22776 class Carnivore @{
22777 public:
22778    virtual int Number_Of_Teeth () = 0;
22779 @};
22780
22781 class Domestic @{
22782 public:
22783    virtual void Set_Owner (char* Name) = 0;
22784 @};
22785
22786 class Animal @{
22787 public:
22788   int Age_Count;
22789   virtual void Set_Age (int New_Age);
22790 @};
22791
22792 class Dog : Animal, Carnivore, Domestic @{
22793  public:
22794   int  Tooth_Count;
22795   char *Owner;
22796
22797   virtual int  Number_Of_Teeth ();
22798   virtual void Set_Owner (char* Name);
22799
22800   Dog();
22801 @};
22802 @end cartouche
22803 @end group
22804 @end smallexample
22805
22806 The corresponding Ada code is generated:
22807
22808 @smallexample @c ada
22809 @group
22810 @cartouche
22811   package Class_Carnivore is
22812     type Carnivore is limited interface;
22813     pragma Import (CPP, Carnivore);
22814
22815     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
22816   end;
22817   use Class_Carnivore;
22818
22819   package Class_Domestic is
22820     type Domestic is limited interface;
22821     pragma Import (CPP, Domestic);
22822
22823     procedure Set_Owner
22824       (this : access Domestic;
22825        Name : Interfaces.C.Strings.chars_ptr) is abstract;
22826   end;
22827   use Class_Domestic;
22828
22829   package Class_Animal is
22830     type Animal is tagged limited record
22831       Age_Count : aliased int;
22832     end record;
22833     pragma Import (CPP, Animal);
22834
22835     procedure Set_Age (this : access Animal; New_Age : int);
22836     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
22837   end;
22838   use Class_Animal;
22839
22840   package Class_Dog is
22841     type Dog is new Animal and Carnivore and Domestic with record
22842       Tooth_Count : aliased int;
22843       Owner : Interfaces.C.Strings.chars_ptr;
22844     end record;
22845     pragma Import (CPP, Dog);
22846
22847     function Number_Of_Teeth (this : access Dog) return int;
22848     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
22849
22850     procedure Set_Owner
22851       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
22852     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
22853
22854     function New_Dog return Dog;
22855     pragma CPP_Constructor (New_Dog);
22856     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
22857   end;
22858   use Class_Dog;
22859 @end cartouche
22860 @end group
22861 @end smallexample
22862
22863 @node Switches
22864 @section Switches
22865
22866 @table @option
22867 @item -fdump-ada-spec
22868 @cindex @option{-fdump-ada-spec} (@command{gcc})
22869 Generate Ada spec files for the given header files transitively (including
22870 all header files that these headers depend upon).
22871
22872 @item -fdump-ada-spec-slim
22873 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
22874 Generate Ada spec files for the header files specified on the command line
22875 only.
22876
22877 @item -C
22878 @cindex @option{-C} (@command{gcc})
22879 Extract comments from headers and generate Ada comments in the Ada spec files.
22880 @end table
22881
22882 @node Other Utility Programs
22883 @chapter Other Utility Programs
22884
22885 @noindent
22886 This chapter discusses some other utility programs available in the Ada
22887 environment.
22888
22889 @menu
22890 * Using Other Utility Programs with GNAT::
22891 * The External Symbol Naming Scheme of GNAT::
22892 * Converting Ada Files to html with gnathtml::
22893 * Installing gnathtml::
22894 @ifset vms
22895 * LSE::
22896 * Profiling::
22897 @end ifset
22898 @end menu
22899
22900 @node Using Other Utility Programs with GNAT
22901 @section Using Other Utility Programs with GNAT
22902
22903 @noindent
22904 The object files generated by GNAT are in standard system format and in
22905 particular the debugging information uses this format. This means
22906 programs generated by GNAT can be used with existing utilities that
22907 depend on these formats.
22908
22909 @ifclear vms
22910 In general, any utility program that works with C will also often work with
22911 Ada programs generated by GNAT. This includes software utilities such as
22912 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22913 as Purify.
22914 @end ifclear
22915
22916 @node The External Symbol Naming Scheme of GNAT
22917 @section The External Symbol Naming Scheme of GNAT
22918
22919 @noindent
22920 In order to interpret the output from GNAT, when using tools that are
22921 originally intended for use with other languages, it is useful to
22922 understand the conventions used to generate link names from the Ada
22923 entity names.
22924
22925 All link names are in all lowercase letters. With the exception of library
22926 procedure names, the mechanism used is simply to use the full expanded
22927 Ada name with dots replaced by double underscores. For example, suppose
22928 we have the following package spec:
22929
22930 @smallexample @c ada
22931 @group
22932 @cartouche
22933 package QRS is
22934    MN : Integer;
22935 end QRS;
22936 @end cartouche
22937 @end group
22938 @end smallexample
22939
22940 @noindent
22941 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22942 the corresponding link name is @code{qrs__mn}.
22943 @findex Export
22944 Of course if a @code{pragma Export} is used this may be overridden:
22945
22946 @smallexample @c ada
22947 @group
22948 @cartouche
22949 package Exports is
22950    Var1 : Integer;
22951    pragma Export (Var1, C, External_Name => "var1_name");
22952    Var2 : Integer;
22953    pragma Export (Var2, C, Link_Name => "var2_link_name");
22954 end Exports;
22955 @end cartouche
22956 @end group
22957 @end smallexample
22958
22959 @noindent
22960 In this case, the link name for @var{Var1} is whatever link name the
22961 C compiler would assign for the C function @var{var1_name}. This typically
22962 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22963 system conventions, but other possibilities exist. The link name for
22964 @var{Var2} is @var{var2_link_name}, and this is not operating system
22965 dependent.
22966
22967 @findex _main
22968 One exception occurs for library level procedures. A potential ambiguity
22969 arises between the required name @code{_main} for the C main program,
22970 and the name we would otherwise assign to an Ada library level procedure
22971 called @code{Main} (which might well not be the main program).
22972
22973 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22974 names. So if we have a library level procedure such as
22975
22976 @smallexample @c ada
22977 @group
22978 @cartouche
22979 procedure Hello (S : String);
22980 @end cartouche
22981 @end group
22982 @end smallexample
22983
22984 @noindent
22985 the external name of this procedure will be @var{_ada_hello}.
22986
22987
22988 @node Converting Ada Files to html with gnathtml
22989 @section Converting Ada Files to HTML with @code{gnathtml}
22990
22991 @noindent
22992 This @code{Perl} script allows Ada source files to be browsed using
22993 standard Web browsers. For installation procedure, see the section
22994 @xref{Installing gnathtml}.
22995
22996 Ada reserved keywords are highlighted in a bold font and Ada comments in
22997 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22998 switch to suppress the generation of cross-referencing information, user
22999 defined variables and types will appear in a different color; you will
23000 be able to click on any identifier and go to its declaration.
23001
23002 The command line is as follow:
23003 @smallexample
23004 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23005 @end smallexample
23006
23007 @noindent
23008 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23009 an html file for every ada file, and a global file called @file{index.htm}.
23010 This file is an index of every identifier defined in the files.
23011
23012 The available ^switches^options^ are the following ones:
23013
23014 @table @option
23015 @item -83
23016 @cindex @option{-83} (@code{gnathtml})
23017 Only the Ada 83 subset of keywords will be highlighted.
23018
23019 @item -cc @var{color}
23020 @cindex @option{-cc} (@code{gnathtml})
23021 This option allows you to change the color used for comments. The default
23022 value is green. The color argument can be any name accepted by html.
23023
23024 @item -d
23025 @cindex @option{-d} (@code{gnathtml})
23026 If the Ada files depend on some other files (for instance through
23027 @code{with} clauses, the latter files will also be converted to html.
23028 Only the files in the user project will be converted to html, not the files
23029 in the run-time library itself.
23030
23031 @item -D
23032 @cindex @option{-D} (@code{gnathtml})
23033 This command is the same as @option{-d} above, but @command{gnathtml} will
23034 also look for files in the run-time library, and generate html files for them.
23035
23036 @item -ext @var{extension}
23037 @cindex @option{-ext} (@code{gnathtml})
23038 This option allows you to change the extension of the generated HTML files.
23039 If you do not specify an extension, it will default to @file{htm}.
23040
23041 @item -f
23042 @cindex @option{-f} (@code{gnathtml})
23043 By default, gnathtml will generate html links only for global entities
23044 ('with'ed units, global variables and types,@dots{}).  If you specify
23045 @option{-f} on the command line, then links will be generated for local
23046 entities too.
23047
23048 @item -l @var{number}
23049 @cindex @option{-l} (@code{gnathtml})
23050 If this ^switch^option^ is provided and @var{number} is not 0, then
23051 @code{gnathtml} will number the html files every @var{number} line.
23052
23053 @item -I @var{dir}
23054 @cindex @option{-I} (@code{gnathtml})
23055 Specify a directory to search for library files (@file{.ALI} files) and
23056 source files. You can provide several -I switches on the command line,
23057 and the directories will be parsed in the order of the command line.
23058
23059 @item -o @var{dir}
23060 @cindex @option{-o} (@code{gnathtml})
23061 Specify the output directory for html files. By default, gnathtml will
23062 saved the generated html files in a subdirectory named @file{html/}.
23063
23064 @item -p @var{file}
23065 @cindex @option{-p} (@code{gnathtml})
23066 If you are using Emacs and the most recent Emacs Ada mode, which provides
23067 a full Integrated Development Environment for compiling, checking,
23068 running and debugging applications, you may use @file{.gpr} files
23069 to give the directories where Emacs can find sources and object files.
23070
23071 Using this ^switch^option^, you can tell gnathtml to use these files.
23072 This allows you to get an html version of your application, even if it
23073 is spread over multiple directories.
23074
23075 @item -sc @var{color}
23076 @cindex @option{-sc} (@code{gnathtml})
23077 This ^switch^option^ allows you to change the color used for symbol
23078 definitions.
23079 The default value is red. The color argument can be any name accepted by html.
23080
23081 @item -t @var{file}
23082 @cindex @option{-t} (@code{gnathtml})
23083 This ^switch^option^ provides the name of a file. This file contains a list of
23084 file names to be converted, and the effect is exactly as though they had
23085 appeared explicitly on the command line. This
23086 is the recommended way to work around the command line length limit on some
23087 systems.
23088
23089 @end table
23090
23091 @node Installing gnathtml
23092 @section Installing @code{gnathtml}
23093
23094 @noindent
23095 @code{Perl} needs to be installed on your machine to run this script.
23096 @code{Perl} is freely available for almost every architecture and
23097 Operating System via the Internet.
23098
23099 On Unix systems, you  may want to modify  the  first line of  the script
23100 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23101 is. The syntax of this line is:
23102 @smallexample
23103 #!full_path_name_to_perl
23104 @end smallexample
23105
23106 @noindent
23107 Alternatively, you may run the script using the following command line:
23108
23109 @smallexample
23110 $ perl gnathtml.pl @ovar{switches} @var{files}
23111 @end smallexample
23112
23113 @ifset vms
23114 @node LSE
23115 @section LSE
23116 @findex LSE
23117
23118 @noindent
23119 The GNAT distribution provides an Ada 95 template for the HP Language
23120 Sensitive Editor (LSE), a component of DECset. In order to
23121 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23122
23123 @node Profiling
23124 @section Profiling
23125 @findex PCA
23126
23127 @noindent
23128 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23129 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23130 the collection phase with the /DEBUG qualifier.
23131
23132 @smallexample
23133 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23134 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23135 $ RUN/DEBUG <PROGRAM_NAME>
23136 @end smallexample
23137 @noindent
23138 @end ifset
23139
23140 @ifclear vms
23141 @c ******************************
23142 @node Code Coverage and Profiling
23143 @chapter Code Coverage and Profiling
23144 @cindex Code Coverage
23145 @cindex Profiling
23146
23147 @noindent
23148 This chapter describes how to use @code{gcov} - coverage testing tool - and
23149 @code{gprof} - profiler tool - on your Ada programs.
23150
23151 @menu
23152 * Code Coverage of Ada Programs using gcov::
23153 * Profiling an Ada Program using gprof::
23154 @end menu
23155
23156 @node Code Coverage of Ada Programs using gcov
23157 @section Code Coverage of Ada Programs using gcov
23158 @cindex gcov
23159 @cindex -fprofile-arcs
23160 @cindex -ftest-coverage
23161 @cindex -coverage
23162 @cindex Code Coverage
23163
23164 @noindent
23165 @code{gcov} is a test coverage program: it analyzes the execution of a given
23166 program on selected tests, to help you determine the portions of the program
23167 that are still untested.
23168
23169 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23170 User's Guide. You can refer to this documentation for a more complete
23171 description.
23172
23173 This chapter provides a quick startup guide, and
23174 details some Gnat-specific features.
23175
23176 @menu
23177 * Quick startup guide::
23178 * Gnat specifics::
23179 @end menu
23180
23181 @node Quick startup guide
23182 @subsection Quick startup guide
23183
23184 In order to perform coverage analysis of a program using @code{gcov}, 3
23185 steps are needed:
23186
23187 @itemize @bullet
23188 @item
23189 Code instrumentation during the compilation process
23190 @item
23191 Execution of the instrumented program
23192 @item
23193 Execution of the @code{gcov} tool to generate the result.
23194 @end itemize
23195
23196 The code instrumentation needed by gcov is created at the object level:
23197 The source code is not modified in any way, because the instrumentation code is
23198 inserted by gcc during the compilation process. To compile your code with code
23199 coverage activated, you need to recompile your whole project using the
23200 switches
23201 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23202 @code{-fprofile-arcs}.
23203
23204 @smallexample
23205 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23206    -largs -fprofile-arcs
23207 @end smallexample
23208
23209 This compilation process will create @file{.gcno} files together with
23210 the usual object files.
23211
23212 Once the program is compiled with coverage instrumentation, you can
23213 run it as many times as needed - on portions of a test suite for
23214 example. The first execution will produce @file{.gcda} files at the
23215 same location as the @file{.gcno} files.  The following executions
23216 will update those files, so that a cumulative result of the covered
23217 portions of the program is generated.
23218
23219 Finally, you need to call the @code{gcov} tool. The different options of
23220 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23221
23222 This will create annotated source files with a @file{.gcov} extension:
23223 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23224
23225 @node Gnat specifics
23226 @subsection Gnat specifics
23227
23228 Because Ada semantics, portions of the source code may be shared among
23229 several object files. This is the case for example when generics are
23230 involved, when inlining is active  or when declarations generate  initialisation
23231 calls. In order to take
23232 into account this shared code, you need to call @code{gcov} on all
23233 source files of the tested program at once.
23234
23235 The list of source files might exceed the system's maximum command line
23236 length. In order to bypass this limitation, a new mechanism has been
23237 implemented in @code{gcov}: you can now list all your project's files into a
23238 text file, and provide this file to gcov as a parameter,  preceded by a @@
23239 (e.g. @samp{gcov @@mysrclist.txt}).
23240
23241 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23242 not supported as there can be unresolved symbols during the final link.
23243
23244 @node Profiling an Ada Program using gprof
23245 @section Profiling an Ada Program using gprof
23246 @cindex gprof
23247 @cindex -pg
23248 @cindex Profiling
23249
23250 @noindent
23251 This section is not meant to be an exhaustive documentation of @code{gprof}.
23252 Full documentation for it can be found in the GNU Profiler User's Guide
23253 documentation that is part of this GNAT distribution.
23254
23255 Profiling a program helps determine the parts of a program that are executed
23256 most often, and are therefore the most time-consuming.
23257
23258 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23259 better handle Ada programs and multitasking.
23260 It is currently supported on the following platforms
23261 @itemize @bullet
23262 @item
23263 linux x86/x86_64
23264 @item
23265 solaris sparc/sparc64/x86
23266 @item
23267 windows x86
23268 @end itemize
23269
23270 @noindent
23271 In order to profile a program using @code{gprof}, 3 steps are needed:
23272
23273 @itemize @bullet
23274 @item
23275 Code instrumentation, requiring a full recompilation of the project with the
23276 proper switches.
23277 @item
23278 Execution of the program under the analysis conditions, i.e. with the desired
23279 input.
23280 @item
23281 Analysis of the results using the @code{gprof} tool.
23282 @end itemize
23283
23284 @noindent
23285 The following sections detail the different steps, and indicate how
23286 to interpret the results:
23287 @menu
23288 * Compilation for profiling::
23289 * Program execution::
23290 * Running gprof::
23291 * Interpretation of profiling results::
23292 @end menu
23293
23294 @node Compilation for profiling
23295 @subsection Compilation for profiling
23296 @cindex -pg
23297 @cindex Profiling
23298
23299 In order to profile a program the first step is to tell the compiler
23300 to generate the necessary profiling information. The compiler switch to be used
23301 is @code{-pg}, which must be added to other compilation switches. This
23302 switch needs to be specified both during compilation and link stages, and can
23303 be specified once when using gnatmake:
23304
23305 @smallexample
23306 gnatmake -f -pg -P my_project
23307 @end smallexample
23308
23309 @noindent
23310 Note that only the objects that were compiled with the @samp{-pg} switch will be
23311 profiled; if you need to profile your whole project, use the
23312 @samp{-f} gnatmake switch to force full recompilation.
23313
23314 @node Program execution
23315 @subsection Program execution
23316
23317 @noindent
23318 Once the program has been compiled for profiling, you can run it as usual.
23319
23320 The only constraint imposed by profiling is that the program must terminate
23321 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23322 properly analyzed.
23323
23324 Once the program completes execution, a data file called @file{gmon.out} is
23325 generated in the directory where the program was launched from. If this file
23326 already exists, it will be overwritten.
23327
23328 @node Running gprof
23329 @subsection Running gprof
23330
23331 @noindent
23332 The @code{gprof} tool is called as follow:
23333
23334 @smallexample
23335 gprof my_prog gmon.out
23336 @end smallexample
23337
23338 @noindent
23339 or simpler:
23340
23341 @smallexample
23342 gprof my_prog
23343 @end smallexample
23344
23345 @noindent
23346 The complete form of the gprof command line is the following:
23347
23348 @smallexample
23349 gprof [^switches^options^] [executable [data-file]]
23350 @end smallexample
23351
23352 @noindent
23353 @code{gprof} supports numerous ^switch^options^. The order of these
23354 ^switch^options^ does not matter. The full list of options can be found in
23355 the GNU Profiler User's Guide documentation that comes with this documentation.
23356
23357 The following is the subset of those switches that is most relevant:
23358
23359 @table @option
23360
23361 @item --demangle[=@var{style}]
23362 @itemx --no-demangle
23363 @cindex @option{--demangle} (@code{gprof})
23364 These options control whether symbol names should be demangled when
23365 printing output.  The default is to demangle C++ symbols.  The
23366 @code{--no-demangle} option may be used to turn off demangling. Different
23367 compilers have different mangling styles.  The optional demangling style
23368 argument can be used to choose an appropriate demangling style for your
23369 compiler, in particular Ada symbols generated by GNAT can be demangled using
23370 @code{--demangle=gnat}.
23371
23372 @item -e @var{function_name}
23373 @cindex @option{-e} (@code{gprof})
23374 The @samp{-e @var{function}} option tells @code{gprof} not to print
23375 information about the function @var{function_name} (and its
23376 children@dots{}) in the call graph.  The function will still be listed
23377 as a child of any functions that call it, but its index number will be
23378 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23379 given; only one @var{function_name} may be indicated with each @samp{-e}
23380 option.
23381
23382 @item -E @var{function_name}
23383 @cindex @option{-E} (@code{gprof})
23384 The @code{-E @var{function}} option works like the @code{-e} option, but
23385 execution time spent in the function (and children who were not called from
23386 anywhere else), will not be used to compute the percentages-of-time for
23387 the call graph.  More than one @samp{-E} option may be given; only one
23388 @var{function_name} may be indicated with each @samp{-E} option.
23389
23390 @item -f @var{function_name}
23391 @cindex @option{-f} (@code{gprof})
23392 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23393 call graph to the function @var{function_name} and its children (and
23394 their children@dots{}).  More than one @samp{-f} option may be given;
23395 only one @var{function_name} may be indicated with each @samp{-f}
23396 option.
23397
23398 @item -F @var{function_name}
23399 @cindex @option{-F} (@code{gprof})
23400 The @samp{-F @var{function}} option works like the @code{-f} option, but
23401 only time spent in the function and its children (and their
23402 children@dots{}) will be used to determine total-time and
23403 percentages-of-time for the call graph.  More than one @samp{-F} option
23404 may be given; only one @var{function_name} may be indicated with each
23405 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23406
23407 @end table
23408
23409 @node Interpretation of profiling results
23410 @subsection Interpretation of profiling results
23411
23412 @noindent
23413
23414 The results of the profiling analysis are represented by two arrays: the
23415 'flat profile' and the 'call graph'. Full documentation of those outputs
23416 can be found in the GNU Profiler User's Guide.
23417
23418 The flat profile shows the time spent in each function of the program, and how
23419 many time it has been called. This allows you to locate easily the most
23420 time-consuming functions.
23421
23422 The call graph shows, for each subprogram, the subprograms that call it,
23423 and the subprograms that it calls. It also provides an estimate of the time
23424 spent in each of those callers/called subprograms.
23425 @end ifclear
23426
23427 @c ******************************
23428 @node Running and Debugging Ada Programs
23429 @chapter Running and Debugging Ada Programs
23430 @cindex Debugging
23431
23432 @noindent
23433 This chapter discusses how to debug Ada programs.
23434 @ifset vms
23435 It applies to GNAT on the Alpha OpenVMS platform;
23436 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23437 since HP has implemented Ada support in the OpenVMS debugger on I64.
23438 @end ifset
23439
23440 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23441
23442 @enumerate
23443 @item
23444 The illegality may be a violation of the static semantics of Ada. In
23445 that case GNAT diagnoses the constructs in the program that are illegal.
23446 It is then a straightforward matter for the user to modify those parts of
23447 the program.
23448
23449 @item
23450 The illegality may be a violation of the dynamic semantics of Ada. In
23451 that case the program compiles and executes, but may generate incorrect
23452 results, or may terminate abnormally with some exception.
23453
23454 @item
23455 When presented with a program that contains convoluted errors, GNAT
23456 itself may terminate abnormally without providing full diagnostics on
23457 the incorrect user program.
23458 @end enumerate
23459
23460 @menu
23461 * The GNAT Debugger GDB::
23462 * Running GDB::
23463 * Introduction to GDB Commands::
23464 * Using Ada Expressions::
23465 * Calling User-Defined Subprograms::
23466 * Using the Next Command in a Function::
23467 * Ada Exceptions::
23468 * Ada Tasks::
23469 * Debugging Generic Units::
23470 * GNAT Abnormal Termination or Failure to Terminate::
23471 * Naming Conventions for GNAT Source Files::
23472 * Getting Internal Debugging Information::
23473 * Stack Traceback::
23474 @end menu
23475
23476 @cindex Debugger
23477 @findex gdb
23478
23479 @node The GNAT Debugger GDB
23480 @section The GNAT Debugger GDB
23481
23482 @noindent
23483 @code{GDB} is a general purpose, platform-independent debugger that
23484 can be used to debug mixed-language programs compiled with @command{gcc},
23485 and in particular is capable of debugging Ada programs compiled with
23486 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23487 complex Ada data structures.
23488
23489 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23490 @ifset vms
23491 located in the GNU:[DOCS] directory,
23492 @end ifset
23493 for full details on the usage of @code{GDB}, including a section on
23494 its usage on programs. This manual should be consulted for full
23495 details. The section that follows is a brief introduction to the
23496 philosophy and use of @code{GDB}.
23497
23498 When GNAT programs are compiled, the compiler optionally writes debugging
23499 information into the generated object file, including information on
23500 line numbers, and on declared types and variables. This information is
23501 separate from the generated code. It makes the object files considerably
23502 larger, but it does not add to the size of the actual executable that
23503 will be loaded into memory, and has no impact on run-time performance. The
23504 generation of debug information is triggered by the use of the
23505 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23506 used to carry out the compilations. It is important to emphasize that
23507 the use of these options does not change the generated code.
23508
23509 The debugging information is written in standard system formats that
23510 are used by many tools, including debuggers and profilers. The format
23511 of the information is typically designed to describe C types and
23512 semantics, but GNAT implements a translation scheme which allows full
23513 details about Ada types and variables to be encoded into these
23514 standard C formats. Details of this encoding scheme may be found in
23515 the file exp_dbug.ads in the GNAT source distribution. However, the
23516 details of this encoding are, in general, of no interest to a user,
23517 since @code{GDB} automatically performs the necessary decoding.
23518
23519 When a program is bound and linked, the debugging information is
23520 collected from the object files, and stored in the executable image of
23521 the program. Again, this process significantly increases the size of
23522 the generated executable file, but it does not increase the size of
23523 the executable program itself. Furthermore, if this program is run in
23524 the normal manner, it runs exactly as if the debug information were
23525 not present, and takes no more actual memory.
23526
23527 However, if the program is run under control of @code{GDB}, the
23528 debugger is activated.  The image of the program is loaded, at which
23529 point it is ready to run.  If a run command is given, then the program
23530 will run exactly as it would have if @code{GDB} were not present. This
23531 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23532 entirely non-intrusive until a breakpoint is encountered.  If no
23533 breakpoint is ever hit, the program will run exactly as it would if no
23534 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23535 the debugging information and can respond to user commands to inspect
23536 variables, and more generally to report on the state of execution.
23537
23538 @c **************
23539 @node Running GDB
23540 @section Running GDB
23541
23542 @noindent
23543 This section describes how to initiate the debugger.
23544 @c The above sentence is really just filler, but it was otherwise
23545 @c clumsy to get the first paragraph nonindented given the conditional
23546 @c nature of the description
23547
23548 @ifclear vms
23549 The debugger can be launched from a @code{GPS} menu or
23550 directly from the command line. The description below covers the latter use.
23551 All the commands shown can be used in the @code{GPS} debug console window,
23552 but there are usually more GUI-based ways to achieve the same effect.
23553 @end ifclear
23554
23555 The command to run @code{GDB} is
23556
23557 @smallexample
23558 $ ^gdb program^GDB PROGRAM^
23559 @end smallexample
23560
23561 @noindent
23562 where @code{^program^PROGRAM^} is the name of the executable file. This
23563 activates the debugger and results in a prompt for debugger commands.
23564 The simplest command is simply @code{run}, which causes the program to run
23565 exactly as if the debugger were not present. The following section
23566 describes some of the additional commands that can be given to @code{GDB}.
23567
23568 @c *******************************
23569 @node Introduction to GDB Commands
23570 @section Introduction to GDB Commands
23571
23572 @noindent
23573 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
23574 Debugging with GDB, gdb, Debugging with GDB},
23575 @ifset vms
23576 located in the GNU:[DOCS] directory,
23577 @end ifset
23578 for extensive documentation on the use
23579 of these commands, together with examples of their use. Furthermore,
23580 the command @command{help} invoked from within GDB activates a simple help
23581 facility which summarizes the available commands and their options.
23582 In this section we summarize a few of the most commonly
23583 used commands to give an idea of what @code{GDB} is about. You should create
23584 a simple program with debugging information and experiment with the use of
23585 these @code{GDB} commands on the program as you read through the
23586 following section.
23587
23588 @table @code
23589 @item set args @var{arguments}
23590 The @var{arguments} list above is a list of arguments to be passed to
23591 the program on a subsequent run command, just as though the arguments
23592 had been entered on a normal invocation of the program. The @code{set args}
23593 command is not needed if the program does not require arguments.
23594
23595 @item run
23596 The @code{run} command causes execution of the program to start from
23597 the beginning. If the program is already running, that is to say if
23598 you are currently positioned at a breakpoint, then a prompt will ask
23599 for confirmation that you want to abandon the current execution and
23600 restart.
23601
23602 @item breakpoint @var{location}
23603 The breakpoint command sets a breakpoint, that is to say a point at which
23604 execution will halt and @code{GDB} will await further
23605 commands. @var{location} is
23606 either a line number within a file, given in the format @code{file:linenumber},
23607 or it is the name of a subprogram. If you request that a breakpoint be set on
23608 a subprogram that is overloaded, a prompt will ask you to specify on which of
23609 those subprograms you want to breakpoint. You can also
23610 specify that all of them should be breakpointed. If the program is run
23611 and execution encounters the breakpoint, then the program
23612 stops and @code{GDB} signals that the breakpoint was encountered by
23613 printing the line of code before which the program is halted.
23614
23615 @item breakpoint exception @var{name}
23616 A special form of the breakpoint command which breakpoints whenever
23617 exception @var{name} is raised.
23618 If @var{name} is omitted,
23619 then a breakpoint will occur when any exception is raised.
23620
23621 @item print @var{expression}
23622 This will print the value of the given expression. Most simple
23623 Ada expression formats are properly handled by @code{GDB}, so the expression
23624 can contain function calls, variables, operators, and attribute references.
23625
23626 @item continue
23627 Continues execution following a breakpoint, until the next breakpoint or the
23628 termination of the program.
23629
23630 @item step
23631 Executes a single line after a breakpoint. If the next statement
23632 is a subprogram call, execution continues into (the first statement of)
23633 the called subprogram.
23634
23635 @item next
23636 Executes a single line. If this line is a subprogram call, executes and
23637 returns from the call.
23638
23639 @item list
23640 Lists a few lines around the current source location. In practice, it
23641 is usually more convenient to have a separate edit window open with the
23642 relevant source file displayed. Successive applications of this command
23643 print subsequent lines. The command can be given an argument which is a
23644 line number, in which case it displays a few lines around the specified one.
23645
23646 @item backtrace
23647 Displays a backtrace of the call chain. This command is typically
23648 used after a breakpoint has occurred, to examine the sequence of calls that
23649 leads to the current breakpoint. The display includes one line for each
23650 activation record (frame) corresponding to an active subprogram.
23651
23652 @item up
23653 At a breakpoint, @code{GDB} can display the values of variables local
23654 to the current frame. The command @code{up} can be used to
23655 examine the contents of other active frames, by moving the focus up
23656 the stack, that is to say from callee to caller, one frame at a time.
23657
23658 @item down
23659 Moves the focus of @code{GDB} down from the frame currently being
23660 examined to the frame of its callee (the reverse of the previous command),
23661
23662 @item frame @var{n}
23663 Inspect the frame with the given number. The value 0 denotes the frame
23664 of the current breakpoint, that is to say the top of the call stack.
23665
23666 @end table
23667
23668 @noindent
23669 The above list is a very short introduction to the commands that
23670 @code{GDB} provides. Important additional capabilities, including conditional
23671 breakpoints, the ability to execute command sequences on a breakpoint,
23672 the ability to debug at the machine instruction level and many other
23673 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23674 Debugging with GDB}.  Note that most commands can be abbreviated
23675 (for example, c for continue, bt for backtrace).
23676
23677 @node Using Ada Expressions
23678 @section Using Ada Expressions
23679 @cindex Ada expressions
23680
23681 @noindent
23682 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23683 extensions. The philosophy behind the design of this subset is
23684
23685 @itemize @bullet
23686 @item
23687 That @code{GDB} should provide basic literals and access to operations for
23688 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23689 leaving more sophisticated computations to subprograms written into the
23690 program (which therefore may be called from @code{GDB}).
23691
23692 @item
23693 That type safety and strict adherence to Ada language restrictions
23694 are not particularly important to the @code{GDB} user.
23695
23696 @item
23697 That brevity is important to the @code{GDB} user.
23698 @end itemize
23699
23700 @noindent
23701 Thus, for brevity, the debugger acts as if there were
23702 implicit @code{with} and @code{use} clauses in effect for all user-written
23703 packages, thus making it unnecessary to fully qualify most names with
23704 their packages, regardless of context. Where this causes ambiguity,
23705 @code{GDB} asks the user's intent.
23706
23707 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23708 GDB, gdb, Debugging with GDB}.
23709
23710 @node Calling User-Defined Subprograms
23711 @section Calling User-Defined Subprograms
23712
23713 @noindent
23714 An important capability of @code{GDB} is the ability to call user-defined
23715 subprograms while debugging. This is achieved simply by entering
23716 a subprogram call statement in the form:
23717
23718 @smallexample
23719 call subprogram-name (parameters)
23720 @end smallexample
23721
23722 @noindent
23723 The keyword @code{call} can be omitted in the normal case where the
23724 @code{subprogram-name} does not coincide with any of the predefined
23725 @code{GDB} commands.
23726
23727 The effect is to invoke the given subprogram, passing it the
23728 list of parameters that is supplied. The parameters can be expressions and
23729 can include variables from the program being debugged. The
23730 subprogram must be defined
23731 at the library level within your program, and @code{GDB} will call the
23732 subprogram within the environment of your program execution (which
23733 means that the subprogram is free to access or even modify variables
23734 within your program).
23735
23736 The most important use of this facility is in allowing the inclusion of
23737 debugging routines that are tailored to particular data structures
23738 in your program. Such debugging routines can be written to provide a suitably
23739 high-level description of an abstract type, rather than a low-level dump
23740 of its physical layout. After all, the standard
23741 @code{GDB print} command only knows the physical layout of your
23742 types, not their abstract meaning. Debugging routines can provide information
23743 at the desired semantic level and are thus enormously useful.
23744
23745 For example, when debugging GNAT itself, it is crucial to have access to
23746 the contents of the tree nodes used to represent the program internally.
23747 But tree nodes are represented simply by an integer value (which in turn
23748 is an index into a table of nodes).
23749 Using the @code{print} command on a tree node would simply print this integer
23750 value, which is not very useful. But the PN routine (defined in file
23751 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23752 a useful high level representation of the tree node, which includes the
23753 syntactic category of the node, its position in the source, the integers
23754 that denote descendant nodes and parent node, as well as varied
23755 semantic information. To study this example in more detail, you might want to
23756 look at the body of the PN procedure in the stated file.
23757
23758 @node Using the Next Command in a Function
23759 @section Using the Next Command in a Function
23760
23761 @noindent
23762 When you use the @code{next} command in a function, the current source
23763 location will advance to the next statement as usual. A special case
23764 arises in the case of a @code{return} statement.
23765
23766 Part of the code for a return statement is the ``epilog'' of the function.
23767 This is the code that returns to the caller. There is only one copy of
23768 this epilog code, and it is typically associated with the last return
23769 statement in the function if there is more than one return. In some
23770 implementations, this epilog is associated with the first statement
23771 of the function.
23772
23773 The result is that if you use the @code{next} command from a return
23774 statement that is not the last return statement of the function you
23775 may see a strange apparent jump to the last return statement or to
23776 the start of the function. You should simply ignore this odd jump.
23777 The value returned is always that from the first return statement
23778 that was stepped through.
23779
23780 @node Ada Exceptions
23781 @section Breaking on Ada Exceptions
23782 @cindex Exceptions
23783
23784 @noindent
23785 You can set breakpoints that trip when your program raises
23786 selected exceptions.
23787
23788 @table @code
23789 @item break exception
23790 Set a breakpoint that trips whenever (any task in the) program raises
23791 any exception.
23792
23793 @item break exception @var{name}
23794 Set a breakpoint that trips whenever (any task in the) program raises
23795 the exception @var{name}.
23796
23797 @item break exception unhandled
23798 Set a breakpoint that trips whenever (any task in the) program raises an
23799 exception for which there is no handler.
23800
23801 @item info exceptions
23802 @itemx info exceptions @var{regexp}
23803 The @code{info exceptions} command permits the user to examine all defined
23804 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23805 argument, prints out only those exceptions whose name matches @var{regexp}.
23806 @end table
23807
23808 @node Ada Tasks
23809 @section Ada Tasks
23810 @cindex Tasks
23811
23812 @noindent
23813 @code{GDB} allows the following task-related commands:
23814
23815 @table @code
23816 @item info tasks
23817 This command shows a list of current Ada tasks, as in the following example:
23818
23819 @smallexample
23820 @iftex
23821 @leftskip=0cm
23822 @end iftex
23823 (gdb) info tasks
23824   ID       TID P-ID   Thread Pri State                 Name
23825    1   8088000   0   807e000  15 Child Activation Wait main_task
23826    2   80a4000   1   80ae000  15 Accept/Select Wait    b
23827    3   809a800   1   80a4800  15 Child Activation Wait a
23828 *  4   80ae800   3   80b8000  15 Running               c
23829 @end smallexample
23830
23831 @noindent
23832 In this listing, the asterisk before the first task indicates it to be the
23833 currently running task. The first column lists the task ID that is used
23834 to refer to tasks in the following commands.
23835
23836 @item break @var{linespec} task @var{taskid}
23837 @itemx break @var{linespec} task @var{taskid} if @dots{}
23838 @cindex Breakpoints and tasks
23839 These commands are like the @code{break @dots{} thread @dots{}}.
23840 @var{linespec} specifies source lines.
23841
23842 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23843 to specify that you only want @code{GDB} to stop the program when a
23844 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23845 numeric task identifiers assigned by @code{GDB}, shown in the first
23846 column of the @samp{info tasks} display.
23847
23848 If you do not specify @samp{task @var{taskid}} when you set a
23849 breakpoint, the breakpoint applies to @emph{all} tasks of your
23850 program.
23851
23852 You can use the @code{task} qualifier on conditional breakpoints as
23853 well; in this case, place @samp{task @var{taskid}} before the
23854 breakpoint condition (before the @code{if}).
23855
23856 @item task @var{taskno}
23857 @cindex Task switching
23858
23859 This command allows to switch to the task referred by @var{taskno}. In
23860 particular, This allows to browse the backtrace of the specified
23861 task. It is advised to switch back to the original task before
23862 continuing execution otherwise the scheduling of the program may be
23863 perturbed.
23864 @end table
23865
23866 @noindent
23867 For more detailed information on the tasking support,
23868 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23869
23870 @node Debugging Generic Units
23871 @section Debugging Generic Units
23872 @cindex Debugging Generic Units
23873 @cindex Generics
23874
23875 @noindent
23876 GNAT always uses code expansion for generic instantiation. This means that
23877 each time an instantiation occurs, a complete copy of the original code is
23878 made, with appropriate substitutions of formals by actuals.
23879
23880 It is not possible to refer to the original generic entities in
23881 @code{GDB}, but it is always possible to debug a particular instance of
23882 a generic, by using the appropriate expanded names. For example, if we have
23883
23884 @smallexample @c ada
23885 @group
23886 @cartouche
23887 procedure g is
23888
23889    generic package k is
23890       procedure kp (v1 : in out integer);
23891    end k;
23892
23893    package body k is
23894       procedure kp (v1 : in out integer) is
23895       begin
23896          v1 := v1 + 1;
23897       end kp;
23898    end k;
23899
23900    package k1 is new k;
23901    package k2 is new k;
23902
23903    var : integer := 1;
23904
23905 begin
23906    k1.kp (var);
23907    k2.kp (var);
23908    k1.kp (var);
23909    k2.kp (var);
23910 end;
23911 @end cartouche
23912 @end group
23913 @end smallexample
23914
23915 @noindent
23916 Then to break on a call to procedure kp in the k2 instance, simply
23917 use the command:
23918
23919 @smallexample
23920 (gdb) break g.k2.kp
23921 @end smallexample
23922
23923 @noindent
23924 When the breakpoint occurs, you can step through the code of the
23925 instance in the normal manner and examine the values of local variables, as for
23926 other units.
23927
23928 @node GNAT Abnormal Termination or Failure to Terminate
23929 @section GNAT Abnormal Termination or Failure to Terminate
23930 @cindex GNAT Abnormal Termination or Failure to Terminate
23931
23932 @noindent
23933 When presented with programs that contain serious errors in syntax
23934 or semantics,
23935 GNAT may on rare occasions  experience problems in operation, such
23936 as aborting with a
23937 segmentation fault or illegal memory access, raising an internal
23938 exception, terminating abnormally, or failing to terminate at all.
23939 In such cases, you can activate
23940 various features of GNAT that can help you pinpoint the construct in your
23941 program that is the likely source of the problem.
23942
23943 The following strategies are presented in increasing order of
23944 difficulty, corresponding to your experience in using GNAT and your
23945 familiarity with compiler internals.
23946
23947 @enumerate
23948 @item
23949 Run @command{gcc} with the @option{-gnatf}. This first
23950 switch causes all errors on a given line to be reported. In its absence,
23951 only the first error on a line is displayed.
23952
23953 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23954 are encountered, rather than after compilation is terminated. If GNAT
23955 terminates prematurely or goes into an infinite loop, the last error
23956 message displayed may help to pinpoint the culprit.
23957
23958 @item
23959 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23960 mode, @command{gcc} produces ongoing information about the progress of the
23961 compilation and provides the name of each procedure as code is
23962 generated. This switch allows you to find which Ada procedure was being
23963 compiled when it encountered a code generation problem.
23964
23965 @item
23966 @cindex @option{-gnatdc} switch
23967 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23968 switch that does for the front-end what @option{^-v^VERBOSE^} does
23969 for the back end. The system prints the name of each unit,
23970 either a compilation unit or nested unit, as it is being analyzed.
23971 @item
23972 Finally, you can start
23973 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23974 front-end of GNAT, and can be run independently (normally it is just
23975 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23976 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23977 @code{where} command is the first line of attack; the variable
23978 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23979 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23980 which the execution stopped, and @code{input_file name} indicates the name of
23981 the source file.
23982 @end enumerate
23983
23984 @node Naming Conventions for GNAT Source Files
23985 @section Naming Conventions for GNAT Source Files
23986
23987 @noindent
23988 In order to examine the workings of the GNAT system, the following
23989 brief description of its organization may be helpful:
23990
23991 @itemize @bullet
23992 @item
23993 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23994
23995 @item
23996 All files prefixed with @file{^par^PAR^} are components of the parser. The
23997 numbers correspond to chapters of the Ada Reference Manual. For example,
23998 parsing of select statements can be found in @file{par-ch9.adb}.
23999
24000 @item
24001 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24002 numbers correspond to chapters of the Ada standard. For example, all
24003 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24004 addition, some features of the language require sufficient special processing
24005 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24006 dynamic dispatching, etc.
24007
24008 @item
24009 All files prefixed with @file{^exp^EXP^} perform normalization and
24010 expansion of the intermediate representation (abstract syntax tree, or AST).
24011 these files use the same numbering scheme as the parser and semantics files.
24012 For example, the construction of record initialization procedures is done in
24013 @file{exp_ch3.adb}.
24014
24015 @item
24016 The files prefixed with @file{^bind^BIND^} implement the binder, which
24017 verifies the consistency of the compilation, determines an order of
24018 elaboration, and generates the bind file.
24019
24020 @item
24021 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24022 data structures used by the front-end.
24023
24024 @item
24025 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24026 the abstract syntax tree as produced by the parser.
24027
24028 @item
24029 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24030 all entities, computed during semantic analysis.
24031
24032 @item
24033 Library management issues are dealt with in files with prefix
24034 @file{^lib^LIB^}.
24035
24036 @item
24037 @findex Ada
24038 @cindex Annex A
24039 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24040 defined in Annex A.
24041
24042 @item
24043 @findex Interfaces
24044 @cindex Annex B
24045 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24046 defined in Annex B.
24047
24048 @item
24049 @findex System
24050 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24051 both language-defined children and GNAT run-time routines.
24052
24053 @item
24054 @findex GNAT
24055 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24056 general-purpose packages, fully documented in their specs. All
24057 the other @file{.c} files are modifications of common @command{gcc} files.
24058 @end itemize
24059
24060 @node Getting Internal Debugging Information
24061 @section Getting Internal Debugging Information
24062
24063 @noindent
24064 Most compilers have internal debugging switches and modes. GNAT
24065 does also, except GNAT internal debugging switches and modes are not
24066 secret. A summary and full description of all the compiler and binder
24067 debug flags are in the file @file{debug.adb}. You must obtain the
24068 sources of the compiler to see the full detailed effects of these flags.
24069
24070 The switches that print the source of the program (reconstructed from
24071 the internal tree) are of general interest for user programs, as are the
24072 options to print
24073 the full internal tree, and the entity table (the symbol table
24074 information). The reconstructed source provides a readable version of the
24075 program after the front-end has completed analysis and  expansion,
24076 and is useful when studying the performance of specific constructs.
24077 For example, constraint checks are indicated, complex aggregates
24078 are replaced with loops and assignments, and tasking primitives
24079 are replaced with run-time calls.
24080
24081 @node Stack Traceback
24082 @section Stack Traceback
24083 @cindex traceback
24084 @cindex stack traceback
24085 @cindex stack unwinding
24086
24087 @noindent
24088 Traceback is a mechanism to display the sequence of subprogram calls that
24089 leads to a specified execution point in a program. Often (but not always)
24090 the execution point is an instruction at which an exception has been raised.
24091 This mechanism is also known as @i{stack unwinding} because it obtains
24092 its information by scanning the run-time stack and recovering the activation
24093 records of all active subprograms. Stack unwinding is one of the most
24094 important tools for program debugging.
24095
24096 The first entry stored in traceback corresponds to the deepest calling level,
24097 that is to say the subprogram currently executing the instruction
24098 from which we want to obtain the traceback.
24099
24100 Note that there is no runtime performance penalty when stack traceback
24101 is enabled, and no exception is raised during program execution.
24102
24103 @menu
24104 * Non-Symbolic Traceback::
24105 * Symbolic Traceback::
24106 @end menu
24107
24108 @node Non-Symbolic Traceback
24109 @subsection Non-Symbolic Traceback
24110 @cindex traceback, non-symbolic
24111
24112 @noindent
24113 Note: this feature is not supported on all platforms. See
24114 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24115 platforms.
24116
24117 @menu
24118 * Tracebacks From an Unhandled Exception::
24119 * Tracebacks From Exception Occurrences (non-symbolic)::
24120 * Tracebacks From Anywhere in a Program (non-symbolic)::
24121 @end menu
24122
24123 @node Tracebacks From an Unhandled Exception
24124 @subsubsection Tracebacks From an Unhandled Exception
24125
24126 @noindent
24127 A runtime non-symbolic traceback is a list of addresses of call instructions.
24128 To enable this feature you must use the @option{-E}
24129 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24130 of exception information. You can retrieve this information using the
24131 @code{addr2line} tool.
24132
24133 Here is a simple example:
24134
24135 @smallexample @c ada
24136 @cartouche
24137 procedure STB is
24138
24139    procedure P1 is
24140    begin
24141       raise Constraint_Error;
24142    end P1;
24143
24144    procedure P2 is
24145    begin
24146       P1;
24147    end P2;
24148
24149 begin
24150    P2;
24151 end STB;
24152 @end cartouche
24153 @end smallexample
24154
24155 @smallexample
24156 $ gnatmake stb -bargs -E
24157 $ stb
24158
24159 Execution terminated by unhandled exception
24160 Exception name: CONSTRAINT_ERROR
24161 Message: stb.adb:5
24162 Call stack traceback locations:
24163 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24164 @end smallexample
24165
24166 @noindent
24167 As we see the traceback lists a sequence of addresses for the unhandled
24168 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24169 guess that this exception come from procedure P1. To translate these
24170 addresses into the source lines where the calls appear, the
24171 @code{addr2line} tool, described below, is invaluable. The use of this tool
24172 requires the program to be compiled with debug information.
24173
24174 @smallexample
24175 $ gnatmake -g stb -bargs -E
24176 $ stb
24177
24178 Execution terminated by unhandled exception
24179 Exception name: CONSTRAINT_ERROR
24180 Message: stb.adb:5
24181 Call stack traceback locations:
24182 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24183
24184 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24185    0x4011f1 0x77e892a4
24186
24187 00401373 at d:/stb/stb.adb:5
24188 0040138B at d:/stb/stb.adb:10
24189 0040139C at d:/stb/stb.adb:14
24190 00401335 at d:/stb/b~stb.adb:104
24191 004011C4 at /build/@dots{}/crt1.c:200
24192 004011F1 at /build/@dots{}/crt1.c:222
24193 77E892A4 in ?? at ??:0
24194 @end smallexample
24195
24196 @noindent
24197 The @code{addr2line} tool has several other useful options:
24198
24199 @table @code
24200 @item --functions
24201 to get the function name corresponding to any location
24202
24203 @item --demangle=gnat
24204 to use the gnat decoding mode for the function names. Note that
24205 for binutils version 2.9.x the option is simply @option{--demangle}.
24206 @end table
24207
24208 @smallexample
24209 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24210    0x40139c 0x401335 0x4011c4 0x4011f1
24211
24212 00401373 in stb.p1 at d:/stb/stb.adb:5
24213 0040138B in stb.p2 at d:/stb/stb.adb:10
24214 0040139C in stb at d:/stb/stb.adb:14
24215 00401335 in main at d:/stb/b~stb.adb:104
24216 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24217 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24218 @end smallexample
24219
24220 @noindent
24221 From this traceback we can see that the exception was raised in
24222 @file{stb.adb} at line 5, which was reached from a procedure call in
24223 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24224 which contains the call to the main program.
24225 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24226 and the output will vary from platform to platform.
24227
24228 It is also possible to use @code{GDB} with these traceback addresses to debug
24229 the program. For example, we can break at a given code location, as reported
24230 in the stack traceback:
24231
24232 @smallexample
24233 $ gdb -nw stb
24234 @ifclear vms
24235 @noindent
24236 Furthermore, this feature is not implemented inside Windows DLL. Only
24237 the non-symbolic traceback is reported in this case.
24238 @end ifclear
24239
24240 (gdb) break *0x401373
24241 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24242 @end smallexample
24243
24244 @noindent
24245 It is important to note that the stack traceback addresses
24246 do not change when debug information is included. This is particularly useful
24247 because it makes it possible to release software without debug information (to
24248 minimize object size), get a field report that includes a stack traceback
24249 whenever an internal bug occurs, and then be able to retrieve the sequence
24250 of calls with the same program compiled with debug information.
24251
24252 @node Tracebacks From Exception Occurrences (non-symbolic)
24253 @subsubsection Tracebacks From Exception Occurrences
24254
24255 @noindent
24256 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24257 The stack traceback is attached to the exception information string, and can
24258 be retrieved in an exception handler within the Ada program, by means of the
24259 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24260
24261 @smallexample @c ada
24262 with Ada.Text_IO;
24263 with Ada.Exceptions;
24264
24265 procedure STB is
24266
24267    use Ada;
24268    use Ada.Exceptions;
24269
24270    procedure P1 is
24271       K : Positive := 1;
24272    begin
24273       K := K - 1;
24274    exception
24275       when E : others =>
24276          Text_IO.Put_Line (Exception_Information (E));
24277    end P1;
24278
24279    procedure P2 is
24280    begin
24281       P1;
24282    end P2;
24283
24284 begin
24285    P2;
24286 end STB;
24287 @end smallexample
24288
24289 @noindent
24290 This program will output:
24291
24292 @smallexample
24293 $ stb
24294
24295 Exception name: CONSTRAINT_ERROR
24296 Message: stb.adb:12
24297 Call stack traceback locations:
24298 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24299 @end smallexample
24300
24301 @node Tracebacks From Anywhere in a Program (non-symbolic)
24302 @subsubsection Tracebacks From Anywhere in a Program
24303
24304 @noindent
24305 It is also possible to retrieve a stack traceback from anywhere in a
24306 program. For this you need to
24307 use the @code{GNAT.Traceback} API. This package includes a procedure called
24308 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24309 display procedures described below. It is not necessary to use the
24310 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24311 is invoked explicitly.
24312
24313 @noindent
24314 In the following example we compute a traceback at a specific location in
24315 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24316 convert addresses to strings:
24317
24318 @smallexample @c ada
24319 with Ada.Text_IO;
24320 with GNAT.Traceback;
24321 with GNAT.Debug_Utilities;
24322
24323 procedure STB is
24324
24325    use Ada;
24326    use GNAT;
24327    use GNAT.Traceback;
24328
24329    procedure P1 is
24330       TB  : Tracebacks_Array (1 .. 10);
24331       --  We are asking for a maximum of 10 stack frames.
24332       Len : Natural;
24333       --  Len will receive the actual number of stack frames returned.
24334    begin
24335       Call_Chain (TB, Len);
24336
24337       Text_IO.Put ("In STB.P1 : ");
24338
24339       for K in 1 .. Len loop
24340          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24341          Text_IO.Put (' ');
24342       end loop;
24343
24344       Text_IO.New_Line;
24345    end P1;
24346
24347    procedure P2 is
24348    begin
24349       P1;
24350    end P2;
24351
24352 begin
24353    P2;
24354 end STB;
24355 @end smallexample
24356
24357 @smallexample
24358 $ gnatmake -g stb
24359 $ stb
24360
24361 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24362 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24363 @end smallexample
24364
24365 @noindent
24366 You can then get further information by invoking the @code{addr2line}
24367 tool as described earlier (note that the hexadecimal addresses
24368 need to be specified in C format, with a leading ``0x'').
24369
24370 @node Symbolic Traceback
24371 @subsection Symbolic Traceback
24372 @cindex traceback, symbolic
24373
24374 @noindent
24375 A symbolic traceback is a stack traceback in which procedure names are
24376 associated with each code location.
24377
24378 @noindent
24379 Note that this feature is not supported on all platforms. See
24380 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24381 list of currently supported platforms.
24382
24383 @noindent
24384 Note that the symbolic traceback requires that the program be compiled
24385 with debug information. If it is not compiled with debug information
24386 only the non-symbolic information will be valid.
24387
24388 @menu
24389 * Tracebacks From Exception Occurrences (symbolic)::
24390 * Tracebacks From Anywhere in a Program (symbolic)::
24391 @end menu
24392
24393 @node Tracebacks From Exception Occurrences (symbolic)
24394 @subsubsection Tracebacks From Exception Occurrences
24395
24396 @smallexample @c ada
24397 with Ada.Text_IO;
24398 with GNAT.Traceback.Symbolic;
24399
24400 procedure STB is
24401
24402    procedure P1 is
24403    begin
24404       raise Constraint_Error;
24405    end P1;
24406
24407    procedure P2 is
24408    begin
24409       P1;
24410    end P2;
24411
24412    procedure P3 is
24413    begin
24414       P2;
24415    end P3;
24416
24417 begin
24418    P3;
24419 exception
24420    when E : others =>
24421       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24422 end STB;
24423 @end smallexample
24424
24425 @smallexample
24426 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24427 $ stb
24428
24429 0040149F in stb.p1 at stb.adb:8
24430 004014B7 in stb.p2 at stb.adb:13
24431 004014CF in stb.p3 at stb.adb:18
24432 004015DD in ada.stb at stb.adb:22
24433 00401461 in main at b~stb.adb:168
24434 004011C4 in __mingw_CRTStartup at crt1.c:200
24435 004011F1 in mainCRTStartup at crt1.c:222
24436 77E892A4 in ?? at ??:0
24437 @end smallexample
24438
24439 @noindent
24440 In the above example the ``.\'' syntax in the @command{gnatmake} command
24441 is currently required by @command{addr2line} for files that are in
24442 the current working directory.
24443 Moreover, the exact sequence of linker options may vary from platform
24444 to platform.
24445 The above @option{-largs} section is for Windows platforms. By contrast,
24446 under Unix there is no need for the @option{-largs} section.
24447 Differences across platforms are due to details of linker implementation.
24448
24449 @node Tracebacks From Anywhere in a Program (symbolic)
24450 @subsubsection Tracebacks From Anywhere in a Program
24451
24452 @noindent
24453 It is possible to get a symbolic stack traceback
24454 from anywhere in a program, just as for non-symbolic tracebacks.
24455 The first step is to obtain a non-symbolic
24456 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24457 information. Here is an example:
24458
24459 @smallexample @c ada
24460 with Ada.Text_IO;
24461 with GNAT.Traceback;
24462 with GNAT.Traceback.Symbolic;
24463
24464 procedure STB is
24465
24466    use Ada;
24467    use GNAT.Traceback;
24468    use GNAT.Traceback.Symbolic;
24469
24470    procedure P1 is
24471       TB  : Tracebacks_Array (1 .. 10);
24472       --  We are asking for a maximum of 10 stack frames.
24473       Len : Natural;
24474       --  Len will receive the actual number of stack frames returned.
24475    begin
24476       Call_Chain (TB, Len);
24477       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24478    end P1;
24479
24480    procedure P2 is
24481    begin
24482       P1;
24483    end P2;
24484
24485 begin
24486    P2;
24487 end STB;
24488 @end smallexample
24489
24490 @c ******************************
24491 @ifset vms
24492 @node Compatibility with HP Ada
24493 @chapter Compatibility with HP Ada
24494 @cindex Compatibility
24495
24496 @noindent
24497 @cindex DEC Ada
24498 @cindex HP Ada
24499 @cindex Compatibility between GNAT and HP Ada
24500 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24501 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24502 GNAT is highly compatible
24503 with HP Ada, and it should generally be straightforward to port code
24504 from the HP Ada environment to GNAT. However, there are a few language
24505 and implementation differences of which the user must be aware. These
24506 differences are discussed in this chapter. In
24507 addition, the operating environment and command structure for the
24508 compiler are different, and these differences are also discussed.
24509
24510 For further details on these and other compatibility issues,
24511 see Appendix E of the HP publication
24512 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24513
24514 Except where otherwise indicated, the description of GNAT for OpenVMS
24515 applies to both the Alpha and I64 platforms.
24516
24517 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24518 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24519
24520 The discussion in this chapter addresses specifically the implementation
24521 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24522 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24523 GNAT always follows the Alpha implementation.
24524
24525 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24526 attributes are recognized, although only a subset of them can sensibly
24527 be implemented.  The description of pragmas in
24528 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24529 indicates whether or not they are applicable to non-VMS systems.
24530
24531 @menu
24532 * Ada Language Compatibility::
24533 * Differences in the Definition of Package System::
24534 * Language-Related Features::
24535 * The Package STANDARD::
24536 * The Package SYSTEM::
24537 * Tasking and Task-Related Features::
24538 * Pragmas and Pragma-Related Features::
24539 * Library of Predefined Units::
24540 * Bindings::
24541 * Main Program Definition::
24542 * Implementation-Defined Attributes::
24543 * Compiler and Run-Time Interfacing::
24544 * Program Compilation and Library Management::
24545 * Input-Output::
24546 * Implementation Limits::
24547 * Tools and Utilities::
24548 @end menu
24549
24550 @node Ada Language Compatibility
24551 @section Ada Language Compatibility
24552
24553 @noindent
24554 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24555 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24556 with Ada 83, and therefore Ada 83 programs will compile
24557 and run under GNAT with
24558 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24559 provides details on specific incompatibilities.
24560
24561 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24562 as well as the pragma @code{ADA_83}, to force the compiler to
24563 operate in Ada 83 mode. This mode does not guarantee complete
24564 conformance to Ada 83, but in practice is sufficient to
24565 eliminate most sources of incompatibilities.
24566 In particular, it eliminates the recognition of the
24567 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24568 in Ada 83 programs is legal, and handles the cases of packages
24569 with optional bodies, and generics that instantiate unconstrained
24570 types without the use of @code{(<>)}.
24571
24572 @node Differences in the Definition of Package System
24573 @section Differences in the Definition of Package @code{System}
24574
24575 @noindent
24576 An Ada compiler is allowed to add
24577 implementation-dependent declarations to package @code{System}.
24578 In normal mode,
24579 GNAT does not take advantage of this permission, and the version of
24580 @code{System} provided by GNAT exactly matches that defined in the Ada
24581 Reference Manual.
24582
24583 However, HP Ada adds an extensive set of declarations to package
24584 @code{System},
24585 as fully documented in the HP Ada manuals. To minimize changes required
24586 for programs that make use of these extensions, GNAT provides the pragma
24587 @code{Extend_System} for extending the definition of package System. By using:
24588 @cindex pragma @code{Extend_System}
24589 @cindex @code{Extend_System} pragma
24590
24591 @smallexample @c ada
24592 @group
24593 @cartouche
24594 pragma Extend_System (Aux_DEC);
24595 @end cartouche
24596 @end group
24597 @end smallexample
24598
24599 @noindent
24600 the set of definitions in @code{System} is extended to include those in
24601 package @code{System.Aux_DEC}.
24602 @cindex @code{System.Aux_DEC} package
24603 @cindex @code{Aux_DEC} package (child of @code{System})
24604 These definitions are incorporated directly into package @code{System},
24605 as though they had been declared there. For a
24606 list of the declarations added, see the spec of this package,
24607 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24608 @cindex @file{s-auxdec.ads} file
24609 The pragma @code{Extend_System} is a configuration pragma, which means that
24610 it can be placed in the file @file{gnat.adc}, so that it will automatically
24611 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24612 for further details.
24613
24614 An alternative approach that avoids the use of the non-standard
24615 @code{Extend_System} pragma is to add a context clause to the unit that
24616 references these facilities:
24617
24618 @smallexample @c ada
24619 @cartouche
24620 with System.Aux_DEC;
24621 use  System.Aux_DEC;
24622 @end cartouche
24623 @end smallexample
24624
24625 @noindent
24626 The effect is not quite semantically identical to incorporating
24627 the declarations directly into package @code{System},
24628 but most programs will not notice a difference
24629 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24630 to reference the entities directly in package @code{System}.
24631 For units containing such references,
24632 the prefixes must either be removed, or the pragma @code{Extend_System}
24633 must be used.
24634
24635 @node Language-Related Features
24636 @section Language-Related Features
24637
24638 @noindent
24639 The following sections highlight differences in types,
24640 representations of types, operations, alignment, and
24641 related topics.
24642
24643 @menu
24644 * Integer Types and Representations::
24645 * Floating-Point Types and Representations::
24646 * Pragmas Float_Representation and Long_Float::
24647 * Fixed-Point Types and Representations::
24648 * Record and Array Component Alignment::
24649 * Address Clauses::
24650 * Other Representation Clauses::
24651 @end menu
24652
24653 @node Integer Types and Representations
24654 @subsection Integer Types and Representations
24655
24656 @noindent
24657 The set of predefined integer types is identical in HP Ada and GNAT.
24658 Furthermore the representation of these integer types is also identical,
24659 including the capability of size clauses forcing biased representation.
24660
24661 In addition,
24662 HP Ada for OpenVMS Alpha systems has defined the
24663 following additional integer types in package @code{System}:
24664
24665 @itemize @bullet
24666
24667 @item
24668 @code{INTEGER_8}
24669
24670 @item
24671 @code{INTEGER_16}
24672
24673 @item
24674 @code{INTEGER_32}
24675
24676 @item
24677 @code{INTEGER_64}
24678
24679 @item
24680 @code{LARGEST_INTEGER}
24681 @end itemize
24682
24683 @noindent
24684 In GNAT, the first four of these types may be obtained from the
24685 standard Ada package @code{Interfaces}.
24686 Alternatively, by use of the pragma @code{Extend_System}, identical
24687 declarations can be referenced directly in package @code{System}.
24688 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24689
24690 @node Floating-Point Types and Representations
24691 @subsection Floating-Point Types and Representations
24692 @cindex Floating-Point types
24693
24694 @noindent
24695 The set of predefined floating-point types is identical in HP Ada and GNAT.
24696 Furthermore the representation of these floating-point
24697 types is also identical. One important difference is that the default
24698 representation for HP Ada is @code{VAX_Float}, but the default representation
24699 for GNAT is IEEE.
24700
24701 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24702 pragma @code{Float_Representation} as described in the HP Ada
24703 documentation.
24704 For example, the declarations:
24705
24706 @smallexample @c ada
24707 @cartouche
24708 type F_Float is digits 6;
24709 pragma Float_Representation (VAX_Float, F_Float);
24710 @end cartouche
24711 @end smallexample
24712
24713 @noindent
24714 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24715 format.
24716 This set of declarations actually appears in @code{System.Aux_DEC},
24717 which contains
24718 the full set of additional floating-point declarations provided in
24719 the HP Ada version of package @code{System}.
24720 This and similar declarations may be accessed in a user program
24721 by using pragma @code{Extend_System}. The use of this
24722 pragma, and the related pragma @code{Long_Float} is described in further
24723 detail in the following section.
24724
24725 @node Pragmas Float_Representation and Long_Float
24726 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24727
24728 @noindent
24729 HP Ada provides the pragma @code{Float_Representation}, which
24730 acts as a program library switch to allow control over
24731 the internal representation chosen for the predefined
24732 floating-point types declared in the package @code{Standard}.
24733 The format of this pragma is as follows:
24734
24735 @smallexample @c ada
24736 @cartouche
24737 pragma Float_Representation(VAX_Float | IEEE_Float);
24738 @end cartouche
24739 @end smallexample
24740
24741 @noindent
24742 This pragma controls the representation of floating-point
24743 types as follows:
24744
24745 @itemize @bullet
24746 @item
24747 @code{VAX_Float} specifies that floating-point
24748 types are represented by default with the VAX system hardware types
24749 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24750 Note that the @code{H-floating}
24751 type was available only on VAX systems, and is not available
24752 in either HP Ada or GNAT.
24753
24754 @item
24755 @code{IEEE_Float} specifies that floating-point
24756 types are represented by default with the IEEE single and
24757 double floating-point types.
24758 @end itemize
24759
24760 @noindent
24761 GNAT provides an identical implementation of the pragma
24762 @code{Float_Representation}, except that it functions as a
24763 configuration pragma. Note that the
24764 notion of configuration pragma corresponds closely to the
24765 HP Ada notion of a program library switch.
24766
24767 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24768 which is different
24769 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24770 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24771 advisable to change the format of numbers passed to standard library
24772 routines, and if necessary explicit type conversions may be needed.
24773
24774 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24775 efficient, and (given that it conforms to an international standard)
24776 potentially more portable.
24777 The situation in which @code{VAX_Float} may be useful is in interfacing
24778 to existing code and data that expect the use of @code{VAX_Float}.
24779 In such a situation use the predefined @code{VAX_Float}
24780 types in package @code{System}, as extended by
24781 @code{Extend_System}. For example, use @code{System.F_Float}
24782 to specify the 32-bit @code{F-Float} format.
24783
24784 @noindent
24785 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24786 to allow control over the internal representation chosen
24787 for the predefined type @code{Long_Float} and for floating-point
24788 type declarations with digits specified in the range 7 .. 15.
24789 The format of this pragma is as follows:
24790
24791 @smallexample @c ada
24792 @cartouche
24793 pragma Long_Float (D_FLOAT | G_FLOAT);
24794 @end cartouche
24795 @end smallexample
24796
24797 @node Fixed-Point Types and Representations
24798 @subsection Fixed-Point Types and Representations
24799
24800 @noindent
24801 On HP Ada for OpenVMS Alpha systems, rounding is
24802 away from zero for both positive and negative numbers.
24803 Therefore, @code{+0.5} rounds to @code{1},
24804 and @code{-0.5} rounds to @code{-1}.
24805
24806 On GNAT the results of operations
24807 on fixed-point types are in accordance with the Ada
24808 rules. In particular, results of operations on decimal
24809 fixed-point types are truncated.
24810
24811 @node Record and Array Component Alignment
24812 @subsection Record and Array Component Alignment
24813
24814 @noindent
24815 On HP Ada for OpenVMS Alpha, all non-composite components
24816 are aligned on natural boundaries. For example, 1-byte
24817 components are aligned on byte boundaries, 2-byte
24818 components on 2-byte boundaries, 4-byte components on 4-byte
24819 byte boundaries, and so on. The OpenVMS Alpha hardware
24820 runs more efficiently with naturally aligned data.
24821
24822 On GNAT, alignment rules are compatible
24823 with HP Ada for OpenVMS Alpha.
24824
24825 @node Address Clauses
24826 @subsection Address Clauses
24827
24828 @noindent
24829 In HP Ada and GNAT, address clauses are supported for
24830 objects and imported subprograms.
24831 The predefined type @code{System.Address} is a private type
24832 in both compilers on Alpha OpenVMS, with the same representation
24833 (it is simply a machine pointer). Addition, subtraction, and comparison
24834 operations are available in the standard Ada package
24835 @code{System.Storage_Elements}, or in package @code{System}
24836 if it is extended to include @code{System.Aux_DEC} using a
24837 pragma @code{Extend_System} as previously described.
24838
24839 Note that code that @code{with}'s both this extended package @code{System}
24840 and the package @code{System.Storage_Elements} should not @code{use}
24841 both packages, or ambiguities will result. In general it is better
24842 not to mix these two sets of facilities. The Ada package was
24843 designed specifically to provide the kind of features that HP Ada
24844 adds directly to package @code{System}.
24845
24846 The type @code{System.Address} is a 64-bit integer type in GNAT for
24847 I64 OpenVMS.  For more information,
24848 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24849
24850 GNAT is compatible with HP Ada in its handling of address
24851 clauses, except for some limitations in
24852 the form of address clauses for composite objects with
24853 initialization. Such address clauses are easily replaced
24854 by the use of an explicitly-defined constant as described
24855 in the Ada Reference Manual (13.1(22)). For example, the sequence
24856 of declarations:
24857
24858 @smallexample @c ada
24859 @cartouche
24860 X, Y : Integer := Init_Func;
24861 Q : String (X .. Y) := "abc";
24862 @dots{}
24863 for Q'Address use Compute_Address;
24864 @end cartouche
24865 @end smallexample
24866
24867 @noindent
24868 will be rejected by GNAT, since the address cannot be computed at the time
24869 that @code{Q} is declared. To achieve the intended effect, write instead:
24870
24871 @smallexample @c ada
24872 @group
24873 @cartouche
24874 X, Y : Integer := Init_Func;
24875 Q_Address : constant Address := Compute_Address;
24876 Q : String (X .. Y) := "abc";
24877 @dots{}
24878 for Q'Address use Q_Address;
24879 @end cartouche
24880 @end group
24881 @end smallexample
24882
24883 @noindent
24884 which will be accepted by GNAT (and other Ada compilers), and is also
24885 compatible with Ada 83. A fuller description of the restrictions
24886 on address specifications is found in @ref{Top, GNAT Reference Manual,
24887 About This Guide, gnat_rm, GNAT Reference Manual}.
24888
24889 @node Other Representation Clauses
24890 @subsection Other Representation Clauses
24891
24892 @noindent
24893 GNAT implements in a compatible manner all the representation
24894 clauses supported by HP Ada. In addition, GNAT
24895 implements the representation clause forms that were introduced in Ada 95,
24896 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24897
24898 @node The Package STANDARD
24899 @section The Package @code{STANDARD}
24900
24901 @noindent
24902 The package @code{STANDARD}, as implemented by HP Ada, is fully
24903 described in the @cite{Ada Reference Manual} and in the
24904 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24905 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24906
24907 In addition, HP Ada supports the Latin-1 character set in
24908 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24909 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24910 the type @code{WIDE_CHARACTER}.
24911
24912 The floating-point types supported by GNAT are those
24913 supported by HP Ada, but the defaults are different, and are controlled by
24914 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24915
24916 @node The Package SYSTEM
24917 @section The Package @code{SYSTEM}
24918
24919 @noindent
24920 HP Ada provides a specific version of the package
24921 @code{SYSTEM} for each platform on which the language is implemented.
24922 For the complete spec of the package @code{SYSTEM}, see
24923 Appendix F of the @cite{HP Ada Language Reference Manual}.
24924
24925 On HP Ada, the package @code{SYSTEM} includes the following conversion
24926 functions:
24927 @itemize @bullet
24928 @item @code{TO_ADDRESS(INTEGER)}
24929
24930 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24931
24932 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24933
24934 @item @code{TO_INTEGER(ADDRESS)}
24935
24936 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24937
24938 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24939 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24940 @end itemize
24941
24942 @noindent
24943 By default, GNAT supplies a version of @code{SYSTEM} that matches
24944 the definition given in the @cite{Ada Reference Manual}.
24945 This
24946 is a subset of the HP system definitions, which is as
24947 close as possible to the original definitions. The only difference
24948 is that the definition of @code{SYSTEM_NAME} is different:
24949
24950 @smallexample @c ada
24951 @cartouche
24952 type Name is (SYSTEM_NAME_GNAT);
24953 System_Name : constant Name := SYSTEM_NAME_GNAT;
24954 @end cartouche
24955 @end smallexample
24956
24957 @noindent
24958 Also, GNAT adds the Ada declarations for
24959 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24960
24961 However, the use of the following pragma causes GNAT
24962 to extend the definition of package @code{SYSTEM} so that it
24963 encompasses the full set of HP-specific extensions,
24964 including the functions listed above:
24965
24966 @smallexample @c ada
24967 @cartouche
24968 pragma Extend_System (Aux_DEC);
24969 @end cartouche
24970 @end smallexample
24971
24972 @noindent
24973 The pragma @code{Extend_System} is a configuration pragma that
24974 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24975 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24976
24977 HP Ada does not allow the recompilation of the package
24978 @code{SYSTEM}. Instead HP Ada provides several pragmas
24979 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24980 to modify values in the package @code{SYSTEM}.
24981 On OpenVMS Alpha systems, the pragma
24982 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24983 its single argument.
24984
24985 GNAT does permit the recompilation of package @code{SYSTEM} using
24986 the special switch @option{-gnatg}, and this switch can be used if
24987 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24988 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24989 or @code{MEMORY_SIZE} by any other means.
24990
24991 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24992 enumeration literal @code{SYSTEM_NAME_GNAT}.
24993
24994 The definitions provided by the use of
24995
24996 @smallexample @c ada
24997 pragma Extend_System (AUX_Dec);
24998 @end smallexample
24999
25000 @noindent
25001 are virtually identical to those provided by the HP Ada 83 package
25002 @code{SYSTEM}. One important difference is that the name of the
25003 @code{TO_ADDRESS}
25004 function for type @code{UNSIGNED_LONGWORD} is changed to
25005 @code{TO_ADDRESS_LONG}.
25006 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
25007 discussion of why this change was necessary.
25008
25009 @noindent
25010 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25011 is in fact
25012 an extension to Ada 83 not strictly compatible with the reference manual.
25013 GNAT, in order to be exactly compatible with the standard,
25014 does not provide this capability. In HP Ada 83, the
25015 point of this definition is to deal with a call like:
25016
25017 @smallexample @c ada
25018 TO_ADDRESS (16#12777#);
25019 @end smallexample
25020
25021 @noindent
25022 Normally, according to Ada 83 semantics, one would expect this to be
25023 ambiguous, since it matches both the @code{INTEGER} and
25024 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25025 However, in HP Ada 83, there is no ambiguity, since the
25026 definition using @i{universal_integer} takes precedence.
25027
25028 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25029 it is
25030 not possible to be 100% compatible. Since there are many programs using
25031 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25032 GNAT was
25033 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25034 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25035
25036 @smallexample @c ada
25037 function To_Address (X : Integer) return Address;
25038 pragma Pure_Function (To_Address);
25039
25040 function To_Address_Long (X : Unsigned_Longword) return Address;
25041 pragma Pure_Function (To_Address_Long);
25042 @end smallexample
25043
25044 @noindent
25045 This means that programs using @code{TO_ADDRESS} for
25046 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25047
25048 @node Tasking and Task-Related Features
25049 @section Tasking and Task-Related Features
25050
25051 @noindent
25052 This section compares the treatment of tasking in GNAT
25053 and in HP Ada for OpenVMS Alpha.
25054 The GNAT description applies to both Alpha and I64 OpenVMS.
25055 For detailed information on tasking in
25056 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25057 relevant run-time reference manual.
25058
25059 @menu
25060 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25061 * Assigning Task IDs::
25062 * Task IDs and Delays::
25063 * Task-Related Pragmas::
25064 * Scheduling and Task Priority::
25065 * The Task Stack::
25066 * External Interrupts::
25067 @end menu
25068
25069 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25070 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25071
25072 @noindent
25073 On OpenVMS Alpha systems, each Ada task (except a passive
25074 task) is implemented as a single stream of execution
25075 that is created and managed by the kernel. On these
25076 systems, HP Ada tasking support is based on DECthreads,
25077 an implementation of the POSIX standard for threads.
25078
25079 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25080 code that calls DECthreads routines can be used together.
25081 The interaction between Ada tasks and DECthreads routines
25082 can have some benefits. For example when on OpenVMS Alpha,
25083 HP Ada can call C code that is already threaded.
25084
25085 GNAT uses the facilities of DECthreads,
25086 and Ada tasks are mapped to threads.
25087
25088 @node Assigning Task IDs
25089 @subsection Assigning Task IDs
25090
25091 @noindent
25092 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25093 the environment task that executes the main program. On
25094 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25095 that have been created but are not yet activated.
25096
25097 On OpenVMS Alpha systems, task IDs are assigned at
25098 activation. On GNAT systems, task IDs are also assigned at
25099 task creation but do not have the same form or values as
25100 task ID values in HP Ada. There is no null task, and the
25101 environment task does not have a specific task ID value.
25102
25103 @node Task IDs and Delays
25104 @subsection Task IDs and Delays
25105
25106 @noindent
25107 On OpenVMS Alpha systems, tasking delays are implemented
25108 using Timer System Services. The Task ID is used for the
25109 identification of the timer request (the @code{REQIDT} parameter).
25110 If Timers are used in the application take care not to use
25111 @code{0} for the identification, because cancelling such a timer
25112 will cancel all timers and may lead to unpredictable results.
25113
25114 @node Task-Related Pragmas
25115 @subsection Task-Related Pragmas
25116
25117 @noindent
25118 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25119 specification of the size of the guard area for a task
25120 stack. (The guard area forms an area of memory that has no
25121 read or write access and thus helps in the detection of
25122 stack overflow.) On OpenVMS Alpha systems, if the pragma
25123 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25124 area is created. In the absence of a pragma @code{TASK_STORAGE},
25125 a default guard area is created.
25126
25127 GNAT supplies the following task-related pragmas:
25128
25129 @itemize @bullet
25130 @item  @code{TASK_INFO}
25131
25132 This pragma appears within a task definition and
25133 applies to the task in which it appears. The argument
25134 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25135
25136 @item  @code{TASK_STORAGE}
25137
25138 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25139 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25140 @code{SUPPRESS}, and @code{VOLATILE}.
25141 @end itemize
25142 @node Scheduling and Task Priority
25143 @subsection Scheduling and Task Priority
25144
25145 @noindent
25146 HP Ada implements the Ada language requirement that
25147 when two tasks are eligible for execution and they have
25148 different priorities, the lower priority task does not
25149 execute while the higher priority task is waiting. The HP
25150 Ada Run-Time Library keeps a task running until either the
25151 task is suspended or a higher priority task becomes ready.
25152
25153 On OpenVMS Alpha systems, the default strategy is round-
25154 robin with preemption. Tasks of equal priority take turns
25155 at the processor. A task is run for a certain period of
25156 time and then placed at the tail of the ready queue for
25157 its priority level.
25158
25159 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25160 which can be used to enable or disable round-robin
25161 scheduling of tasks with the same priority.
25162 See the relevant HP Ada run-time reference manual for
25163 information on using the pragmas to control HP Ada task
25164 scheduling.
25165
25166 GNAT follows the scheduling rules of Annex D (Real-Time
25167 Annex) of the @cite{Ada Reference Manual}. In general, this
25168 scheduling strategy is fully compatible with HP Ada
25169 although it provides some additional constraints (as
25170 fully documented in Annex D).
25171 GNAT implements time slicing control in a manner compatible with
25172 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25173 are identical to the HP Ada 83 pragma of the same name.
25174 Note that it is not possible to mix GNAT tasking and
25175 HP Ada 83 tasking in the same program, since the two run-time
25176 libraries are not compatible.
25177
25178 @node The Task Stack
25179 @subsection The Task Stack
25180
25181 @noindent
25182 In HP Ada, a task stack is allocated each time a
25183 non-passive task is activated. As soon as the task is
25184 terminated, the storage for the task stack is deallocated.
25185 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25186 a default stack size is used. Also, regardless of the size
25187 specified, some additional space is allocated for task
25188 management purposes. On OpenVMS Alpha systems, at least
25189 one page is allocated.
25190
25191 GNAT handles task stacks in a similar manner. In accordance with
25192 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25193 an alternative method for controlling the task stack size.
25194 The specification of the attribute @code{T'STORAGE_SIZE} is also
25195 supported in a manner compatible with HP Ada.
25196
25197 @node External Interrupts
25198 @subsection External Interrupts
25199
25200 @noindent
25201 On HP Ada, external interrupts can be associated with task entries.
25202 GNAT is compatible with HP Ada in its handling of external interrupts.
25203
25204 @node Pragmas and Pragma-Related Features
25205 @section Pragmas and Pragma-Related Features
25206
25207 @noindent
25208 Both HP Ada and GNAT supply all language-defined pragmas
25209 as specified by the Ada 83 standard. GNAT also supplies all
25210 language-defined pragmas introduced by Ada 95 and Ada 2005.
25211 In addition, GNAT implements the implementation-defined pragmas
25212 from HP Ada 83.
25213
25214 @itemize @bullet
25215 @item  @code{AST_ENTRY}
25216
25217 @item  @code{COMMON_OBJECT}
25218
25219 @item  @code{COMPONENT_ALIGNMENT}
25220
25221 @item  @code{EXPORT_EXCEPTION}
25222
25223 @item  @code{EXPORT_FUNCTION}
25224
25225 @item  @code{EXPORT_OBJECT}
25226
25227 @item  @code{EXPORT_PROCEDURE}
25228
25229 @item  @code{EXPORT_VALUED_PROCEDURE}
25230
25231 @item  @code{FLOAT_REPRESENTATION}
25232
25233 @item  @code{IDENT}
25234
25235 @item  @code{IMPORT_EXCEPTION}
25236
25237 @item  @code{IMPORT_FUNCTION}
25238
25239 @item  @code{IMPORT_OBJECT}
25240
25241 @item  @code{IMPORT_PROCEDURE}
25242
25243 @item  @code{IMPORT_VALUED_PROCEDURE}
25244
25245 @item  @code{INLINE_GENERIC}
25246
25247 @item  @code{INTERFACE_NAME}
25248
25249 @item  @code{LONG_FLOAT}
25250
25251 @item  @code{MAIN_STORAGE}
25252
25253 @item  @code{PASSIVE}
25254
25255 @item  @code{PSECT_OBJECT}
25256
25257 @item  @code{SHARE_GENERIC}
25258
25259 @item  @code{SUPPRESS_ALL}
25260
25261 @item  @code{TASK_STORAGE}
25262
25263 @item  @code{TIME_SLICE}
25264
25265 @item  @code{TITLE}
25266 @end itemize
25267
25268 @noindent
25269 These pragmas are all fully implemented, with the exception of @code{TITLE},
25270 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25271 recognized, but which have no
25272 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25273 use of Ada protected objects. In GNAT, all generics are inlined.
25274
25275 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25276 a separate subprogram specification which must appear before the
25277 subprogram body.
25278
25279 GNAT also supplies a number of implementation-defined pragmas as follows:
25280 @itemize @bullet
25281 @item  @code{ABORT_DEFER}
25282
25283 @item  @code{ADA_83}
25284
25285 @item  @code{ADA_95}
25286
25287 @item  @code{ADA_05}
25288
25289 @item  @code{ANNOTATE}
25290
25291 @item  @code{ASSERT}
25292
25293 @item  @code{C_PASS_BY_COPY}
25294
25295 @item  @code{CPP_CLASS}
25296
25297 @item  @code{CPP_CONSTRUCTOR}
25298
25299 @item  @code{CPP_DESTRUCTOR}
25300
25301 @item  @code{DEBUG}
25302
25303 @item  @code{EXTEND_SYSTEM}
25304
25305 @item  @code{LINKER_ALIAS}
25306
25307 @item  @code{LINKER_SECTION}
25308
25309 @item  @code{MACHINE_ATTRIBUTE}
25310
25311 @item  @code{NO_RETURN}
25312
25313 @item  @code{PURE_FUNCTION}
25314
25315 @item  @code{SOURCE_FILE_NAME}
25316
25317 @item  @code{SOURCE_REFERENCE}
25318
25319 @item  @code{TASK_INFO}
25320
25321 @item  @code{UNCHECKED_UNION}
25322
25323 @item  @code{UNIMPLEMENTED_UNIT}
25324
25325 @item  @code{UNIVERSAL_DATA}
25326
25327 @item  @code{UNSUPPRESS}
25328
25329 @item  @code{WARNINGS}
25330
25331 @item  @code{WEAK_EXTERNAL}
25332 @end itemize
25333
25334 @noindent
25335 For full details on these GNAT implementation-defined pragmas,
25336 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25337 Manual}.
25338
25339 @menu
25340 * Restrictions on the Pragma INLINE::
25341 * Restrictions on the Pragma INTERFACE::
25342 * Restrictions on the Pragma SYSTEM_NAME::
25343 @end menu
25344
25345 @node Restrictions on the Pragma INLINE
25346 @subsection Restrictions on Pragma @code{INLINE}
25347
25348 @noindent
25349 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25350 @itemize @bullet
25351 @item  Parameters cannot have a task type.
25352
25353 @item  Function results cannot be task types, unconstrained
25354 array types, or unconstrained types with discriminants.
25355
25356 @item  Bodies cannot declare the following:
25357 @itemize @bullet
25358 @item  Subprogram body or stub (imported subprogram is allowed)
25359
25360 @item  Tasks
25361
25362 @item  Generic declarations
25363
25364 @item  Instantiations
25365
25366 @item  Exceptions
25367
25368 @item  Access types (types derived from access types allowed)
25369
25370 @item  Array or record types
25371
25372 @item  Dependent tasks
25373
25374 @item  Direct recursive calls of subprogram or containing
25375 subprogram, directly or via a renaming
25376
25377 @end itemize
25378 @end itemize
25379
25380 @noindent
25381 In GNAT, the only restriction on pragma @code{INLINE} is that the
25382 body must occur before the call if both are in the same
25383 unit, and the size must be appropriately small. There are
25384 no other specific restrictions which cause subprograms to
25385 be incapable of being inlined.
25386
25387 @node  Restrictions on the Pragma INTERFACE
25388 @subsection  Restrictions on Pragma @code{INTERFACE}
25389
25390 @noindent
25391 The following restrictions on pragma @code{INTERFACE}
25392 are enforced by both HP Ada and GNAT:
25393 @itemize @bullet
25394 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25395 Default is the default on OpenVMS Alpha systems.
25396
25397 @item  Parameter passing: Language specifies default
25398 mechanisms but can be overridden with an @code{EXPORT} pragma.
25399
25400 @itemize @bullet
25401 @item  Ada: Use internal Ada rules.
25402
25403 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25404 record or task type. Result cannot be a string, an
25405 array, or a record.
25406
25407 @item  Fortran: Parameters cannot have a task type. Result cannot
25408 be a string, an array, or a record.
25409 @end itemize
25410 @end itemize
25411
25412 @noindent
25413 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25414 record parameters for all languages.
25415
25416 @node  Restrictions on the Pragma SYSTEM_NAME
25417 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25418
25419 @noindent
25420 For HP Ada for OpenVMS Alpha, the enumeration literal
25421 for the type @code{NAME} is @code{OPENVMS_AXP}.
25422 In GNAT, the enumeration
25423 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25424
25425 @node  Library of Predefined Units
25426 @section  Library of Predefined Units
25427
25428 @noindent
25429 A library of predefined units is provided as part of the
25430 HP Ada and GNAT implementations. HP Ada does not provide
25431 the package @code{MACHINE_CODE} but instead recommends importing
25432 assembler code.
25433
25434 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25435 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25436 version.
25437 The HP Ada Predefined Library units are modified to remove post-Ada 83
25438 incompatibilities and to make them interoperable with GNAT
25439 (@pxref{Changes to DECLIB}, for details).
25440 The units are located in the @file{DECLIB} directory.
25441
25442 The GNAT RTL is contained in
25443 the @file{ADALIB} directory, and
25444 the default search path is set up to find @code{DECLIB} units in preference
25445 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25446 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25447
25448 @menu
25449 * Changes to DECLIB::
25450 @end menu
25451
25452 @node Changes to DECLIB
25453 @subsection Changes to @code{DECLIB}
25454
25455 @noindent
25456 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25457 compatibility are minor and include the following:
25458
25459 @itemize @bullet
25460 @item  Adjusting the location of pragmas and record representation
25461 clauses to obey Ada 95 (and thus Ada 2005) rules
25462
25463 @item  Adding the proper notation to generic formal parameters
25464 that take unconstrained types in instantiation
25465
25466 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25467 that have package bodies not otherwise allowed
25468
25469 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25470 ``@code{PROTECTD}''.
25471 Currently these are found only in the @code{STARLET} package spec.
25472
25473 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25474 where the address size is constrained to 32 bits.
25475 @end itemize
25476
25477 @noindent
25478 None of the above changes is visible to users.
25479
25480 @node Bindings
25481 @section Bindings
25482
25483 @noindent
25484 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25485 @itemize @bullet
25486
25487 @item  Command Language Interpreter (CLI interface)
25488
25489 @item  DECtalk Run-Time Library (DTK interface)
25490
25491 @item  Librarian utility routines (LBR interface)
25492
25493 @item  General Purpose Run-Time Library (LIB interface)
25494
25495 @item  Math Run-Time Library (MTH interface)
25496
25497 @item  National Character Set Run-Time Library (NCS interface)
25498
25499 @item  Compiled Code Support Run-Time Library (OTS interface)
25500
25501 @item  Parallel Processing Run-Time Library (PPL interface)
25502
25503 @item  Screen Management Run-Time Library (SMG interface)
25504
25505 @item  Sort Run-Time Library (SOR interface)
25506
25507 @item  String Run-Time Library (STR interface)
25508
25509 @item STARLET System Library
25510 @findex Starlet
25511
25512 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25513
25514 @item  X Windows Toolkit (XT interface)
25515
25516 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25517 @end itemize
25518
25519 @noindent
25520 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25521 directory, on both the Alpha and I64 OpenVMS platforms.
25522
25523 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25524 in the
25525 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25526 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25527 @code{Xt}, and @code{X_Lib}
25528 causing the default X/Motif sharable image libraries to be linked in. This
25529 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25530 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25531
25532 It may be necessary to edit these options files to update or correct the
25533 library names if, for example, the newer X/Motif bindings from
25534 @file{ADA$EXAMPLES}
25535 had been (previous to installing GNAT) copied and renamed to supersede the
25536 default @file{ADA$PREDEFINED} versions.
25537
25538 @menu
25539 * Shared Libraries and Options Files::
25540 * Interfaces to C::
25541 @end menu
25542
25543 @node Shared Libraries and Options Files
25544 @subsection Shared Libraries and Options Files
25545
25546 @noindent
25547 When using the HP Ada
25548 predefined X and Motif bindings, the linking with their sharable images is
25549 done automatically by @command{GNAT LINK}.
25550 When using other X and Motif bindings, you need
25551 to add the corresponding sharable images to the command line for
25552 @code{GNAT LINK}. When linking with shared libraries, or with
25553 @file{.OPT} files, you must
25554 also add them to the command line for @command{GNAT LINK}.
25555
25556 A shared library to be used with GNAT is built in the same way as other
25557 libraries under VMS. The VMS Link command can be used in standard fashion.
25558
25559 @node Interfaces to C
25560 @subsection Interfaces to C
25561
25562 @noindent
25563 HP Ada
25564 provides the following Ada types and operations:
25565
25566 @itemize @bullet
25567 @item C types package (@code{C_TYPES})
25568
25569 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25570
25571 @item Other_types (@code{SHORT_INT})
25572 @end itemize
25573
25574 @noindent
25575 Interfacing to C with GNAT, you can use the above approach
25576 described for HP Ada or the facilities of Annex B of
25577 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25578 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25579 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25580
25581 The @option{-gnatF} qualifier forces default and explicit
25582 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25583 to be uppercased for compatibility with the default behavior
25584 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25585
25586 @node Main Program Definition
25587 @section Main Program Definition
25588
25589 @noindent
25590 The following section discusses differences in the
25591 definition of main programs on HP Ada and GNAT.
25592 On HP Ada, main programs are defined to meet the
25593 following conditions:
25594 @itemize @bullet
25595 @item  Procedure with no formal parameters (returns @code{0} upon
25596 normal completion)
25597
25598 @item  Procedure with no formal parameters (returns @code{42} when
25599 an unhandled exception is raised)
25600
25601 @item  Function with no formal parameters whose returned value
25602 is of a discrete type
25603
25604 @item  Procedure with one @code{out} formal of a discrete type for
25605 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25606
25607 @end itemize
25608
25609 @noindent
25610 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25611 a main function or main procedure returns a discrete
25612 value whose size is less than 64 bits (32 on VAX systems),
25613 the value is zero- or sign-extended as appropriate.
25614 On GNAT, main programs are defined as follows:
25615 @itemize @bullet
25616 @item  Must be a non-generic, parameterless subprogram that
25617 is either a procedure or function returning an Ada
25618 @code{STANDARD.INTEGER} (the predefined type)
25619
25620 @item  Cannot be a generic subprogram or an instantiation of a
25621 generic subprogram
25622 @end itemize
25623
25624 @node Implementation-Defined Attributes
25625 @section Implementation-Defined Attributes
25626
25627 @noindent
25628 GNAT provides all HP Ada implementation-defined
25629 attributes.
25630
25631 @node Compiler and Run-Time Interfacing
25632 @section Compiler and Run-Time Interfacing
25633
25634 @noindent
25635 HP Ada provides the following qualifiers to pass options to the linker
25636 (ACS LINK):
25637 @itemize @bullet
25638 @item  @option{/WAIT} and @option{/SUBMIT}
25639
25640 @item  @option{/COMMAND}
25641
25642 @item  @option{/@r{[}NO@r{]}MAP}
25643
25644 @item  @option{/OUTPUT=@var{file-spec}}
25645
25646 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25647 @end itemize
25648
25649 @noindent
25650 To pass options to the linker, GNAT provides the following
25651 switches:
25652
25653 @itemize @bullet
25654 @item   @option{/EXECUTABLE=@var{exec-name}}
25655
25656 @item   @option{/VERBOSE}
25657
25658 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25659 @end itemize
25660
25661 @noindent
25662 For more information on these switches, see
25663 @ref{Switches for gnatlink}.
25664 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25665 to control optimization. HP Ada also supplies the
25666 following pragmas:
25667 @itemize @bullet
25668 @item  @code{OPTIMIZE}
25669
25670 @item  @code{INLINE}
25671
25672 @item  @code{INLINE_GENERIC}
25673
25674 @item  @code{SUPPRESS_ALL}
25675
25676 @item  @code{PASSIVE}
25677 @end itemize
25678
25679 @noindent
25680 In GNAT, optimization is controlled strictly by command
25681 line parameters, as described in the corresponding section of this guide.
25682 The HP pragmas for control of optimization are
25683 recognized but ignored.
25684
25685 Note that in GNAT, the default is optimization off, whereas in HP Ada
25686 the default is that optimization is turned on.
25687
25688 @node Program Compilation and Library Management
25689 @section Program Compilation and Library Management
25690
25691 @noindent
25692 HP Ada and GNAT provide a comparable set of commands to
25693 build programs. HP Ada also provides a program library,
25694 which is a concept that does not exist on GNAT. Instead,
25695 GNAT provides directories of sources that are compiled as
25696 needed.
25697
25698 The following table summarizes
25699 the HP Ada commands and provides
25700 equivalent GNAT commands. In this table, some GNAT
25701 equivalents reflect the fact that GNAT does not use the
25702 concept of a program library. Instead, it uses a model
25703 in which collections of source and object files are used
25704 in a manner consistent with other languages like C and
25705 Fortran. Therefore, standard system file commands are used
25706 to manipulate these elements. Those GNAT commands are marked with
25707 an asterisk.
25708 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25709
25710 @need 1500
25711 @multitable @columnfractions .35 .65
25712
25713 @item @emph{HP Ada Command}
25714 @tab @emph{GNAT Equivalent / Description}
25715
25716 @item @command{ADA}
25717 @tab @command{GNAT COMPILE}@*
25718 Invokes the compiler to compile one or more Ada source files.
25719
25720 @item @command{ACS ATTACH}@*
25721 @tab [No equivalent]@*
25722 Switches control of terminal from current process running the program
25723 library manager.
25724
25725 @item @command{ACS CHECK}
25726 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25727 Forms the execution closure of one
25728 or more compiled units and checks completeness and currency.
25729
25730 @item @command{ACS COMPILE}
25731 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25732 Forms the execution closure of one or
25733 more specified units, checks completeness and currency,
25734 identifies units that have revised source files, compiles same,
25735 and recompiles units that are or will become obsolete.
25736 Also completes incomplete generic instantiations.
25737
25738 @item @command{ACS COPY FOREIGN}
25739 @tab Copy (*)@*
25740 Copies a foreign object file into the program library as a
25741 library unit body.
25742
25743 @item @command{ACS COPY UNIT}
25744 @tab Copy (*)@*
25745 Copies a compiled unit from one program library to another.
25746
25747 @item @command{ACS CREATE LIBRARY}
25748 @tab Create /directory (*)@*
25749 Creates a program library.
25750
25751 @item @command{ACS CREATE SUBLIBRARY}
25752 @tab Create /directory (*)@*
25753 Creates a program sublibrary.
25754
25755 @item @command{ACS DELETE LIBRARY}
25756 @tab @*
25757 Deletes a program library and its contents.
25758
25759 @item @command{ACS DELETE SUBLIBRARY}
25760 @tab @*
25761 Deletes a program sublibrary and its contents.
25762
25763 @item @command{ACS DELETE UNIT}
25764 @tab Delete file (*)@*
25765 On OpenVMS systems, deletes one or more compiled units from
25766 the current program library.
25767
25768 @item @command{ACS DIRECTORY}
25769 @tab Directory (*)@*
25770 On OpenVMS systems, lists units contained in the current
25771 program library.
25772
25773 @item @command{ACS ENTER FOREIGN}
25774 @tab Copy (*)@*
25775 Allows the import of a foreign body as an Ada library
25776 spec and enters a reference to a pointer.
25777
25778 @item @command{ACS ENTER UNIT}
25779 @tab Copy (*)@*
25780 Enters a reference (pointer) from the current program library to
25781 a unit compiled into another program library.
25782
25783 @item @command{ACS EXIT}
25784 @tab [No equivalent]@*
25785 Exits from the program library manager.
25786
25787 @item @command{ACS EXPORT}
25788 @tab Copy (*)@*
25789 Creates an object file that contains system-specific object code
25790 for one or more units. With GNAT, object files can simply be copied
25791 into the desired directory.
25792
25793 @item @command{ACS EXTRACT SOURCE}
25794 @tab Copy (*)@*
25795 Allows access to the copied source file for each Ada compilation unit
25796
25797 @item @command{ACS HELP}
25798 @tab @command{HELP GNAT}@*
25799 Provides online help.
25800
25801 @item @command{ACS LINK}
25802 @tab @command{GNAT LINK}@*
25803 Links an object file containing Ada units into an executable file.
25804
25805 @item @command{ACS LOAD}
25806 @tab Copy (*)@*
25807 Loads (partially compiles) Ada units into the program library.
25808 Allows loading a program from a collection of files into a library
25809 without knowing the relationship among units.
25810
25811 @item @command{ACS MERGE}
25812 @tab Copy (*)@*
25813 Merges into the current program library, one or more units from
25814 another library where they were modified.
25815
25816 @item @command{ACS RECOMPILE}
25817 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25818 Recompiles from   external or copied source files any obsolete
25819 unit in the closure. Also, completes any incomplete generic
25820 instantiations.
25821
25822 @item @command{ACS REENTER}
25823 @tab @command{GNAT MAKE}@*
25824 Reenters current references to units compiled after last entered
25825 with the @command{ACS ENTER UNIT} command.
25826
25827 @item @command{ACS SET LIBRARY}
25828 @tab Set default (*)@*
25829 Defines a program library to be the compilation context as well
25830 as the target library for compiler output and commands in general.
25831
25832 @item @command{ACS SET PRAGMA}
25833 @tab Edit @file{gnat.adc} (*)@*
25834 Redefines specified  values of the library characteristics
25835 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25836 and @code{Float_Representation}.
25837
25838 @item @command{ACS SET SOURCE}
25839 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25840 Defines the source file search list for the @command{ACS COMPILE} command.
25841
25842 @item @command{ACS SHOW LIBRARY}
25843 @tab Directory (*)@*
25844 Lists information about one or more program libraries.
25845
25846 @item @command{ACS SHOW PROGRAM}
25847 @tab [No equivalent]@*
25848 Lists information about the execution closure of one or
25849 more units in the program library.
25850
25851 @item @command{ACS SHOW SOURCE}
25852 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25853 Shows the source file search used when compiling units.
25854
25855 @item @command{ACS SHOW VERSION}
25856 @tab Compile with @option{VERBOSE} option
25857 Displays the version number of the compiler and program library
25858 manager used.
25859
25860 @item @command{ACS SPAWN}
25861 @tab [No equivalent]@*
25862 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25863 command).
25864
25865 @item @command{ACS VERIFY}
25866 @tab [No equivalent]@*
25867 Performs a series of consistency checks on a program library to
25868 determine whether the library structure and library files are in
25869 valid form.
25870 @end multitable
25871
25872 @noindent
25873
25874 @node Input-Output
25875 @section Input-Output
25876
25877 @noindent
25878 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25879 Management Services (RMS) to perform operations on
25880 external files.
25881
25882 @noindent
25883 HP Ada and GNAT predefine an identical set of input-
25884 output packages. To make the use of the
25885 generic @code{TEXT_IO} operations more convenient, HP Ada
25886 provides predefined library packages that instantiate the
25887 integer and floating-point operations for the predefined
25888 integer and floating-point types as shown in the following table.
25889
25890 @multitable @columnfractions .45 .55
25891 @item @emph{Package Name} @tab Instantiation
25892
25893 @item @code{INTEGER_TEXT_IO}
25894 @tab @code{INTEGER_IO(INTEGER)}
25895
25896 @item @code{SHORT_INTEGER_TEXT_IO}
25897 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25898
25899 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25900 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25901
25902 @item @code{FLOAT_TEXT_IO}
25903 @tab @code{FLOAT_IO(FLOAT)}
25904
25905 @item @code{LONG_FLOAT_TEXT_IO}
25906 @tab @code{FLOAT_IO(LONG_FLOAT)}
25907 @end multitable
25908
25909 @noindent
25910 The HP Ada predefined packages and their operations
25911 are implemented using OpenVMS Alpha files and input-output
25912 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25913 Familiarity with the following is recommended:
25914 @itemize @bullet
25915 @item  RMS file organizations and access methods
25916
25917 @item  OpenVMS file specifications and directories
25918
25919 @item  OpenVMS File Definition Language (FDL)
25920 @end itemize
25921
25922 @noindent
25923 GNAT provides I/O facilities that are completely
25924 compatible with HP Ada. The distribution includes the
25925 standard HP Ada versions of all I/O packages, operating
25926 in a manner compatible with HP Ada. In particular, the
25927 following packages are by default the HP Ada (Ada 83)
25928 versions of these packages rather than the renamings
25929 suggested in Annex J of the Ada Reference Manual:
25930 @itemize @bullet
25931 @item  @code{TEXT_IO}
25932
25933 @item  @code{SEQUENTIAL_IO}
25934
25935 @item  @code{DIRECT_IO}
25936 @end itemize
25937
25938 @noindent
25939 The use of the standard child package syntax (for
25940 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25941 packages.
25942 GNAT provides HP-compatible predefined instantiations
25943 of the @code{TEXT_IO} packages, and also
25944 provides the standard predefined instantiations required
25945 by the @cite{Ada Reference Manual}.
25946
25947 For further information on how GNAT interfaces to the file
25948 system or how I/O is implemented in programs written in
25949 mixed languages, see @ref{Implementation of the Standard I/O,,,
25950 gnat_rm, GNAT Reference Manual}.
25951 This chapter covers the following:
25952 @itemize @bullet
25953 @item  Standard I/O packages
25954
25955 @item  @code{FORM} strings
25956
25957 @item  @code{ADA.DIRECT_IO}
25958
25959 @item  @code{ADA.SEQUENTIAL_IO}
25960
25961 @item  @code{ADA.TEXT_IO}
25962
25963 @item  Stream pointer positioning
25964
25965 @item  Reading and writing non-regular files
25966
25967 @item  @code{GET_IMMEDIATE}
25968
25969 @item  Treating @code{TEXT_IO} files as streams
25970
25971 @item  Shared files
25972
25973 @item  Open modes
25974 @end itemize
25975
25976 @node Implementation Limits
25977 @section Implementation Limits
25978
25979 @noindent
25980 The following table lists implementation limits for HP Ada
25981 and GNAT systems.
25982 @multitable @columnfractions .60 .20 .20
25983 @sp 1
25984 @item  @emph{Compilation Parameter}
25985 @tab   @emph{HP Ada}
25986 @tab   @emph{GNAT}
25987 @sp 1
25988
25989 @item  In a subprogram or entry  declaration, maximum number of
25990 formal parameters that are of an unconstrained record type
25991 @tab   32
25992 @tab   No set limit
25993 @sp 1
25994
25995 @item  Maximum identifier length (number of characters)
25996 @tab   255
25997 @tab   32766
25998 @sp 1
25999
26000 @item  Maximum number of characters in a source line
26001 @tab   255
26002 @tab   32766
26003 @sp 1
26004
26005 @item  Maximum collection size   (number of bytes)
26006 @tab   2**31-1
26007 @tab   2**31-1
26008 @sp 1
26009
26010 @item  Maximum number of discriminants for a record type
26011 @tab   245
26012 @tab   No set limit
26013 @sp 1
26014
26015 @item  Maximum number of formal parameters in an entry or
26016 subprogram declaration
26017 @tab   246
26018 @tab    No set limit
26019 @sp 1
26020
26021 @item  Maximum number of dimensions in an array type
26022 @tab   255
26023 @tab   No set limit
26024 @sp 1
26025
26026 @item  Maximum number of library  units and subunits in a compilation.
26027 @tab   4095
26028 @tab   No set limit
26029 @sp 1
26030
26031 @item  Maximum number of library units and subunits in an execution.
26032 @tab   16383
26033 @tab   No set limit
26034 @sp 1
26035
26036 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26037 or @code{PSECT_OBJECT}
26038 @tab   32757
26039 @tab   No set limit
26040 @sp 1
26041
26042 @item  Maximum number of enumeration literals in an enumeration type
26043 definition
26044 @tab   65535
26045 @tab   No set limit
26046 @sp 1
26047
26048 @item  Maximum number of lines in a source file
26049 @tab   65534
26050 @tab   No set limit
26051 @sp 1
26052
26053 @item  Maximum number of bits in any object
26054 @tab   2**31-1
26055 @tab   2**31-1
26056 @sp 1
26057
26058 @item  Maximum size of the static portion of a stack frame (approximate)
26059 @tab   2**31-1
26060 @tab   2**31-1
26061 @end multitable
26062
26063 @node Tools and Utilities
26064 @section Tools and Utilities
26065
26066 @noindent
26067 The following table lists some of the OpenVMS development tools
26068 available for HP Ada, and the corresponding tools for
26069 use with @value{EDITION} on Alpha and I64 platforms.
26070 Aside from the debugger, all the OpenVMS tools identified are part
26071 of the DECset package.
26072
26073 @iftex
26074 @c Specify table in TeX since Texinfo does a poor job
26075 @tex
26076 \smallskip
26077 \smallskip
26078 \settabs\+Language-Sensitive Editor\quad
26079    &Product with HP Ada\quad
26080    &\cr
26081 \+\it Tool
26082    &\it Product with HP Ada
26083    & \it Product with GNAT Pro\cr
26084 \smallskip
26085 \+Code Management System
26086    &HP CMS
26087    & HP CMS\cr
26088 \smallskip
26089 \+Language-Sensitive Editor
26090    &HP LSE
26091    & emacs or HP LSE (Alpha)\cr
26092 \+
26093    &
26094    & HP LSE (I64)\cr
26095 \smallskip
26096 \+Debugger
26097    &OpenVMS Debug
26098    & gdb (Alpha),\cr
26099 \+
26100    &
26101    & OpenVMS Debug (I64)\cr
26102 \smallskip
26103 \+Source Code Analyzer /
26104    &HP SCA
26105    & GNAT XREF\cr
26106 \+Cross Referencer
26107    &
26108    &\cr
26109 \smallskip
26110 \+Test Manager
26111    &HP Digital Test
26112    & HP DTM\cr
26113 \+
26114    &Manager (DTM)
26115    &\cr
26116 \smallskip
26117 \+Performance and
26118    & HP PCA
26119    & HP PCA\cr
26120 \+Coverage Analyzer
26121    &
26122    &\cr
26123 \smallskip
26124 \+Module Management
26125    & HP MMS
26126    & Not applicable\cr
26127 \+ System
26128    &
26129    &\cr
26130 \smallskip
26131 \smallskip
26132 @end tex
26133 @end iftex
26134
26135 @ifnottex
26136 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26137 @c the TeX version above for the printed version
26138 @flushleft
26139 @c @multitable @columnfractions .3 .4 .4
26140 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26141 @item @i{Tool}
26142 @tab @i{Tool with HP Ada}
26143 @tab @i{Tool with @value{EDITION}}
26144 @item Code Management@*System
26145 @tab HP CMS
26146 @tab HP CMS
26147 @item Language-Sensitive@*Editor
26148 @tab HP LSE
26149 @tab emacs or HP LSE (Alpha)
26150 @item
26151 @tab
26152 @tab HP LSE (I64)
26153 @item Debugger
26154 @tab OpenVMS Debug
26155 @tab gdb (Alpha),
26156 @item
26157 @tab
26158 @tab OpenVMS Debug (I64)
26159 @item Source Code Analyzer /@*Cross Referencer
26160 @tab HP SCA
26161 @tab GNAT XREF
26162 @item Test Manager
26163 @tab HP Digital Test@*Manager (DTM)
26164 @tab HP DTM
26165 @item Performance and@*Coverage Analyzer
26166 @tab HP PCA
26167 @tab HP PCA
26168 @item Module Management@*System
26169 @tab HP MMS
26170 @tab Not applicable
26171 @end multitable
26172 @end flushleft
26173 @end ifnottex
26174
26175 @end ifset
26176
26177 @c **************************************
26178 @node Platform-Specific Information for the Run-Time Libraries
26179 @appendix Platform-Specific Information for the Run-Time Libraries
26180 @cindex Tasking and threads libraries
26181 @cindex Threads libraries and tasking
26182 @cindex Run-time libraries (platform-specific information)
26183
26184 @noindent
26185 The GNAT run-time implementation may vary with respect to both the
26186 underlying threads library and the exception handling scheme.
26187 For threads support, one or more of the following are supplied:
26188 @itemize @bullet
26189 @item @b{native threads library}, a binding to the thread package from
26190 the underlying operating system
26191
26192 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26193 POSIX thread package
26194 @end itemize
26195
26196 @noindent
26197 For exception handling, either or both of two models are supplied:
26198 @itemize @bullet
26199 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26200 Most programs should experience a substantial speed improvement by
26201 being compiled with a ZCX run-time.
26202 This is especially true for
26203 tasking applications or applications with many exception handlers.}
26204 @cindex Zero-Cost Exceptions
26205 @cindex ZCX (Zero-Cost Exceptions)
26206 which uses binder-generated tables that
26207 are interrogated at run time to locate a handler
26208
26209 @item @b{setjmp / longjmp} (``SJLJ''),
26210 @cindex setjmp/longjmp Exception Model
26211 @cindex SJLJ (setjmp/longjmp Exception Model)
26212 which uses dynamically-set data to establish
26213 the set of handlers
26214 @end itemize
26215
26216 @noindent
26217 This appendix summarizes which combinations of threads and exception support
26218 are supplied on various GNAT platforms.
26219 It then shows how to select a particular library either
26220 permanently or temporarily,
26221 explains the properties of (and tradeoffs among) the various threads
26222 libraries, and provides some additional
26223 information about several specific platforms.
26224
26225 @menu
26226 * Summary of Run-Time Configurations::
26227 * Specifying a Run-Time Library::
26228 * Choosing the Scheduling Policy::
26229 * Solaris-Specific Considerations::
26230 * Linux-Specific Considerations::
26231 * AIX-Specific Considerations::
26232 * Irix-Specific Considerations::
26233 * RTX-Specific Considerations::
26234 @end menu
26235
26236 @node Summary of Run-Time Configurations
26237 @section Summary of Run-Time Configurations
26238
26239 @multitable @columnfractions .30 .70
26240 @item @b{alpha-openvms}
26241 @item @code{@ @ }@i{rts-native (default)}
26242 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26243 @item @code{@ @ @ @ }Exceptions @tab ZCX
26244 @*
26245 @item @b{alpha-tru64}
26246 @item @code{@ @ }@i{rts-native (default)}
26247 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26248 @item @code{@ @ @ @ }Exceptions @tab ZCX
26249 @*
26250 @item @code{@ @ }@i{rts-sjlj}
26251 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26252 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26253 @*
26254 @item @b{ia64-hp_linux}
26255 @item @code{@ @ }@i{rts-native (default)}
26256 @item @code{@ @ @ @ }Tasking    @tab pthread library
26257 @item @code{@ @ @ @ }Exceptions @tab ZCX
26258 @*
26259 @item @b{ia64-hpux}
26260 @item @code{@ @ }@i{rts-native (default)}
26261 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26262 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26263 @*
26264 @item @b{ia64-openvms}
26265 @item @code{@ @ }@i{rts-native (default)}
26266 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26267 @item @code{@ @ @ @ }Exceptions @tab ZCX
26268 @*
26269 @item @b{ia64-sgi_linux}
26270 @item @code{@ @ }@i{rts-native (default)}
26271 @item @code{@ @ @ @ }Tasking    @tab pthread library
26272 @item @code{@ @ @ @ }Exceptions @tab ZCX
26273 @*
26274 @item @b{mips-irix}
26275 @item @code{@ @ }@i{rts-native (default)}
26276 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26277 @item @code{@ @ @ @ }Exceptions @tab ZCX
26278 @*
26279 @item @b{pa-hpux}
26280 @item @code{@ @ }@i{rts-native (default)}
26281 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26282 @item @code{@ @ @ @ }Exceptions @tab ZCX
26283 @*
26284 @item @code{@ @ }@i{rts-sjlj}
26285 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26286 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26287 @*
26288 @item @b{ppc-aix}
26289 @item @code{@ @ }@i{rts-native (default)}
26290 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26291 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26292 @*
26293 @item @b{ppc-darwin}
26294 @item @code{@ @ }@i{rts-native (default)}
26295 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26296 @item @code{@ @ @ @ }Exceptions @tab ZCX
26297 @*
26298 @item @b{sparc-solaris}  @tab
26299 @item @code{@ @ }@i{rts-native (default)}
26300 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26301 @item @code{@ @ @ @ }Exceptions @tab ZCX
26302 @*
26303 @item @code{@ @ }@i{rts-pthread}
26304 @item @code{@ @ @ @ }Tasking    @tab pthread library
26305 @item @code{@ @ @ @ }Exceptions @tab ZCX
26306 @*
26307 @item @code{@ @ }@i{rts-sjlj}
26308 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26309 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26310 @*
26311 @item @b{sparc64-solaris}  @tab
26312 @item @code{@ @ }@i{rts-native (default)}
26313 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26314 @item @code{@ @ @ @ }Exceptions @tab ZCX
26315 @*
26316 @item @b{x86-linux}
26317 @item @code{@ @ }@i{rts-native (default)}
26318 @item @code{@ @ @ @ }Tasking    @tab pthread library
26319 @item @code{@ @ @ @ }Exceptions @tab ZCX
26320 @*
26321 @item @code{@ @ }@i{rts-sjlj}
26322 @item @code{@ @ @ @ }Tasking    @tab pthread library
26323 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26324 @*
26325 @item @b{x86-lynx}
26326 @item @code{@ @ }@i{rts-native (default)}
26327 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26328 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26329 @*
26330 @item @b{x86-solaris}
26331 @item @code{@ @ }@i{rts-native (default)}
26332 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26333 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26334 @*
26335 @item @b{x86-windows}
26336 @item @code{@ @ }@i{rts-native (default)}
26337 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26338 @item @code{@ @ @ @ }Exceptions @tab ZCX
26339 @*
26340 @item @code{@ @ }@i{rts-sjlj (default)}
26341 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26342 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26343 @*
26344 @item @b{x86-windows-rtx}
26345 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26346 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26347 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26348 @*
26349 @item @code{@ @ }@i{rts-rtx-w32}
26350 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26351 @item @code{@ @ @ @ }Exceptions @tab ZCX
26352 @*
26353 @item @b{x86_64-linux}
26354 @item @code{@ @ }@i{rts-native (default)}
26355 @item @code{@ @ @ @ }Tasking    @tab pthread library
26356 @item @code{@ @ @ @ }Exceptions @tab ZCX
26357 @*
26358 @item @code{@ @ }@i{rts-sjlj}
26359 @item @code{@ @ @ @ }Tasking    @tab pthread library
26360 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26361 @*
26362 @end multitable
26363
26364 @node Specifying a Run-Time Library
26365 @section Specifying a Run-Time Library
26366
26367 @noindent
26368 The @file{adainclude} subdirectory containing the sources of the GNAT
26369 run-time library, and the @file{adalib} subdirectory containing the
26370 @file{ALI} files and the static and/or shared GNAT library, are located
26371 in the gcc target-dependent area:
26372
26373 @smallexample
26374 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26375 @end smallexample
26376
26377 @noindent
26378 As indicated above, on some platforms several run-time libraries are supplied.
26379 These libraries are installed in the target dependent area and
26380 contain a complete source and binary subdirectory. The detailed description
26381 below explains the differences between the different libraries in terms of
26382 their thread support.
26383
26384 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26385 This default run time is selected by the means of soft links.
26386 For example on x86-linux:
26387
26388 @smallexample
26389 @group
26390  $(target-dir)
26391      |
26392      +--- adainclude----------+
26393      |                        |
26394      +--- adalib-----------+  |
26395      |                     |  |
26396      +--- rts-native       |  |
26397      |    |                |  |
26398      |    +--- adainclude <---+
26399      |    |                |
26400      |    +--- adalib <----+
26401      |
26402      +--- rts-sjlj
26403           |
26404           +--- adainclude
26405           |
26406           +--- adalib
26407 @end group
26408 @end smallexample
26409
26410 @noindent
26411 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26412 these soft links can be modified with the following commands:
26413
26414 @smallexample
26415 $ cd $target
26416 $ rm -f adainclude adalib
26417 $ ln -s rts-sjlj/adainclude adainclude
26418 $ ln -s rts-sjlj/adalib adalib
26419 @end smallexample
26420
26421 @noindent
26422 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26423 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26424 @file{$target/ada_object_path}.
26425
26426 Selecting another run-time library temporarily can be
26427 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26428 @cindex @option{--RTS} option
26429
26430 @node Choosing the Scheduling Policy
26431 @section Choosing the Scheduling Policy
26432
26433 @noindent
26434 When using a POSIX threads implementation, you have a choice of several
26435 scheduling policies: @code{SCHED_FIFO},
26436 @cindex @code{SCHED_FIFO} scheduling policy
26437 @code{SCHED_RR}
26438 @cindex @code{SCHED_RR} scheduling policy
26439 and @code{SCHED_OTHER}.
26440 @cindex @code{SCHED_OTHER} scheduling policy
26441 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26442 or @code{SCHED_RR} requires special (e.g., root) privileges.
26443
26444 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26445 @code{SCHED_FIFO},
26446 @cindex @code{SCHED_FIFO} scheduling policy
26447 you can use one of the following:
26448
26449 @itemize @bullet
26450 @item
26451 @code{pragma Time_Slice (0.0)}
26452 @cindex pragma Time_Slice
26453 @item
26454 the corresponding binder option @option{-T0}
26455 @cindex @option{-T0} option
26456 @item
26457 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26458 @cindex pragma Task_Dispatching_Policy
26459 @end itemize
26460
26461 @noindent
26462 To specify @code{SCHED_RR},
26463 @cindex @code{SCHED_RR} scheduling policy
26464 you should use @code{pragma Time_Slice} with a
26465 value greater than @code{0.0}, or else use the corresponding @option{-T}
26466 binder option.
26467
26468 @node Solaris-Specific Considerations
26469 @section Solaris-Specific Considerations
26470 @cindex Solaris Sparc threads libraries
26471
26472 @noindent
26473 This section addresses some topics related to the various threads libraries
26474 on Sparc Solaris.
26475
26476 @menu
26477 * Solaris Threads Issues::
26478 @end menu
26479
26480 @node Solaris Threads Issues
26481 @subsection Solaris Threads Issues
26482
26483 @noindent
26484 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26485 library based on POSIX threads --- @emph{rts-pthread}.
26486 @cindex rts-pthread threads library
26487 This run-time library has the advantage of being mostly shared across all
26488 POSIX-compliant thread implementations, and it also provides under
26489 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26490 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26491 and @code{PTHREAD_PRIO_PROTECT}
26492 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26493 semantics that can be selected using the predefined pragma
26494 @code{Locking_Policy}
26495 @cindex pragma Locking_Policy (under rts-pthread)
26496 with respectively
26497 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26498 @cindex @code{Inheritance_Locking} (under rts-pthread)
26499 @cindex @code{Ceiling_Locking} (under rts-pthread)
26500
26501 As explained above, the native run-time library is based on the Solaris thread
26502 library (@code{libthread}) and is the default library.
26503
26504 When the Solaris threads library is used (this is the default), programs
26505 compiled with GNAT can automatically take advantage of
26506 and can thus execute on multiple processors.
26507 The user can alternatively specify a processor on which the program should run
26508 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26509 is made by
26510 setting the environment variable @env{GNAT_PROCESSOR}
26511 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26512 to one of the following:
26513
26514 @table @code
26515 @item -2
26516 Use the default configuration (run the program on all
26517 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26518 unset
26519
26520 @item -1
26521 Let the run-time implementation choose one processor and run the program on
26522 that processor
26523
26524 @item 0 .. Last_Proc
26525 Run the program on the specified processor.
26526 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26527 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26528 @end table
26529
26530 @node Linux-Specific Considerations
26531 @section Linux-Specific Considerations
26532 @cindex Linux threads libraries
26533
26534 @noindent
26535 On GNU/Linux without NPTL support (usually system with GNU C Library
26536 older than 2.3), the signal model is not POSIX compliant, which means
26537 that to send a signal to the process, you need to send the signal to all
26538 threads, e.g.@: by using @code{killpg()}.
26539
26540 @node AIX-Specific Considerations
26541 @section AIX-Specific Considerations
26542 @cindex AIX resolver library
26543
26544 @noindent
26545 On AIX, the resolver library initializes some internal structure on
26546 the first call to @code{get*by*} functions, which are used to implement
26547 @code{GNAT.Sockets.Get_Host_By_Name} and
26548 @code{GNAT.Sockets.Get_Host_By_Address}.
26549 If such initialization occurs within an Ada task, and the stack size for
26550 the task is the default size, a stack overflow may occur.
26551
26552 To avoid this overflow, the user should either ensure that the first call
26553 to @code{GNAT.Sockets.Get_Host_By_Name} or
26554 @code{GNAT.Sockets.Get_Host_By_Addrss}
26555 occurs in the environment task, or use @code{pragma Storage_Size} to
26556 specify a sufficiently large size for the stack of the task that contains
26557 this call.
26558
26559 @node Irix-Specific Considerations
26560 @section Irix-Specific Considerations
26561 @cindex Irix libraries
26562
26563 @noindent
26564 The GCC support libraries coming with the Irix compiler have moved to
26565 their canonical place with respect to the general Irix ABI related
26566 conventions. Running applications built with the default shared GNAT
26567 run-time now requires the LD_LIBRARY_PATH environment variable to
26568 include this location. A possible way to achieve this is to issue the
26569 following command line on a bash prompt:
26570
26571 @smallexample
26572 @group
26573 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26574 @end group
26575 @end smallexample
26576
26577 @node RTX-Specific Considerations
26578 @section RTX-Specific Considerations
26579 @cindex RTX libraries
26580
26581 @noindent
26582 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26583 API. Applications can be built to work in two different modes:
26584
26585 @itemize @bullet
26586 @item
26587 Windows executables that run in Ring 3 to utilize memory protection
26588 (@emph{rts-rtx-w32}).
26589
26590 @item
26591 Real-time subsystem (RTSS) executables that run in Ring 0, where
26592 performance can be optimized with RTSS applications taking precedent
26593 over all Windows applications (@emph{rts-rtx-rtss}).
26594
26595 @end itemize
26596
26597 @c *******************************
26598 @node Example of Binder Output File
26599 @appendix Example of Binder Output File
26600
26601 @noindent
26602 This Appendix displays the source code for @command{gnatbind}'s output
26603 file generated for a simple ``Hello World'' program.
26604 Comments have been added for clarification purposes.
26605
26606 @smallexample @c adanocomment
26607 @iftex
26608 @leftskip=0cm
26609 @end iftex
26610 --  The package is called Ada_Main unless this name is actually used
26611 --  as a unit name in the partition, in which case some other unique
26612 --  name is used.
26613
26614 with System;
26615 package ada_main is
26616
26617    Elab_Final_Code : Integer;
26618    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26619
26620    --  The main program saves the parameters (argument count,
26621    --  argument values, environment pointer) in global variables
26622    --  for later access by other units including
26623    --  Ada.Command_Line.
26624
26625    gnat_argc : Integer;
26626    gnat_argv : System.Address;
26627    gnat_envp : System.Address;
26628
26629    --  The actual variables are stored in a library routine. This
26630    --  is useful for some shared library situations, where there
26631    --  are problems if variables are not in the library.
26632
26633    pragma Import (C, gnat_argc);
26634    pragma Import (C, gnat_argv);
26635    pragma Import (C, gnat_envp);
26636
26637    --  The exit status is similarly an external location
26638
26639    gnat_exit_status : Integer;
26640    pragma Import (C, gnat_exit_status);
26641
26642    GNAT_Version : constant String :=
26643                     "GNAT Version: 6.0.0w (20061115)";
26644    pragma Export (C, GNAT_Version, "__gnat_version");
26645
26646    --  This is the generated adafinal routine that performs
26647    --  finalization at the end of execution. In the case where
26648    --  Ada is the main program, this main program makes a call
26649    --  to adafinal at program termination.
26650
26651    procedure adafinal;
26652    pragma Export (C, adafinal, "adafinal");
26653
26654    --  This is the generated adainit routine that performs
26655    --  initialization at the start of execution. In the case
26656    --  where Ada is the main program, this main program makes
26657    --  a call to adainit at program startup.
26658
26659    procedure adainit;
26660    pragma Export (C, adainit, "adainit");
26661
26662    --  This routine is called at the start of execution. It is
26663    --  a dummy routine that is used by the debugger to breakpoint
26664    --  at the start of execution.
26665
26666    procedure Break_Start;
26667    pragma Import (C, Break_Start, "__gnat_break_start");
26668
26669    --  This is the actual generated main program (it would be
26670    --  suppressed if the no main program switch were used). As
26671    --  required by standard system conventions, this program has
26672    --  the external name main.
26673
26674    function main
26675      (argc : Integer;
26676       argv : System.Address;
26677       envp : System.Address)
26678       return Integer;
26679    pragma Export (C, main, "main");
26680
26681    --  The following set of constants give the version
26682    --  identification values for every unit in the bound
26683    --  partition. This identification is computed from all
26684    --  dependent semantic units, and corresponds to the
26685    --  string that would be returned by use of the
26686    --  Body_Version or Version attributes.
26687
26688    type Version_32 is mod 2 ** 32;
26689    u00001 : constant Version_32 := 16#7880BEB3#;
26690    u00002 : constant Version_32 := 16#0D24CBD0#;
26691    u00003 : constant Version_32 := 16#3283DBEB#;
26692    u00004 : constant Version_32 := 16#2359F9ED#;
26693    u00005 : constant Version_32 := 16#664FB847#;
26694    u00006 : constant Version_32 := 16#68E803DF#;
26695    u00007 : constant Version_32 := 16#5572E604#;
26696    u00008 : constant Version_32 := 16#46B173D8#;
26697    u00009 : constant Version_32 := 16#156A40CF#;
26698    u00010 : constant Version_32 := 16#033DABE0#;
26699    u00011 : constant Version_32 := 16#6AB38FEA#;
26700    u00012 : constant Version_32 := 16#22B6217D#;
26701    u00013 : constant Version_32 := 16#68A22947#;
26702    u00014 : constant Version_32 := 16#18CC4A56#;
26703    u00015 : constant Version_32 := 16#08258E1B#;
26704    u00016 : constant Version_32 := 16#367D5222#;
26705    u00017 : constant Version_32 := 16#20C9ECA4#;
26706    u00018 : constant Version_32 := 16#50D32CB6#;
26707    u00019 : constant Version_32 := 16#39A8BB77#;
26708    u00020 : constant Version_32 := 16#5CF8FA2B#;
26709    u00021 : constant Version_32 := 16#2F1EB794#;
26710    u00022 : constant Version_32 := 16#31AB6444#;
26711    u00023 : constant Version_32 := 16#1574B6E9#;
26712    u00024 : constant Version_32 := 16#5109C189#;
26713    u00025 : constant Version_32 := 16#56D770CD#;
26714    u00026 : constant Version_32 := 16#02F9DE3D#;
26715    u00027 : constant Version_32 := 16#08AB6B2C#;
26716    u00028 : constant Version_32 := 16#3FA37670#;
26717    u00029 : constant Version_32 := 16#476457A0#;
26718    u00030 : constant Version_32 := 16#731E1B6E#;
26719    u00031 : constant Version_32 := 16#23C2E789#;
26720    u00032 : constant Version_32 := 16#0F1BD6A1#;
26721    u00033 : constant Version_32 := 16#7C25DE96#;
26722    u00034 : constant Version_32 := 16#39ADFFA2#;
26723    u00035 : constant Version_32 := 16#571DE3E7#;
26724    u00036 : constant Version_32 := 16#5EB646AB#;
26725    u00037 : constant Version_32 := 16#4249379B#;
26726    u00038 : constant Version_32 := 16#0357E00A#;
26727    u00039 : constant Version_32 := 16#3784FB72#;
26728    u00040 : constant Version_32 := 16#2E723019#;
26729    u00041 : constant Version_32 := 16#623358EA#;
26730    u00042 : constant Version_32 := 16#107F9465#;
26731    u00043 : constant Version_32 := 16#6843F68A#;
26732    u00044 : constant Version_32 := 16#63305874#;
26733    u00045 : constant Version_32 := 16#31E56CE1#;
26734    u00046 : constant Version_32 := 16#02917970#;
26735    u00047 : constant Version_32 := 16#6CCBA70E#;
26736    u00048 : constant Version_32 := 16#41CD4204#;
26737    u00049 : constant Version_32 := 16#572E3F58#;
26738    u00050 : constant Version_32 := 16#20729FF5#;
26739    u00051 : constant Version_32 := 16#1D4F93E8#;
26740    u00052 : constant Version_32 := 16#30B2EC3D#;
26741    u00053 : constant Version_32 := 16#34054F96#;
26742    u00054 : constant Version_32 := 16#5A199860#;
26743    u00055 : constant Version_32 := 16#0E7F912B#;
26744    u00056 : constant Version_32 := 16#5760634A#;
26745    u00057 : constant Version_32 := 16#5D851835#;
26746
26747    --  The following Export pragmas export the version numbers
26748    --  with symbolic names ending in B (for body) or S
26749    --  (for spec) so that they can be located in a link. The
26750    --  information provided here is sufficient to track down
26751    --  the exact versions of units used in a given build.
26752
26753    pragma Export (C, u00001, "helloB");
26754    pragma Export (C, u00002, "system__standard_libraryB");
26755    pragma Export (C, u00003, "system__standard_libraryS");
26756    pragma Export (C, u00004, "adaS");
26757    pragma Export (C, u00005, "ada__text_ioB");
26758    pragma Export (C, u00006, "ada__text_ioS");
26759    pragma Export (C, u00007, "ada__exceptionsB");
26760    pragma Export (C, u00008, "ada__exceptionsS");
26761    pragma Export (C, u00009, "gnatS");
26762    pragma Export (C, u00010, "gnat__heap_sort_aB");
26763    pragma Export (C, u00011, "gnat__heap_sort_aS");
26764    pragma Export (C, u00012, "systemS");
26765    pragma Export (C, u00013, "system__exception_tableB");
26766    pragma Export (C, u00014, "system__exception_tableS");
26767    pragma Export (C, u00015, "gnat__htableB");
26768    pragma Export (C, u00016, "gnat__htableS");
26769    pragma Export (C, u00017, "system__exceptionsS");
26770    pragma Export (C, u00018, "system__machine_state_operationsB");
26771    pragma Export (C, u00019, "system__machine_state_operationsS");
26772    pragma Export (C, u00020, "system__machine_codeS");
26773    pragma Export (C, u00021, "system__storage_elementsB");
26774    pragma Export (C, u00022, "system__storage_elementsS");
26775    pragma Export (C, u00023, "system__secondary_stackB");
26776    pragma Export (C, u00024, "system__secondary_stackS");
26777    pragma Export (C, u00025, "system__parametersB");
26778    pragma Export (C, u00026, "system__parametersS");
26779    pragma Export (C, u00027, "system__soft_linksB");
26780    pragma Export (C, u00028, "system__soft_linksS");
26781    pragma Export (C, u00029, "system__stack_checkingB");
26782    pragma Export (C, u00030, "system__stack_checkingS");
26783    pragma Export (C, u00031, "system__tracebackB");
26784    pragma Export (C, u00032, "system__tracebackS");
26785    pragma Export (C, u00033, "ada__streamsS");
26786    pragma Export (C, u00034, "ada__tagsB");
26787    pragma Export (C, u00035, "ada__tagsS");
26788    pragma Export (C, u00036, "system__string_opsB");
26789    pragma Export (C, u00037, "system__string_opsS");
26790    pragma Export (C, u00038, "interfacesS");
26791    pragma Export (C, u00039, "interfaces__c_streamsB");
26792    pragma Export (C, u00040, "interfaces__c_streamsS");
26793    pragma Export (C, u00041, "system__file_ioB");
26794    pragma Export (C, u00042, "system__file_ioS");
26795    pragma Export (C, u00043, "ada__finalizationB");
26796    pragma Export (C, u00044, "ada__finalizationS");
26797    pragma Export (C, u00045, "system__finalization_rootB");
26798    pragma Export (C, u00046, "system__finalization_rootS");
26799    pragma Export (C, u00047, "system__finalization_implementationB");
26800    pragma Export (C, u00048, "system__finalization_implementationS");
26801    pragma Export (C, u00049, "system__string_ops_concat_3B");
26802    pragma Export (C, u00050, "system__string_ops_concat_3S");
26803    pragma Export (C, u00051, "system__stream_attributesB");
26804    pragma Export (C, u00052, "system__stream_attributesS");
26805    pragma Export (C, u00053, "ada__io_exceptionsS");
26806    pragma Export (C, u00054, "system__unsigned_typesS");
26807    pragma Export (C, u00055, "system__file_control_blockS");
26808    pragma Export (C, u00056, "ada__finalization__list_controllerB");
26809    pragma Export (C, u00057, "ada__finalization__list_controllerS");
26810
26811    -- BEGIN ELABORATION ORDER
26812    -- ada (spec)
26813    -- gnat (spec)
26814    -- gnat.heap_sort_a (spec)
26815    -- gnat.heap_sort_a (body)
26816    -- gnat.htable (spec)
26817    -- gnat.htable (body)
26818    -- interfaces (spec)
26819    -- system (spec)
26820    -- system.machine_code (spec)
26821    -- system.parameters (spec)
26822    -- system.parameters (body)
26823    -- interfaces.c_streams (spec)
26824    -- interfaces.c_streams (body)
26825    -- system.standard_library (spec)
26826    -- ada.exceptions (spec)
26827    -- system.exception_table (spec)
26828    -- system.exception_table (body)
26829    -- ada.io_exceptions (spec)
26830    -- system.exceptions (spec)
26831    -- system.storage_elements (spec)
26832    -- system.storage_elements (body)
26833    -- system.machine_state_operations (spec)
26834    -- system.machine_state_operations (body)
26835    -- system.secondary_stack (spec)
26836    -- system.stack_checking (spec)
26837    -- system.soft_links (spec)
26838    -- system.soft_links (body)
26839    -- system.stack_checking (body)
26840    -- system.secondary_stack (body)
26841    -- system.standard_library (body)
26842    -- system.string_ops (spec)
26843    -- system.string_ops (body)
26844    -- ada.tags (spec)
26845    -- ada.tags (body)
26846    -- ada.streams (spec)
26847    -- system.finalization_root (spec)
26848    -- system.finalization_root (body)
26849    -- system.string_ops_concat_3 (spec)
26850    -- system.string_ops_concat_3 (body)
26851    -- system.traceback (spec)
26852    -- system.traceback (body)
26853    -- ada.exceptions (body)
26854    -- system.unsigned_types (spec)
26855    -- system.stream_attributes (spec)
26856    -- system.stream_attributes (body)
26857    -- system.finalization_implementation (spec)
26858    -- system.finalization_implementation (body)
26859    -- ada.finalization (spec)
26860    -- ada.finalization (body)
26861    -- ada.finalization.list_controller (spec)
26862    -- ada.finalization.list_controller (body)
26863    -- system.file_control_block (spec)
26864    -- system.file_io (spec)
26865    -- system.file_io (body)
26866    -- ada.text_io (spec)
26867    -- ada.text_io (body)
26868    -- hello (body)
26869    -- END ELABORATION ORDER
26870
26871 end ada_main;
26872
26873 --  The following source file name pragmas allow the generated file
26874 --  names to be unique for different main programs. They are needed
26875 --  since the package name will always be Ada_Main.
26876
26877 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26878 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26879
26880 --  Generated package body for Ada_Main starts here
26881
26882 package body ada_main is
26883
26884    --  The actual finalization is performed by calling the
26885    --  library routine in System.Standard_Library.Adafinal
26886
26887    procedure Do_Finalize;
26888    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26889
26890    -------------
26891    -- adainit --
26892    -------------
26893
26894 @findex adainit
26895    procedure adainit is
26896
26897       --  These booleans are set to True once the associated unit has
26898       --  been elaborated. It is also used to avoid elaborating the
26899       --  same unit twice.
26900
26901       E040 : Boolean;
26902       pragma Import (Ada, E040, "interfaces__c_streams_E");
26903
26904       E008 : Boolean;
26905       pragma Import (Ada, E008, "ada__exceptions_E");
26906
26907       E014 : Boolean;
26908       pragma Import (Ada, E014, "system__exception_table_E");
26909
26910       E053 : Boolean;
26911       pragma Import (Ada, E053, "ada__io_exceptions_E");
26912
26913       E017 : Boolean;
26914       pragma Import (Ada, E017, "system__exceptions_E");
26915
26916       E024 : Boolean;
26917       pragma Import (Ada, E024, "system__secondary_stack_E");
26918
26919       E030 : Boolean;
26920       pragma Import (Ada, E030, "system__stack_checking_E");
26921
26922       E028 : Boolean;
26923       pragma Import (Ada, E028, "system__soft_links_E");
26924
26925       E035 : Boolean;
26926       pragma Import (Ada, E035, "ada__tags_E");
26927
26928       E033 : Boolean;
26929       pragma Import (Ada, E033, "ada__streams_E");
26930
26931       E046 : Boolean;
26932       pragma Import (Ada, E046, "system__finalization_root_E");
26933
26934       E048 : Boolean;
26935       pragma Import (Ada, E048, "system__finalization_implementation_E");
26936
26937       E044 : Boolean;
26938       pragma Import (Ada, E044, "ada__finalization_E");
26939
26940       E057 : Boolean;
26941       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26942
26943       E055 : Boolean;
26944       pragma Import (Ada, E055, "system__file_control_block_E");
26945
26946       E042 : Boolean;
26947       pragma Import (Ada, E042, "system__file_io_E");
26948
26949       E006 : Boolean;
26950       pragma Import (Ada, E006, "ada__text_io_E");
26951
26952       --  Set_Globals is a library routine that stores away the
26953       --  value of the indicated set of global values in global
26954       --  variables within the library.
26955
26956       procedure Set_Globals
26957         (Main_Priority            : Integer;
26958          Time_Slice_Value         : Integer;
26959          WC_Encoding              : Character;
26960          Locking_Policy           : Character;
26961          Queuing_Policy           : Character;
26962          Task_Dispatching_Policy  : Character;
26963          Adafinal                 : System.Address;
26964          Unreserve_All_Interrupts : Integer;
26965          Exception_Tracebacks     : Integer);
26966 @findex __gnat_set_globals
26967       pragma Import (C, Set_Globals, "__gnat_set_globals");
26968
26969       --  SDP_Table_Build is a library routine used to build the
26970       --  exception tables. See unit Ada.Exceptions in files
26971       --  a-except.ads/adb for full details of how zero cost
26972       --  exception handling works. This procedure, the call to
26973       --  it, and the two following tables are all omitted if the
26974       --  build is in longjmp/setjmp exception mode.
26975
26976 @findex SDP_Table_Build
26977 @findex Zero Cost Exceptions
26978       procedure SDP_Table_Build
26979         (SDP_Addresses   : System.Address;
26980          SDP_Count       : Natural;
26981          Elab_Addresses  : System.Address;
26982          Elab_Addr_Count : Natural);
26983       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26984
26985       --  Table of Unit_Exception_Table addresses. Used for zero
26986       --  cost exception handling to build the top level table.
26987
26988       ST : aliased constant array (1 .. 23) of System.Address := (
26989         Hello'UET_Address,
26990         Ada.Text_Io'UET_Address,
26991         Ada.Exceptions'UET_Address,
26992         Gnat.Heap_Sort_A'UET_Address,
26993         System.Exception_Table'UET_Address,
26994         System.Machine_State_Operations'UET_Address,
26995         System.Secondary_Stack'UET_Address,
26996         System.Parameters'UET_Address,
26997         System.Soft_Links'UET_Address,
26998         System.Stack_Checking'UET_Address,
26999         System.Traceback'UET_Address,
27000         Ada.Streams'UET_Address,
27001         Ada.Tags'UET_Address,
27002         System.String_Ops'UET_Address,
27003         Interfaces.C_Streams'UET_Address,
27004         System.File_Io'UET_Address,
27005         Ada.Finalization'UET_Address,
27006         System.Finalization_Root'UET_Address,
27007         System.Finalization_Implementation'UET_Address,
27008         System.String_Ops_Concat_3'UET_Address,
27009         System.Stream_Attributes'UET_Address,
27010         System.File_Control_Block'UET_Address,
27011         Ada.Finalization.List_Controller'UET_Address);
27012
27013       --  Table of addresses of elaboration routines. Used for
27014       --  zero cost exception handling to make sure these
27015       --  addresses are included in the top level procedure
27016       --  address table.
27017
27018       EA : aliased constant array (1 .. 23) of System.Address := (
27019         adainit'Code_Address,
27020         Do_Finalize'Code_Address,
27021         Ada.Exceptions'Elab_Spec'Address,
27022         System.Exceptions'Elab_Spec'Address,
27023         Interfaces.C_Streams'Elab_Spec'Address,
27024         System.Exception_Table'Elab_Body'Address,
27025         Ada.Io_Exceptions'Elab_Spec'Address,
27026         System.Stack_Checking'Elab_Spec'Address,
27027         System.Soft_Links'Elab_Body'Address,
27028         System.Secondary_Stack'Elab_Body'Address,
27029         Ada.Tags'Elab_Spec'Address,
27030         Ada.Tags'Elab_Body'Address,
27031         Ada.Streams'Elab_Spec'Address,
27032         System.Finalization_Root'Elab_Spec'Address,
27033         Ada.Exceptions'Elab_Body'Address,
27034         System.Finalization_Implementation'Elab_Spec'Address,
27035         System.Finalization_Implementation'Elab_Body'Address,
27036         Ada.Finalization'Elab_Spec'Address,
27037         Ada.Finalization.List_Controller'Elab_Spec'Address,
27038         System.File_Control_Block'Elab_Spec'Address,
27039         System.File_Io'Elab_Body'Address,
27040         Ada.Text_Io'Elab_Spec'Address,
27041         Ada.Text_Io'Elab_Body'Address);
27042
27043    --  Start of processing for adainit
27044
27045    begin
27046
27047       --  Call SDP_Table_Build to build the top level procedure
27048       --  table for zero cost exception handling (omitted in
27049       --  longjmp/setjmp mode).
27050
27051       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27052
27053       --  Call Set_Globals to record various information for
27054       --  this partition.  The values are derived by the binder
27055       --  from information stored in the ali files by the compiler.
27056
27057 @findex __gnat_set_globals
27058       Set_Globals
27059         (Main_Priority            => -1,
27060          --  Priority of main program, -1 if no pragma Priority used
27061
27062          Time_Slice_Value         => -1,
27063          --  Time slice from Time_Slice pragma, -1 if none used
27064
27065          WC_Encoding              => 'b',
27066          --  Wide_Character encoding used, default is brackets
27067
27068          Locking_Policy           => ' ',
27069          --  Locking_Policy used, default of space means not
27070          --  specified, otherwise it is the first character of
27071          --  the policy name.
27072
27073          Queuing_Policy           => ' ',
27074          --  Queuing_Policy used, default of space means not
27075          --  specified, otherwise it is the first character of
27076          --  the policy name.
27077
27078          Task_Dispatching_Policy  => ' ',
27079          --  Task_Dispatching_Policy used, default of space means
27080          --  not specified, otherwise first character of the
27081          --  policy name.
27082
27083          Adafinal                 => System.Null_Address,
27084          --  Address of Adafinal routine, not used anymore
27085
27086          Unreserve_All_Interrupts => 0,
27087          --  Set true if pragma Unreserve_All_Interrupts was used
27088
27089          Exception_Tracebacks     => 0);
27090          --  Indicates if exception tracebacks are enabled
27091
27092       Elab_Final_Code := 1;
27093
27094       --  Now we have the elaboration calls for all units in the partition.
27095       --  The Elab_Spec and Elab_Body attributes generate references to the
27096       --  implicit elaboration procedures generated by the compiler for
27097       --  each unit that requires elaboration.
27098
27099       if not E040 then
27100          Interfaces.C_Streams'Elab_Spec;
27101       end if;
27102       E040 := True;
27103       if not E008 then
27104          Ada.Exceptions'Elab_Spec;
27105       end if;
27106       if not E014 then
27107          System.Exception_Table'Elab_Body;
27108          E014 := True;
27109       end if;
27110       if not E053 then
27111          Ada.Io_Exceptions'Elab_Spec;
27112          E053 := True;
27113       end if;
27114       if not E017 then
27115          System.Exceptions'Elab_Spec;
27116          E017 := True;
27117       end if;
27118       if not E030 then
27119          System.Stack_Checking'Elab_Spec;
27120       end if;
27121       if not E028 then
27122          System.Soft_Links'Elab_Body;
27123          E028 := True;
27124       end if;
27125       E030 := True;
27126       if not E024 then
27127          System.Secondary_Stack'Elab_Body;
27128          E024 := True;
27129       end if;
27130       if not E035 then
27131          Ada.Tags'Elab_Spec;
27132       end if;
27133       if not E035 then
27134          Ada.Tags'Elab_Body;
27135          E035 := True;
27136       end if;
27137       if not E033 then
27138          Ada.Streams'Elab_Spec;
27139          E033 := True;
27140       end if;
27141       if not E046 then
27142          System.Finalization_Root'Elab_Spec;
27143       end if;
27144       E046 := True;
27145       if not E008 then
27146          Ada.Exceptions'Elab_Body;
27147          E008 := True;
27148       end if;
27149       if not E048 then
27150          System.Finalization_Implementation'Elab_Spec;
27151       end if;
27152       if not E048 then
27153          System.Finalization_Implementation'Elab_Body;
27154          E048 := True;
27155       end if;
27156       if not E044 then
27157          Ada.Finalization'Elab_Spec;
27158       end if;
27159       E044 := True;
27160       if not E057 then
27161          Ada.Finalization.List_Controller'Elab_Spec;
27162       end if;
27163       E057 := True;
27164       if not E055 then
27165          System.File_Control_Block'Elab_Spec;
27166          E055 := True;
27167       end if;
27168       if not E042 then
27169          System.File_Io'Elab_Body;
27170          E042 := True;
27171       end if;
27172       if not E006 then
27173          Ada.Text_Io'Elab_Spec;
27174       end if;
27175       if not E006 then
27176          Ada.Text_Io'Elab_Body;
27177          E006 := True;
27178       end if;
27179
27180       Elab_Final_Code := 0;
27181    end adainit;
27182
27183    --------------
27184    -- adafinal --
27185    --------------
27186
27187 @findex adafinal
27188    procedure adafinal is
27189    begin
27190       Do_Finalize;
27191    end adafinal;
27192
27193    ----------
27194    -- main --
27195    ----------
27196
27197    --  main is actually a function, as in the ANSI C standard,
27198    --  defined to return the exit status. The three parameters
27199    --  are the argument count, argument values and environment
27200    --  pointer.
27201
27202 @findex Main Program
27203    function main
27204      (argc : Integer;
27205       argv : System.Address;
27206       envp : System.Address)
27207       return Integer
27208    is
27209       --  The initialize routine performs low level system
27210       --  initialization using a standard library routine which
27211       --  sets up signal handling and performs any other
27212       --  required setup. The routine can be found in file
27213       --  a-init.c.
27214
27215 @findex __gnat_initialize
27216       procedure initialize;
27217       pragma Import (C, initialize, "__gnat_initialize");
27218
27219       --  The finalize routine performs low level system
27220       --  finalization using a standard library routine. The
27221       --  routine is found in file a-final.c and in the standard
27222       --  distribution is a dummy routine that does nothing, so
27223       --  really this is a hook for special user finalization.
27224
27225 @findex __gnat_finalize
27226       procedure finalize;
27227       pragma Import (C, finalize, "__gnat_finalize");
27228
27229       --  We get to the main program of the partition by using
27230       --  pragma Import because if we try to with the unit and
27231       --  call it Ada style, then not only do we waste time
27232       --  recompiling it, but also, we don't really know the right
27233       --  switches (e.g.@: identifier character set) to be used
27234       --  to compile it.
27235
27236       procedure Ada_Main_Program;
27237       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27238
27239    --  Start of processing for main
27240
27241    begin
27242       --  Save global variables
27243
27244       gnat_argc := argc;
27245       gnat_argv := argv;
27246       gnat_envp := envp;
27247
27248       --  Call low level system initialization
27249
27250       Initialize;
27251
27252       --  Call our generated Ada initialization routine
27253
27254       adainit;
27255
27256       --  This is the point at which we want the debugger to get
27257       --  control
27258
27259       Break_Start;
27260
27261       --  Now we call the main program of the partition
27262
27263       Ada_Main_Program;
27264
27265       --  Perform Ada finalization
27266
27267       adafinal;
27268
27269       --  Perform low level system finalization
27270
27271       Finalize;
27272
27273       --  Return the proper exit status
27274       return (gnat_exit_status);
27275    end;
27276
27277 --  This section is entirely comments, so it has no effect on the
27278 --  compilation of the Ada_Main package. It provides the list of
27279 --  object files and linker options, as well as some standard
27280 --  libraries needed for the link. The gnatlink utility parses
27281 --  this b~hello.adb file to read these comment lines to generate
27282 --  the appropriate command line arguments for the call to the
27283 --  system linker. The BEGIN/END lines are used for sentinels for
27284 --  this parsing operation.
27285
27286 --  The exact file names will of course depend on the environment,
27287 --  host/target and location of files on the host system.
27288
27289 @findex Object file list
27290 -- BEGIN Object file/option list
27291    --   ./hello.o
27292    --   -L./
27293    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27294    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27295 -- END Object file/option list
27296
27297 end ada_main;
27298 @end smallexample
27299
27300 @noindent
27301 The Ada code in the above example is exactly what is generated by the
27302 binder. We have added comments to more clearly indicate the function
27303 of each part of the generated @code{Ada_Main} package.
27304
27305 The code is standard Ada in all respects, and can be processed by any
27306 tools that handle Ada. In particular, it is possible to use the debugger
27307 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27308 suppose that for reasons that you do not understand, your program is crashing
27309 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27310 you can place a breakpoint on the call:
27311
27312 @smallexample @c ada
27313 Ada.Text_Io'Elab_Body;
27314 @end smallexample
27315
27316 @noindent
27317 and trace the elaboration routine for this package to find out where
27318 the problem might be (more usually of course you would be debugging
27319 elaboration code in your own application).
27320
27321 @node Elaboration Order Handling in GNAT
27322 @appendix Elaboration Order Handling in GNAT
27323 @cindex Order of elaboration
27324 @cindex Elaboration control
27325
27326 @menu
27327 * Elaboration Code::
27328 * Checking the Elaboration Order::
27329 * Controlling the Elaboration Order::
27330 * Controlling Elaboration in GNAT - Internal Calls::
27331 * Controlling Elaboration in GNAT - External Calls::
27332 * Default Behavior in GNAT - Ensuring Safety::
27333 * Treatment of Pragma Elaborate::
27334 * Elaboration Issues for Library Tasks::
27335 * Mixing Elaboration Models::
27336 * What to Do If the Default Elaboration Behavior Fails::
27337 * Elaboration for Access-to-Subprogram Values::
27338 * Summary of Procedures for Elaboration Control::
27339 * Other Elaboration Order Considerations::
27340 @end menu
27341
27342 @noindent
27343 This chapter describes the handling of elaboration code in Ada and
27344 in GNAT, and discusses how the order of elaboration of program units can
27345 be controlled in GNAT, either automatically or with explicit programming
27346 features.
27347
27348 @node Elaboration Code
27349 @section Elaboration Code
27350
27351 @noindent
27352 Ada provides rather general mechanisms for executing code at elaboration
27353 time, that is to say before the main program starts executing. Such code arises
27354 in three contexts:
27355
27356 @table @asis
27357 @item Initializers for variables.
27358 Variables declared at the library level, in package specs or bodies, can
27359 require initialization that is performed at elaboration time, as in:
27360 @smallexample @c ada
27361 @cartouche
27362 Sqrt_Half : Float := Sqrt (0.5);
27363 @end cartouche
27364 @end smallexample
27365
27366 @item Package initialization code
27367 Code in a @code{BEGIN-END} section at the outer level of a package body is
27368 executed as part of the package body elaboration code.
27369
27370 @item Library level task allocators
27371 Tasks that are declared using task allocators at the library level
27372 start executing immediately and hence can execute at elaboration time.
27373 @end table
27374
27375 @noindent
27376 Subprogram calls are possible in any of these contexts, which means that
27377 any arbitrary part of the program may be executed as part of the elaboration
27378 code. It is even possible to write a program which does all its work at
27379 elaboration time, with a null main program, although stylistically this
27380 would usually be considered an inappropriate way to structure
27381 a program.
27382
27383 An important concern arises in the context of elaboration code:
27384 we have to be sure that it is executed in an appropriate order. What we
27385 have is a series of elaboration code sections, potentially one section
27386 for each unit in the program. It is important that these execute
27387 in the correct order. Correctness here means that, taking the above
27388 example of the declaration of @code{Sqrt_Half},
27389 if some other piece of
27390 elaboration code references @code{Sqrt_Half},
27391 then it must run after the
27392 section of elaboration code that contains the declaration of
27393 @code{Sqrt_Half}.
27394
27395 There would never be any order of elaboration problem if we made a rule
27396 that whenever you @code{with} a unit, you must elaborate both the spec and body
27397 of that unit before elaborating the unit doing the @code{with}'ing:
27398
27399 @smallexample @c ada
27400 @group
27401 @cartouche
27402 with Unit_1;
27403 package Unit_2 is @dots{}
27404 @end cartouche
27405 @end group
27406 @end smallexample
27407
27408 @noindent
27409 would require that both the body and spec of @code{Unit_1} be elaborated
27410 before the spec of @code{Unit_2}. However, a rule like that would be far too
27411 restrictive. In particular, it would make it impossible to have routines
27412 in separate packages that were mutually recursive.
27413
27414 You might think that a clever enough compiler could look at the actual
27415 elaboration code and determine an appropriate correct order of elaboration,
27416 but in the general case, this is not possible. Consider the following
27417 example.
27418
27419 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27420 that references
27421 the variable @code{Sqrt_1}, which is declared in the elaboration code
27422 of the body of @code{Unit_1}:
27423
27424 @smallexample @c ada
27425 @cartouche
27426 Sqrt_1 : Float := Sqrt (0.1);
27427 @end cartouche
27428 @end smallexample
27429
27430 @noindent
27431 The elaboration code of the body of @code{Unit_1} also contains:
27432
27433 @smallexample @c ada
27434 @group
27435 @cartouche
27436 if expression_1 = 1 then
27437    Q := Unit_2.Func_2;
27438 end if;
27439 @end cartouche
27440 @end group
27441 @end smallexample
27442
27443 @noindent
27444 @code{Unit_2} is exactly parallel,
27445 it has a procedure @code{Func_2} that references
27446 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27447 the body @code{Unit_2}:
27448
27449 @smallexample @c ada
27450 @cartouche
27451 Sqrt_2 : Float := Sqrt (0.1);
27452 @end cartouche
27453 @end smallexample
27454
27455 @noindent
27456 The elaboration code of the body of @code{Unit_2} also contains:
27457
27458 @smallexample @c ada
27459 @group
27460 @cartouche
27461 if expression_2 = 2 then
27462    Q := Unit_1.Func_1;
27463 end if;
27464 @end cartouche
27465 @end group
27466 @end smallexample
27467
27468 @noindent
27469 Now the question is, which of the following orders of elaboration is
27470 acceptable:
27471
27472 @smallexample
27473 @group
27474 Spec of Unit_1
27475 Spec of Unit_2
27476 Body of Unit_1
27477 Body of Unit_2
27478 @end group
27479 @end smallexample
27480
27481 @noindent
27482 or
27483
27484 @smallexample
27485 @group
27486 Spec of Unit_2
27487 Spec of Unit_1
27488 Body of Unit_2
27489 Body of Unit_1
27490 @end group
27491 @end smallexample
27492
27493 @noindent
27494 If you carefully analyze the flow here, you will see that you cannot tell
27495 at compile time the answer to this question.
27496 If @code{expression_1} is not equal to 1,
27497 and @code{expression_2} is not equal to 2,
27498 then either order is acceptable, because neither of the function calls is
27499 executed. If both tests evaluate to true, then neither order is acceptable
27500 and in fact there is no correct order.
27501
27502 If one of the two expressions is true, and the other is false, then one
27503 of the above orders is correct, and the other is incorrect. For example,
27504 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27505 then the call to @code{Func_1}
27506 will occur, but not the call to @code{Func_2.}
27507 This means that it is essential
27508 to elaborate the body of @code{Unit_1} before
27509 the body of @code{Unit_2}, so the first
27510 order of elaboration is correct and the second is wrong.
27511
27512 By making @code{expression_1} and @code{expression_2}
27513 depend on input data, or perhaps
27514 the time of day, we can make it impossible for the compiler or binder
27515 to figure out which of these expressions will be true, and hence it
27516 is impossible to guarantee a safe order of elaboration at run time.
27517
27518 @node Checking the Elaboration Order
27519 @section Checking the Elaboration Order
27520
27521 @noindent
27522 In some languages that involve the same kind of elaboration problems,
27523 e.g.@: Java and C++, the programmer is expected to worry about these
27524 ordering problems himself, and it is common to
27525 write a program in which an incorrect elaboration order  gives
27526 surprising results, because it references variables before they
27527 are initialized.
27528 Ada is designed to be a safe language, and a programmer-beware approach is
27529 clearly not sufficient. Consequently, the language provides three lines
27530 of defense:
27531
27532 @table @asis
27533 @item Standard rules
27534 Some standard rules restrict the possible choice of elaboration
27535 order. In particular, if you @code{with} a unit, then its spec is always
27536 elaborated before the unit doing the @code{with}. Similarly, a parent
27537 spec is always elaborated before the child spec, and finally
27538 a spec is always elaborated before its corresponding body.
27539
27540 @item Dynamic elaboration checks
27541 @cindex Elaboration checks
27542 @cindex Checks, elaboration
27543 Dynamic checks are made at run time, so that if some entity is accessed
27544 before it is elaborated (typically  by means of a subprogram call)
27545 then the exception (@code{Program_Error}) is raised.
27546
27547 @item Elaboration control
27548 Facilities are provided for the programmer to specify the desired order
27549 of elaboration.
27550 @end table
27551
27552 Let's look at these facilities in more detail. First, the rules for
27553 dynamic checking. One possible rule would be simply to say that the
27554 exception is raised if you access a variable which has not yet been
27555 elaborated. The trouble with this approach is that it could require
27556 expensive checks on every variable reference. Instead Ada has two
27557 rules which are a little more restrictive, but easier to check, and
27558 easier to state:
27559
27560 @table @asis
27561 @item Restrictions on calls
27562 A subprogram can only be called at elaboration time if its body
27563 has been elaborated. The rules for elaboration given above guarantee
27564 that the spec of the subprogram has been elaborated before the
27565 call, but not the body. If this rule is violated, then the
27566 exception @code{Program_Error} is raised.
27567
27568 @item Restrictions on instantiations
27569 A generic unit can only be instantiated if the body of the generic
27570 unit has been elaborated. Again, the rules for elaboration given above
27571 guarantee that the spec of the generic unit has been elaborated
27572 before the instantiation, but not the body. If this rule is
27573 violated, then the exception @code{Program_Error} is raised.
27574 @end table
27575
27576 @noindent
27577 The idea is that if the body has been elaborated, then any variables
27578 it references must have been elaborated; by checking for the body being
27579 elaborated we guarantee that none of its references causes any
27580 trouble. As we noted above, this is a little too restrictive, because a
27581 subprogram that has no non-local references in its body may in fact be safe
27582 to call. However, it really would be unsafe to rely on this, because
27583 it would mean that the caller was aware of details of the implementation
27584 in the body. This goes against the basic tenets of Ada.
27585
27586 A plausible implementation can be described as follows.
27587 A Boolean variable is associated with each subprogram
27588 and each generic unit. This variable is initialized to False, and is set to
27589 True at the point body is elaborated. Every call or instantiation checks the
27590 variable, and raises @code{Program_Error} if the variable is False.
27591
27592 Note that one might think that it would be good enough to have one Boolean
27593 variable for each package, but that would not deal with cases of trying
27594 to call a body in the same package as the call
27595 that has not been elaborated yet.
27596 Of course a compiler may be able to do enough analysis to optimize away
27597 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27598 does such optimizations, but still the easiest conceptual model is to
27599 think of there being one variable per subprogram.
27600
27601 @node Controlling the Elaboration Order
27602 @section Controlling the Elaboration Order
27603
27604 @noindent
27605 In the previous section we discussed the rules in Ada which ensure
27606 that @code{Program_Error} is raised if an incorrect elaboration order is
27607 chosen. This prevents erroneous executions, but we need mechanisms to
27608 specify a correct execution and avoid the exception altogether.
27609 To achieve this, Ada provides a number of features for controlling
27610 the order of elaboration. We discuss these features in this section.
27611
27612 First, there are several ways of indicating to the compiler that a given
27613 unit has no elaboration problems:
27614
27615 @table @asis
27616 @item packages that do not require a body
27617 A library package that does not require a body does not permit
27618 a body (this rule was introduced in Ada 95).
27619 Thus if we have a such a package, as in:
27620
27621 @smallexample @c ada
27622 @group
27623 @cartouche
27624 package Definitions is
27625    generic
27626       type m is new integer;
27627    package Subp is
27628       type a is array (1 .. 10) of m;
27629       type b is array (1 .. 20) of m;
27630    end Subp;
27631 end Definitions;
27632 @end cartouche
27633 @end group
27634 @end smallexample
27635
27636 @noindent
27637 A package that @code{with}'s @code{Definitions} may safely instantiate
27638 @code{Definitions.Subp} because the compiler can determine that there
27639 definitely is no package body to worry about in this case
27640
27641 @item pragma Pure
27642 @cindex pragma Pure
27643 @findex Pure
27644 Places sufficient restrictions on a unit to guarantee that
27645 no call to any subprogram in the unit can result in an
27646 elaboration problem. This means that the compiler does not need
27647 to worry about the point of elaboration of such units, and in
27648 particular, does not need to check any calls to any subprograms
27649 in this unit.
27650
27651 @item pragma Preelaborate
27652 @findex Preelaborate
27653 @cindex pragma Preelaborate
27654 This pragma places slightly less stringent restrictions on a unit than
27655 does pragma Pure,
27656 but these restrictions are still sufficient to ensure that there
27657 are no elaboration problems with any calls to the unit.
27658
27659 @item pragma Elaborate_Body
27660 @findex Elaborate_Body
27661 @cindex pragma Elaborate_Body
27662 This pragma requires that the body of a unit be elaborated immediately
27663 after its spec. Suppose a unit @code{A} has such a pragma,
27664 and unit @code{B} does
27665 a @code{with} of unit @code{A}. Recall that the standard rules require
27666 the spec of unit @code{A}
27667 to be elaborated before the @code{with}'ing unit; given the pragma in
27668 @code{A}, we also know that the body of @code{A}
27669 will be elaborated before @code{B}, so
27670 that calls to @code{A} are safe and do not need a check.
27671 @end table
27672
27673 @noindent
27674 Note that,
27675 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27676 the use of
27677 @code{Elaborate_Body} does not guarantee that the program is
27678 free of elaboration problems, because it may not be possible
27679 to satisfy the requested elaboration order.
27680 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27681 If a programmer
27682 marks @code{Unit_1} as @code{Elaborate_Body},
27683 and not @code{Unit_2,} then the order of
27684 elaboration will be:
27685
27686 @smallexample
27687 @group
27688 Spec of Unit_2
27689 Spec of Unit_1
27690 Body of Unit_1
27691 Body of Unit_2
27692 @end group
27693 @end smallexample
27694
27695 @noindent
27696 Now that means that the call to @code{Func_1} in @code{Unit_2}
27697 need not be checked,
27698 it must be safe. But the call to @code{Func_2} in
27699 @code{Unit_1} may still fail if
27700 @code{Expression_1} is equal to 1,
27701 and the programmer must still take
27702 responsibility for this not being the case.
27703
27704 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27705 eliminated, except for calls entirely within a body, which are
27706 in any case fully under programmer control. However, using the pragma
27707 everywhere is not always possible.
27708 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27709 we marked both of them as having pragma @code{Elaborate_Body}, then
27710 clearly there would be no possible elaboration order.
27711
27712 The above pragmas allow a server to guarantee safe use by clients, and
27713 clearly this is the preferable approach. Consequently a good rule
27714 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27715 and if this is not possible,
27716 mark them as @code{Elaborate_Body} if possible.
27717 As we have seen, there are situations where neither of these
27718 three pragmas can be used.
27719 So we also provide methods for clients to control the
27720 order of elaboration of the servers on which they depend:
27721
27722 @table @asis
27723 @item pragma Elaborate (unit)
27724 @findex Elaborate
27725 @cindex pragma Elaborate
27726 This pragma is placed in the context clause, after a @code{with} clause,
27727 and it requires that the body of the named unit be elaborated before
27728 the unit in which the pragma occurs. The idea is to use this pragma
27729 if the current unit calls at elaboration time, directly or indirectly,
27730 some subprogram in the named unit.
27731
27732 @item pragma Elaborate_All (unit)
27733 @findex Elaborate_All
27734 @cindex pragma Elaborate_All
27735 This is a stronger version of the Elaborate pragma. Consider the
27736 following example:
27737
27738 @smallexample
27739 Unit A @code{with}'s unit B and calls B.Func in elab code
27740 Unit B @code{with}'s unit C, and B.Func calls C.Func
27741 @end smallexample
27742
27743 @noindent
27744 Now if we put a pragma @code{Elaborate (B)}
27745 in unit @code{A}, this ensures that the
27746 body of @code{B} is elaborated before the call, but not the
27747 body of @code{C}, so
27748 the call to @code{C.Func} could still cause @code{Program_Error} to
27749 be raised.
27750
27751 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27752 not only that the body of the named unit be elaborated before the
27753 unit doing the @code{with}, but also the bodies of all units that the
27754 named unit uses, following @code{with} links transitively. For example,
27755 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27756 then it requires
27757 not only that the body of @code{B} be elaborated before @code{A},
27758 but also the
27759 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27760 @end table
27761
27762 @noindent
27763 We are now in a position to give a usage rule in Ada for avoiding
27764 elaboration problems, at least if dynamic dispatching and access to
27765 subprogram values are not used. We will handle these cases separately
27766 later.
27767
27768 The rule is simple. If a unit has elaboration code that can directly or
27769 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27770 a generic package in a @code{with}'ed unit,
27771 then if the @code{with}'ed unit does not have
27772 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27773 a pragma @code{Elaborate_All}
27774 for the @code{with}'ed unit. By following this rule a client is
27775 assured that calls can be made without risk of an exception.
27776
27777 For generic subprogram instantiations, the rule can be relaxed to
27778 require only a pragma @code{Elaborate} since elaborating the body
27779 of a subprogram cannot cause any transitive elaboration (we are
27780 not calling the subprogram in this case, just elaborating its
27781 declaration).
27782
27783 If this rule is not followed, then a program may be in one of four
27784 states:
27785
27786 @table @asis
27787 @item No order exists
27788 No order of elaboration exists which follows the rules, taking into
27789 account any @code{Elaborate}, @code{Elaborate_All},
27790 or @code{Elaborate_Body} pragmas. In
27791 this case, an Ada compiler must diagnose the situation at bind
27792 time, and refuse to build an executable program.
27793
27794 @item One or more orders exist, all incorrect
27795 One or more acceptable elaboration orders exist, and all of them
27796 generate an elaboration order problem. In this case, the binder
27797 can build an executable program, but @code{Program_Error} will be raised
27798 when the program is run.
27799
27800 @item Several orders exist, some right, some incorrect
27801 One or more acceptable elaboration orders exists, and some of them
27802 work, and some do not. The programmer has not controlled
27803 the order of elaboration, so the binder may or may not pick one of
27804 the correct orders, and the program may or may not raise an
27805 exception when it is run. This is the worst case, because it means
27806 that the program may fail when moved to another compiler, or even
27807 another version of the same compiler.
27808
27809 @item One or more orders exists, all correct
27810 One ore more acceptable elaboration orders exist, and all of them
27811 work. In this case the program runs successfully. This state of
27812 affairs can be guaranteed by following the rule we gave above, but
27813 may be true even if the rule is not followed.
27814 @end table
27815
27816 @noindent
27817 Note that one additional advantage of following our rules on the use
27818 of @code{Elaborate} and @code{Elaborate_All}
27819 is that the program continues to stay in the ideal (all orders OK) state
27820 even if maintenance
27821 changes some bodies of some units. Conversely, if a program that does
27822 not follow this rule happens to be safe at some point, this state of affairs
27823 may deteriorate silently as a result of maintenance changes.
27824
27825 You may have noticed that the above discussion did not mention
27826 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27827 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27828 code in the body makes calls to some other unit, so it is still necessary
27829 to use @code{Elaborate_All} on such units.
27830
27831 @node Controlling Elaboration in GNAT - Internal Calls
27832 @section Controlling Elaboration in GNAT - Internal Calls
27833
27834 @noindent
27835 In the case of internal calls, i.e., calls within a single package, the
27836 programmer has full control over the order of elaboration, and it is up
27837 to the programmer to elaborate declarations in an appropriate order. For
27838 example writing:
27839
27840 @smallexample @c ada
27841 @group
27842 @cartouche
27843 function One return Float;
27844
27845 Q : Float := One;
27846
27847 function One return Float is
27848 begin
27849      return 1.0;
27850 end One;
27851 @end cartouche
27852 @end group
27853 @end smallexample
27854
27855 @noindent
27856 will obviously raise @code{Program_Error} at run time, because function
27857 One will be called before its body is elaborated. In this case GNAT will
27858 generate a warning that the call will raise @code{Program_Error}:
27859
27860 @smallexample
27861 @group
27862 @cartouche
27863  1. procedure y is
27864  2.    function One return Float;
27865  3.
27866  4.    Q : Float := One;
27867                     |
27868     >>> warning: cannot call "One" before body is elaborated
27869     >>> warning: Program_Error will be raised at run time
27870
27871  5.
27872  6.    function One return Float is
27873  7.    begin
27874  8.         return 1.0;
27875  9.    end One;
27876 10.
27877 11. begin
27878 12.    null;
27879 13. end;
27880 @end cartouche
27881 @end group
27882 @end smallexample
27883
27884 @noindent
27885 Note that in this particular case, it is likely that the call is safe, because
27886 the function @code{One} does not access any global variables.
27887 Nevertheless in Ada, we do not want the validity of the check to depend on
27888 the contents of the body (think about the separate compilation case), so this
27889 is still wrong, as we discussed in the previous sections.
27890
27891 The error is easily corrected by rearranging the declarations so that the
27892 body of @code{One} appears before the declaration containing the call
27893 (note that in Ada 95 and Ada 2005,
27894 declarations can appear in any order, so there is no restriction that
27895 would prevent this reordering, and if we write:
27896
27897 @smallexample @c ada
27898 @group
27899 @cartouche
27900 function One return Float;
27901
27902 function One return Float is
27903 begin
27904      return 1.0;
27905 end One;
27906
27907 Q : Float := One;
27908 @end cartouche
27909 @end group
27910 @end smallexample
27911
27912 @noindent
27913 then all is well, no warning is generated, and no
27914 @code{Program_Error} exception
27915 will be raised.
27916 Things are more complicated when a chain of subprograms is executed:
27917
27918 @smallexample @c ada
27919 @group
27920 @cartouche
27921 function A return Integer;
27922 function B return Integer;
27923 function C return Integer;
27924
27925 function B return Integer is begin return A; end;
27926 function C return Integer is begin return B; end;
27927
27928 X : Integer := C;
27929
27930 function A return Integer is begin return 1; end;
27931 @end cartouche
27932 @end group
27933 @end smallexample
27934
27935 @noindent
27936 Now the call to @code{C}
27937 at elaboration time in the declaration of @code{X} is correct, because
27938 the body of @code{C} is already elaborated,
27939 and the call to @code{B} within the body of
27940 @code{C} is correct, but the call
27941 to @code{A} within the body of @code{B} is incorrect, because the body
27942 of @code{A} has not been elaborated, so @code{Program_Error}
27943 will be raised on the call to @code{A}.
27944 In this case GNAT will generate a
27945 warning that @code{Program_Error} may be
27946 raised at the point of the call. Let's look at the warning:
27947
27948 @smallexample
27949 @group
27950 @cartouche
27951  1. procedure x is
27952  2.    function A return Integer;
27953  3.    function B return Integer;
27954  4.    function C return Integer;
27955  5.
27956  6.    function B return Integer is begin return A; end;
27957                                                     |
27958     >>> warning: call to "A" before body is elaborated may
27959                  raise Program_Error
27960     >>> warning: "B" called at line 7
27961     >>> warning: "C" called at line 9
27962
27963  7.    function C return Integer is begin return B; end;
27964  8.
27965  9.    X : Integer := C;
27966 10.
27967 11.    function A return Integer is begin return 1; end;
27968 12.
27969 13. begin
27970 14.    null;
27971 15. end;
27972 @end cartouche
27973 @end group
27974 @end smallexample
27975
27976 @noindent
27977 Note that the message here says ``may raise'', instead of the direct case,
27978 where the message says ``will be raised''. That's because whether
27979 @code{A} is
27980 actually called depends in general on run-time flow of control.
27981 For example, if the body of @code{B} said
27982
27983 @smallexample @c ada
27984 @group
27985 @cartouche
27986 function B return Integer is
27987 begin
27988    if some-condition-depending-on-input-data then
27989       return A;
27990    else
27991       return 1;
27992    end if;
27993 end B;
27994 @end cartouche
27995 @end group
27996 @end smallexample
27997
27998 @noindent
27999 then we could not know until run time whether the incorrect call to A would
28000 actually occur, so @code{Program_Error} might
28001 or might not be raised. It is possible for a compiler to
28002 do a better job of analyzing bodies, to
28003 determine whether or not @code{Program_Error}
28004 might be raised, but it certainly
28005 couldn't do a perfect job (that would require solving the halting problem
28006 and is provably impossible), and because this is a warning anyway, it does
28007 not seem worth the effort to do the analysis. Cases in which it
28008 would be relevant are rare.
28009
28010 In practice, warnings of either of the forms given
28011 above will usually correspond to
28012 real errors, and should be examined carefully and eliminated.
28013 In the rare case where a warning is bogus, it can be suppressed by any of
28014 the following methods:
28015
28016 @itemize @bullet
28017 @item
28018 Compile with the @option{-gnatws} switch set
28019
28020 @item
28021 Suppress @code{Elaboration_Check} for the called subprogram
28022
28023 @item
28024 Use pragma @code{Warnings_Off} to turn warnings off for the call
28025 @end itemize
28026
28027 @noindent
28028 For the internal elaboration check case,
28029 GNAT by default generates the
28030 necessary run-time checks to ensure
28031 that @code{Program_Error} is raised if any
28032 call fails an elaboration check. Of course this can only happen if a
28033 warning has been issued as described above. The use of pragma
28034 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28035 some of these checks, meaning that it may be possible (but is not
28036 guaranteed) for a program to be able to call a subprogram whose body
28037 is not yet elaborated, without raising a @code{Program_Error} exception.
28038
28039 @node Controlling Elaboration in GNAT - External Calls
28040 @section Controlling Elaboration in GNAT - External Calls
28041
28042 @noindent
28043 The previous section discussed the case in which the execution of a
28044 particular thread of elaboration code occurred entirely within a
28045 single unit. This is the easy case to handle, because a programmer
28046 has direct and total control over the order of elaboration, and
28047 furthermore, checks need only be generated in cases which are rare
28048 and which the compiler can easily detect.
28049 The situation is more complex when separate compilation is taken into account.
28050 Consider the following:
28051
28052 @smallexample @c ada
28053 @cartouche
28054 @group
28055 package Math is
28056    function Sqrt (Arg : Float) return Float;
28057 end Math;
28058
28059 package body Math is
28060    function Sqrt (Arg : Float) return Float is
28061    begin
28062          @dots{}
28063    end Sqrt;
28064 end Math;
28065 @end group
28066 @group
28067 with Math;
28068 package Stuff is
28069    X : Float := Math.Sqrt (0.5);
28070 end Stuff;
28071
28072 with Stuff;
28073 procedure Main is
28074 begin
28075    @dots{}
28076 end Main;
28077 @end group
28078 @end cartouche
28079 @end smallexample
28080
28081 @noindent
28082 where @code{Main} is the main program. When this program is executed, the
28083 elaboration code must first be executed, and one of the jobs of the
28084 binder is to determine the order in which the units of a program are
28085 to be elaborated. In this case we have four units: the spec and body
28086 of @code{Math},
28087 the spec of @code{Stuff} and the body of @code{Main}).
28088 In what order should the four separate sections of elaboration code
28089 be executed?
28090
28091 There are some restrictions in the order of elaboration that the binder
28092 can choose. In particular, if unit U has a @code{with}
28093 for a package @code{X}, then you
28094 are assured that the spec of @code{X}
28095 is elaborated before U , but you are
28096 not assured that the body of @code{X}
28097 is elaborated before U.
28098 This means that in the above case, the binder is allowed to choose the
28099 order:
28100
28101 @smallexample
28102 spec of Math
28103 spec of Stuff
28104 body of Math
28105 body of Main
28106 @end smallexample
28107
28108 @noindent
28109 but that's not good, because now the call to @code{Math.Sqrt}
28110 that happens during
28111 the elaboration of the @code{Stuff}
28112 spec happens before the body of @code{Math.Sqrt} is
28113 elaborated, and hence causes @code{Program_Error} exception to be raised.
28114 At first glance, one might say that the binder is misbehaving, because
28115 obviously you want to elaborate the body of something you @code{with}
28116 first, but
28117 that is not a general rule that can be followed in all cases. Consider
28118
28119 @smallexample @c ada
28120 @group
28121 @cartouche
28122 package X is @dots{}
28123
28124 package Y is @dots{}
28125
28126 with X;
28127 package body Y is @dots{}
28128
28129 with Y;
28130 package body X is @dots{}
28131 @end cartouche
28132 @end group
28133 @end smallexample
28134
28135 @noindent
28136 This is a common arrangement, and, apart from the order of elaboration
28137 problems that might arise in connection with elaboration code, this works fine.
28138 A rule that says that you must first elaborate the body of anything you
28139 @code{with} cannot work in this case:
28140 the body of @code{X} @code{with}'s @code{Y},
28141 which means you would have to
28142 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28143 which means
28144 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28145 loop that cannot be broken.
28146
28147 It is true that the binder can in many cases guess an order of elaboration
28148 that is unlikely to cause a @code{Program_Error}
28149 exception to be raised, and it tries to do so (in the
28150 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28151 by default
28152 elaborate the body of @code{Math} right after its spec, so all will be well).
28153
28154 However, a program that blindly relies on the binder to be helpful can
28155 get into trouble, as we discussed in the previous sections, so
28156 GNAT
28157 provides a number of facilities for assisting the programmer in
28158 developing programs that are robust with respect to elaboration order.
28159
28160 @node Default Behavior in GNAT - Ensuring Safety
28161 @section Default Behavior in GNAT - Ensuring Safety
28162
28163 @noindent
28164 The default behavior in GNAT ensures elaboration safety. In its
28165 default mode GNAT implements the
28166 rule we previously described as the right approach. Let's restate it:
28167
28168 @itemize
28169 @item
28170 @emph{If a unit has elaboration code that can directly or indirectly make a
28171 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28172 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28173 does not have pragma @code{Pure} or
28174 @code{Preelaborate}, then the client should have an
28175 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28176
28177 @emph{In the case of instantiating a generic subprogram, it is always
28178 sufficient to have only an @code{Elaborate} pragma for the
28179 @code{with}'ed unit.}
28180 @end itemize
28181
28182 @noindent
28183 By following this rule a client is assured that calls and instantiations
28184 can be made without risk of an exception.
28185
28186 In this mode GNAT traces all calls that are potentially made from
28187 elaboration code, and puts in any missing implicit @code{Elaborate}
28188 and @code{Elaborate_All} pragmas.
28189 The advantage of this approach is that no elaboration problems
28190 are possible if the binder can find an elaboration order that is
28191 consistent with these implicit @code{Elaborate} and
28192 @code{Elaborate_All} pragmas. The
28193 disadvantage of this approach is that no such order may exist.
28194
28195 If the binder does not generate any diagnostics, then it means that it has
28196 found an elaboration order that is guaranteed to be safe. However, the binder
28197 may still be relying on implicitly generated @code{Elaborate} and
28198 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28199 guaranteed.
28200
28201 If it is important to guarantee portability, then the compilations should
28202 use the
28203 @option{-gnatwl}
28204 (warn on elaboration problems) switch. This will cause warning messages
28205 to be generated indicating the missing @code{Elaborate} and
28206 @code{Elaborate_All} pragmas.
28207 Consider the following source program:
28208
28209 @smallexample @c ada
28210 @group
28211 @cartouche
28212 with k;
28213 package j is
28214   m : integer := k.r;
28215 end;
28216 @end cartouche
28217 @end group
28218 @end smallexample
28219
28220 @noindent
28221 where it is clear that there
28222 should be a pragma @code{Elaborate_All}
28223 for unit @code{k}. An implicit pragma will be generated, and it is
28224 likely that the binder will be able to honor it. However, if you want
28225 to port this program to some other Ada compiler than GNAT.
28226 it is safer to include the pragma explicitly in the source. If this
28227 unit is compiled with the
28228 @option{-gnatwl}
28229 switch, then the compiler outputs a warning:
28230
28231 @smallexample
28232 @group
28233 @cartouche
28234 1. with k;
28235 2. package j is
28236 3.   m : integer := k.r;
28237                      |
28238    >>> warning: call to "r" may raise Program_Error
28239    >>> warning: missing pragma Elaborate_All for "k"
28240
28241 4. end;
28242 @end cartouche
28243 @end group
28244 @end smallexample
28245
28246 @noindent
28247 and these warnings can be used as a guide for supplying manually
28248 the missing pragmas. It is usually a bad idea to use this warning
28249 option during development. That's because it will warn you when
28250 you need to put in a pragma, but cannot warn you when it is time
28251 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28252 unnecessary dependencies and even false circularities.
28253
28254 This default mode is more restrictive than the Ada Reference
28255 Manual, and it is possible to construct programs which will compile
28256 using the dynamic model described there, but will run into a
28257 circularity using the safer static model we have described.
28258
28259 Of course any Ada compiler must be able to operate in a mode
28260 consistent with the requirements of the Ada Reference Manual,
28261 and in particular must have the capability of implementing the
28262 standard dynamic model of elaboration with run-time checks.
28263
28264 In GNAT, this standard mode can be achieved either by the use of
28265 the @option{-gnatE} switch on the compiler (@command{gcc} or
28266 @command{gnatmake}) command, or by the use of the configuration pragma:
28267
28268 @smallexample @c ada
28269 pragma Elaboration_Checks (RM);
28270 @end smallexample
28271
28272 @noindent
28273 Either approach will cause the unit affected to be compiled using the
28274 standard dynamic run-time elaboration checks described in the Ada
28275 Reference Manual. The static model is generally preferable, since it
28276 is clearly safer to rely on compile and link time checks rather than
28277 run-time checks. However, in the case of legacy code, it may be
28278 difficult to meet the requirements of the static model. This
28279 issue is further discussed in
28280 @ref{What to Do If the Default Elaboration Behavior Fails}.
28281
28282 Note that the static model provides a strict subset of the allowed
28283 behavior and programs of the Ada Reference Manual, so if you do
28284 adhere to the static model and no circularities exist,
28285 then you are assured that your program will
28286 work using the dynamic model, providing that you remove any
28287 pragma Elaborate statements from the source.
28288
28289 @node Treatment of Pragma Elaborate
28290 @section Treatment of Pragma Elaborate
28291 @cindex Pragma Elaborate
28292
28293 @noindent
28294 The use of @code{pragma Elaborate}
28295 should generally be avoided in Ada 95 and Ada 2005 programs,
28296 since there is no guarantee that transitive calls
28297 will be properly handled. Indeed at one point, this pragma was placed
28298 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28299
28300 Now that's a bit restrictive. In practice, the case in which
28301 @code{pragma Elaborate} is useful is when the caller knows that there
28302 are no transitive calls, or that the called unit contains all necessary
28303 transitive @code{pragma Elaborate} statements, and legacy code often
28304 contains such uses.
28305
28306 Strictly speaking the static mode in GNAT should ignore such pragmas,
28307 since there is no assurance at compile time that the necessary safety
28308 conditions are met. In practice, this would cause GNAT to be incompatible
28309 with correctly written Ada 83 code that had all necessary
28310 @code{pragma Elaborate} statements in place. Consequently, we made the
28311 decision that GNAT in its default mode will believe that if it encounters
28312 a @code{pragma Elaborate} then the programmer knows what they are doing,
28313 and it will trust that no elaboration errors can occur.
28314
28315 The result of this decision is two-fold. First to be safe using the
28316 static mode, you should remove all @code{pragma Elaborate} statements.
28317 Second, when fixing circularities in existing code, you can selectively
28318 use @code{pragma Elaborate} statements to convince the static mode of
28319 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28320 statement.
28321
28322 When using the static mode with @option{-gnatwl}, any use of
28323 @code{pragma Elaborate} will generate a warning about possible
28324 problems.
28325
28326 @node Elaboration Issues for Library Tasks
28327 @section Elaboration Issues for Library Tasks
28328 @cindex Library tasks, elaboration issues
28329 @cindex Elaboration of library tasks
28330
28331 @noindent
28332 In this section we examine special elaboration issues that arise for
28333 programs that declare library level tasks.
28334
28335 Generally the model of execution of an Ada program is that all units are
28336 elaborated, and then execution of the program starts. However, the
28337 declaration of library tasks definitely does not fit this model. The
28338 reason for this is that library tasks start as soon as they are declared
28339 (more precisely, as soon as the statement part of the enclosing package
28340 body is reached), that is to say before elaboration
28341 of the program is complete. This means that if such a task calls a
28342 subprogram, or an entry in another task, the callee may or may not be
28343 elaborated yet, and in the standard
28344 Reference Manual model of dynamic elaboration checks, you can even
28345 get timing dependent Program_Error exceptions, since there can be
28346 a race between the elaboration code and the task code.
28347
28348 The static model of elaboration in GNAT seeks to avoid all such
28349 dynamic behavior, by being conservative, and the conservative
28350 approach in this particular case is to assume that all the code
28351 in a task body is potentially executed at elaboration time if
28352 a task is declared at the library level.
28353
28354 This can definitely result in unexpected circularities. Consider
28355 the following example
28356
28357 @smallexample @c ada
28358 package Decls is
28359   task Lib_Task is
28360      entry Start;
28361   end Lib_Task;
28362
28363   type My_Int is new Integer;
28364
28365   function Ident (M : My_Int) return My_Int;
28366 end Decls;
28367
28368 with Utils;
28369 package body Decls is
28370   task body Lib_Task is
28371   begin
28372      accept Start;
28373      Utils.Put_Val (2);
28374   end Lib_Task;
28375
28376   function Ident (M : My_Int) return My_Int is
28377   begin
28378      return M;
28379   end Ident;
28380 end Decls;
28381
28382 with Decls;
28383 package Utils is
28384   procedure Put_Val (Arg : Decls.My_Int);
28385 end Utils;
28386
28387 with Text_IO;
28388 package body Utils is
28389   procedure Put_Val (Arg : Decls.My_Int) is
28390   begin
28391      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28392   end Put_Val;
28393 end Utils;
28394
28395 with Decls;
28396 procedure Main is
28397 begin
28398    Decls.Lib_Task.Start;
28399 end;
28400 @end smallexample
28401
28402 @noindent
28403 If the above example is compiled in the default static elaboration
28404 mode, then a circularity occurs. The circularity comes from the call
28405 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28406 this call occurs in elaboration code, we need an implicit pragma
28407 @code{Elaborate_All} for @code{Utils}. This means that not only must
28408 the spec and body of @code{Utils} be elaborated before the body
28409 of @code{Decls}, but also the spec and body of any unit that is
28410 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28411 the body of @code{Decls}. This is the transitive implication of
28412 pragma @code{Elaborate_All} and it makes sense, because in general
28413 the body of @code{Put_Val} might have a call to something in a
28414 @code{with'ed} unit.
28415
28416 In this case, the body of Utils (actually its spec) @code{with's}
28417 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28418 must be elaborated before itself, in case there is a call from the
28419 body of @code{Utils}.
28420
28421 Here is the exact chain of events we are worrying about:
28422
28423 @enumerate
28424 @item
28425 In the body of @code{Decls} a call is made from within the body of a library
28426 task to a subprogram in the package @code{Utils}. Since this call may
28427 occur at elaboration time (given that the task is activated at elaboration
28428 time), we have to assume the worst, i.e., that the
28429 call does happen at elaboration time.
28430
28431 @item
28432 This means that the body and spec of @code{Util} must be elaborated before
28433 the body of @code{Decls} so that this call does not cause an access before
28434 elaboration.
28435
28436 @item
28437 Within the body of @code{Util}, specifically within the body of
28438 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28439 by this package.
28440
28441 @item
28442 One such @code{with}'ed package is package @code{Decls}, so there
28443 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28444 In fact there is such a call in this example, but we would have to
28445 assume that there was such a call even if it were not there, since
28446 we are not supposed to write the body of @code{Decls} knowing what
28447 is in the body of @code{Utils}; certainly in the case of the
28448 static elaboration model, the compiler does not know what is in
28449 other bodies and must assume the worst.
28450
28451 @item
28452 This means that the spec and body of @code{Decls} must also be
28453 elaborated before we elaborate the unit containing the call, but
28454 that unit is @code{Decls}! This means that the body of @code{Decls}
28455 must be elaborated before itself, and that's a circularity.
28456 @end enumerate
28457
28458 @noindent
28459 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28460 the body of @code{Decls} you will get a true Ada Reference Manual
28461 circularity that makes the program illegal.
28462
28463 In practice, we have found that problems with the static model of
28464 elaboration in existing code often arise from library tasks, so
28465 we must address this particular situation.
28466
28467 Note that if we compile and run the program above, using the dynamic model of
28468 elaboration (that is to say use the @option{-gnatE} switch),
28469 then it compiles, binds,
28470 links, and runs, printing the expected result of 2. Therefore in some sense
28471 the circularity here is only apparent, and we need to capture
28472 the properties of this program that  distinguish it from other library-level
28473 tasks that have real elaboration problems.
28474
28475 We have four possible answers to this question:
28476
28477 @itemize @bullet
28478
28479 @item
28480 Use the dynamic model of elaboration.
28481
28482 If we use the @option{-gnatE} switch, then as noted above, the program works.
28483 Why is this? If we examine the task body, it is apparent that the task cannot
28484 proceed past the
28485 @code{accept} statement until after elaboration has been completed, because
28486 the corresponding entry call comes from the main program, not earlier.
28487 This is why the dynamic model works here. But that's really giving
28488 up on a precise analysis, and we prefer to take this approach only if we cannot
28489 solve the
28490 problem in any other manner. So let us examine two ways to reorganize
28491 the program to avoid the potential elaboration problem.
28492
28493 @item
28494 Split library tasks into separate packages.
28495
28496 Write separate packages, so that library tasks are isolated from
28497 other declarations as much as possible. Let us look at a variation on
28498 the above program.
28499
28500 @smallexample @c ada
28501 package Decls1 is
28502   task Lib_Task is
28503      entry Start;
28504   end Lib_Task;
28505 end Decls1;
28506
28507 with Utils;
28508 package body Decls1 is
28509   task body Lib_Task is
28510   begin
28511      accept Start;
28512      Utils.Put_Val (2);
28513   end Lib_Task;
28514 end Decls1;
28515
28516 package Decls2 is
28517   type My_Int is new Integer;
28518   function Ident (M : My_Int) return My_Int;
28519 end Decls2;
28520
28521 with Utils;
28522 package body Decls2 is
28523   function Ident (M : My_Int) return My_Int is
28524   begin
28525      return M;
28526   end Ident;
28527 end Decls2;
28528
28529 with Decls2;
28530 package Utils is
28531   procedure Put_Val (Arg : Decls2.My_Int);
28532 end Utils;
28533
28534 with Text_IO;
28535 package body Utils is
28536   procedure Put_Val (Arg : Decls2.My_Int) is
28537   begin
28538      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28539   end Put_Val;
28540 end Utils;
28541
28542 with Decls1;
28543 procedure Main is
28544 begin
28545    Decls1.Lib_Task.Start;
28546 end;
28547 @end smallexample
28548
28549 @noindent
28550 All we have done is to split @code{Decls} into two packages, one
28551 containing the library task, and one containing everything else. Now
28552 there is no cycle, and the program compiles, binds, links and executes
28553 using the default static model of elaboration.
28554
28555 @item
28556 Declare separate task types.
28557
28558 A significant part of the problem arises because of the use of the
28559 single task declaration form. This means that the elaboration of
28560 the task type, and the elaboration of the task itself (i.e.@: the
28561 creation of the task) happen at the same time. A good rule
28562 of style in Ada is to always create explicit task types. By
28563 following the additional step of placing task objects in separate
28564 packages from the task type declaration, many elaboration problems
28565 are avoided. Here is another modified example of the example program:
28566
28567 @smallexample @c ada
28568 package Decls is
28569   task type Lib_Task_Type is
28570      entry Start;
28571   end Lib_Task_Type;
28572
28573   type My_Int is new Integer;
28574
28575   function Ident (M : My_Int) return My_Int;
28576 end Decls;
28577
28578 with Utils;
28579 package body Decls is
28580   task body Lib_Task_Type is
28581   begin
28582      accept Start;
28583      Utils.Put_Val (2);
28584   end Lib_Task_Type;
28585
28586   function Ident (M : My_Int) return My_Int is
28587   begin
28588      return M;
28589   end Ident;
28590 end Decls;
28591
28592 with Decls;
28593 package Utils is
28594   procedure Put_Val (Arg : Decls.My_Int);
28595 end Utils;
28596
28597 with Text_IO;
28598 package body Utils is
28599   procedure Put_Val (Arg : Decls.My_Int) is
28600   begin
28601      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28602   end Put_Val;
28603 end Utils;
28604
28605 with Decls;
28606 package Declst is
28607    Lib_Task : Decls.Lib_Task_Type;
28608 end Declst;
28609
28610 with Declst;
28611 procedure Main is
28612 begin
28613    Declst.Lib_Task.Start;
28614 end;
28615 @end smallexample
28616
28617 @noindent
28618 What we have done here is to replace the @code{task} declaration in
28619 package @code{Decls} with a @code{task type} declaration. Then we
28620 introduce a separate package @code{Declst} to contain the actual
28621 task object. This separates the elaboration issues for
28622 the @code{task type}
28623 declaration, which causes no trouble, from the elaboration issues
28624 of the task object, which is also unproblematic, since it is now independent
28625 of the elaboration of  @code{Utils}.
28626 This separation of concerns also corresponds to
28627 a generally sound engineering principle of separating declarations
28628 from instances. This version of the program also compiles, binds, links,
28629 and executes, generating the expected output.
28630
28631 @item
28632 Use No_Entry_Calls_In_Elaboration_Code restriction.
28633 @cindex No_Entry_Calls_In_Elaboration_Code
28634
28635 The previous two approaches described how a program can be restructured
28636 to avoid the special problems caused by library task bodies. in practice,
28637 however, such restructuring may be difficult to apply to existing legacy code,
28638 so we must consider solutions that do not require massive rewriting.
28639
28640 Let us consider more carefully why our original sample program works
28641 under the dynamic model of elaboration. The reason is that the code
28642 in the task body blocks immediately on the @code{accept}
28643 statement. Now of course there is nothing to prohibit elaboration
28644 code from making entry calls (for example from another library level task),
28645 so we cannot tell in isolation that
28646 the task will not execute the accept statement  during elaboration.
28647
28648 However, in practice it is very unusual to see elaboration code
28649 make any entry calls, and the pattern of tasks starting
28650 at elaboration time and then immediately blocking on @code{accept} or
28651 @code{select} statements is very common. What this means is that
28652 the compiler is being too pessimistic when it analyzes the
28653 whole package body as though it might be executed at elaboration
28654 time.
28655
28656 If we know that the elaboration code contains no entry calls, (a very safe
28657 assumption most of the time, that could almost be made the default
28658 behavior), then we can compile all units of the program under control
28659 of the following configuration pragma:
28660
28661 @smallexample
28662 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28663 @end smallexample
28664
28665 @noindent
28666 This pragma can be placed in the @file{gnat.adc} file in the usual
28667 manner. If we take our original unmodified program and compile it
28668 in the presence of a @file{gnat.adc} containing the above pragma,
28669 then once again, we can compile, bind, link, and execute, obtaining
28670 the expected result. In the presence of this pragma, the compiler does
28671 not trace calls in a task body, that appear after the first @code{accept}
28672 or @code{select} statement, and therefore does not report a potential
28673 circularity in the original program.
28674
28675 The compiler will check to the extent it can that the above
28676 restriction is not violated, but it is not always possible to do a
28677 complete check at compile time, so it is important to use this
28678 pragma only if the stated restriction is in fact met, that is to say
28679 no task receives an entry call before elaboration of all units is completed.
28680
28681 @end itemize
28682
28683 @node Mixing Elaboration Models
28684 @section Mixing Elaboration Models
28685 @noindent
28686 So far, we have assumed that the entire program is either compiled
28687 using the dynamic model or static model, ensuring consistency. It
28688 is possible to mix the two models, but rules have to be followed
28689 if this mixing is done to ensure that elaboration checks are not
28690 omitted.
28691
28692 The basic rule is that @emph{a unit compiled with the static model cannot
28693 be @code{with'ed} by a unit compiled with the dynamic model}. The
28694 reason for this is that in the static model, a unit assumes that
28695 its clients guarantee to use (the equivalent of) pragma
28696 @code{Elaborate_All} so that no elaboration checks are required
28697 in inner subprograms, and this assumption is violated if the
28698 client is compiled with dynamic checks.
28699
28700 The precise rule is as follows. A unit that is compiled with dynamic
28701 checks can only @code{with} a unit that meets at least one of the
28702 following criteria:
28703
28704 @itemize @bullet
28705
28706 @item
28707 The @code{with'ed} unit is itself compiled with dynamic elaboration
28708 checks (that is with the @option{-gnatE} switch.
28709
28710 @item
28711 The @code{with'ed} unit is an internal GNAT implementation unit from
28712 the System, Interfaces, Ada, or GNAT hierarchies.
28713
28714 @item
28715 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28716
28717 @item
28718 The @code{with'ing} unit (that is the client) has an explicit pragma
28719 @code{Elaborate_All} for the @code{with'ed} unit.
28720
28721 @end itemize
28722
28723 @noindent
28724 If this rule is violated, that is if a unit with dynamic elaboration
28725 checks @code{with's} a unit that does not meet one of the above four
28726 criteria, then the binder (@code{gnatbind}) will issue a warning
28727 similar to that in the following example:
28728
28729 @smallexample
28730 warning: "x.ads" has dynamic elaboration checks and with's
28731 warning:   "y.ads" which has static elaboration checks
28732 @end smallexample
28733
28734 @noindent
28735 These warnings indicate that the rule has been violated, and that as a result
28736 elaboration checks may be missed in the resulting executable file.
28737 This warning may be suppressed using the @option{-ws} binder switch
28738 in the usual manner.
28739
28740 One useful application of this mixing rule is in the case of a subsystem
28741 which does not itself @code{with} units from the remainder of the
28742 application. In this case, the entire subsystem can be compiled with
28743 dynamic checks to resolve a circularity in the subsystem, while
28744 allowing the main application that uses this subsystem to be compiled
28745 using the more reliable default static model.
28746
28747 @node What to Do If the Default Elaboration Behavior Fails
28748 @section What to Do If the Default Elaboration Behavior Fails
28749
28750 @noindent
28751 If the binder cannot find an acceptable order, it outputs detailed
28752 diagnostics. For example:
28753 @smallexample
28754 @group
28755 @iftex
28756 @leftskip=0cm
28757 @end iftex
28758 error: elaboration circularity detected
28759 info:   "proc (body)" must be elaborated before "pack (body)"
28760 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28761 info:     recompile "pack (body)" with -gnatwl
28762 info:                             for full details
28763 info:       "proc (body)"
28764 info:         is needed by its spec:
28765 info:       "proc (spec)"
28766 info:         which is withed by:
28767 info:       "pack (body)"
28768 info:  "pack (body)" must be elaborated before "proc (body)"
28769 info:     reason: pragma Elaborate in unit "proc (body)"
28770 @end group
28771
28772 @end smallexample
28773
28774 @noindent
28775 In this case we have a cycle that the binder cannot break. On the one
28776 hand, there is an explicit pragma Elaborate in @code{proc} for
28777 @code{pack}. This means that the body of @code{pack} must be elaborated
28778 before the body of @code{proc}. On the other hand, there is elaboration
28779 code in @code{pack} that calls a subprogram in @code{proc}. This means
28780 that for maximum safety, there should really be a pragma
28781 Elaborate_All in @code{pack} for @code{proc} which would require that
28782 the body of @code{proc} be elaborated before the body of
28783 @code{pack}. Clearly both requirements cannot be satisfied.
28784 Faced with a circularity of this kind, you have three different options.
28785
28786 @table @asis
28787 @item Fix the program
28788 The most desirable option from the point of view of long-term maintenance
28789 is to rearrange the program so that the elaboration problems are avoided.
28790 One useful technique is to place the elaboration code into separate
28791 child packages. Another is to move some of the initialization code to
28792 explicitly called subprograms, where the program controls the order
28793 of initialization explicitly. Although this is the most desirable option,
28794 it may be impractical and involve too much modification, especially in
28795 the case of complex legacy code.
28796
28797 @item Perform dynamic checks
28798 If the compilations are done using the
28799 @option{-gnatE}
28800 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28801 manner. Dynamic checks are generated for all calls that could possibly result
28802 in raising an exception. With this switch, the compiler does not generate
28803 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28804 exactly as specified in the @cite{Ada Reference Manual}.
28805 The binder will generate
28806 an executable program that may or may not raise @code{Program_Error}, and then
28807 it is the programmer's job to ensure that it does not raise an exception. Note
28808 that it is important to compile all units with the switch, it cannot be used
28809 selectively.
28810
28811 @item Suppress checks
28812 The drawback of dynamic checks is that they generate a
28813 significant overhead at run time, both in space and time. If you
28814 are absolutely sure that your program cannot raise any elaboration
28815 exceptions, and you still want to use the dynamic elaboration model,
28816 then you can use the configuration pragma
28817 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28818 example this pragma could be placed in the @file{gnat.adc} file.
28819
28820 @item Suppress checks selectively
28821 When you know that certain calls or instantiations in elaboration code cannot
28822 possibly lead to an elaboration error, and the binder nevertheless complains
28823 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28824 elaboration circularities, it is possible to remove those warnings locally and
28825 obtain a program that will bind. Clearly this can be unsafe, and it is the
28826 responsibility of the programmer to make sure that the resulting program has no
28827 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28828 used with different granularity to suppress warnings and break elaboration
28829 circularities:
28830
28831 @itemize @bullet
28832 @item
28833 Place the pragma that names the called subprogram in the declarative part
28834 that contains the call.
28835
28836 @item
28837 Place the pragma in the declarative part, without naming an entity. This
28838 disables warnings on all calls in the corresponding  declarative region.
28839
28840 @item
28841 Place the pragma in the package spec that declares the called subprogram,
28842 and name the subprogram. This disables warnings on all elaboration calls to
28843 that subprogram.
28844
28845 @item
28846 Place the pragma in the package spec that declares the called subprogram,
28847 without naming any entity. This disables warnings on all elaboration calls to
28848 all subprograms declared in this spec.
28849
28850 @item Use Pragma Elaborate
28851 As previously described in section @xref{Treatment of Pragma Elaborate},
28852 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28853 that no elaboration checks are required on calls to the designated unit.
28854 There may be cases in which the caller knows that no transitive calls
28855 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28856 case where @code{pragma Elaborate_All} would cause a circularity.
28857 @end itemize
28858
28859 @noindent
28860 These five cases are listed in order of decreasing safety, and therefore
28861 require increasing programmer care in their application. Consider the
28862 following program:
28863
28864 @smallexample @c adanocomment
28865 package Pack1 is
28866   function F1 return Integer;
28867   X1 : Integer;
28868 end Pack1;
28869
28870 package Pack2 is
28871   function F2 return Integer;
28872   function Pure (x : integer) return integer;
28873   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28874   --  pragma Suppress (Elaboration_Check);              -- (4)
28875 end Pack2;
28876
28877 with Pack2;
28878 package body Pack1 is
28879   function F1 return Integer is
28880   begin
28881     return 100;
28882   end F1;
28883   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28884 begin
28885   declare
28886     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28887     --  pragma Suppress(Elaboration_Check);             -- (2)
28888   begin
28889     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28890   end;
28891 end Pack1;
28892
28893 with Pack1;
28894 package body Pack2 is
28895   function F2 return Integer is
28896   begin
28897      return Pack1.F1;
28898   end F2;
28899   function Pure (x : integer) return integer is
28900   begin
28901      return x ** 3 - 3 * x;
28902   end;
28903 end Pack2;
28904
28905 with Pack1, Ada.Text_IO;
28906 procedure Proc3 is
28907 begin
28908   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28909 end Proc3;
28910 @end smallexample
28911 In the absence of any pragmas, an attempt to bind this program produces
28912 the following diagnostics:
28913 @smallexample
28914 @group
28915 @iftex
28916 @leftskip=.5cm
28917 @end iftex
28918 error: elaboration circularity detected
28919 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28920 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28921 info:       recompile "pack1 (body)" with -gnatwl for full details
28922 info:          "pack1 (body)"
28923 info:             must be elaborated along with its spec:
28924 info:          "pack1 (spec)"
28925 info:             which is withed by:
28926 info:          "pack2 (body)"
28927 info:             which must be elaborated along with its spec:
28928 info:          "pack2 (spec)"
28929 info:             which is withed by:
28930 info:          "pack1 (body)"
28931 @end group
28932 @end smallexample
28933 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28934 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28935 F2 is safe, even though F2 calls F1, because the call appears after the
28936 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28937 remove the warning on the call. It is also possible to use pragma (2)
28938 because there are no other potentially unsafe calls in the block.
28939
28940 @noindent
28941 The call to @code{Pure} is safe because this function does not depend on the
28942 state of @code{Pack2}. Therefore any call to this function is safe, and it
28943 is correct to place pragma (3) in the corresponding package spec.
28944
28945 @noindent
28946 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28947 warnings on all calls to functions declared therein. Note that this is not
28948 necessarily safe, and requires more detailed examination of the subprogram
28949 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28950 be already elaborated.
28951 @end table
28952
28953 @noindent
28954 It is hard to generalize on which of these four approaches should be
28955 taken. Obviously if it is possible to fix the program so that the default
28956 treatment works, this is preferable, but this may not always be practical.
28957 It is certainly simple enough to use
28958 @option{-gnatE}
28959 but the danger in this case is that, even if the GNAT binder
28960 finds a correct elaboration order, it may not always do so,
28961 and certainly a binder from another Ada compiler might not. A
28962 combination of testing and analysis (for which the warnings generated
28963 with the
28964 @option{-gnatwl}
28965 switch can be useful) must be used to ensure that the program is free
28966 of errors. One switch that is useful in this testing is the
28967 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28968 switch for
28969 @code{gnatbind}.
28970 Normally the binder tries to find an order that has the best chance
28971 of avoiding elaboration problems. However, if this switch is used, the binder
28972 plays a devil's advocate role, and tries to choose the order that
28973 has the best chance of failing. If your program works even with this
28974 switch, then it has a better chance of being error free, but this is still
28975 not a guarantee.
28976
28977 For an example of this approach in action, consider the C-tests (executable
28978 tests) from the ACVC suite. If these are compiled and run with the default
28979 treatment, then all but one of them succeed without generating any error
28980 diagnostics from the binder. However, there is one test that fails, and
28981 this is not surprising, because the whole point of this test is to ensure
28982 that the compiler can handle cases where it is impossible to determine
28983 a correct order statically, and it checks that an exception is indeed
28984 raised at run time.
28985
28986 This one test must be compiled and run using the
28987 @option{-gnatE}
28988 switch, and then it passes. Alternatively, the entire suite can
28989 be run using this switch. It is never wrong to run with the dynamic
28990 elaboration switch if your code is correct, and we assume that the
28991 C-tests are indeed correct (it is less efficient, but efficiency is
28992 not a factor in running the ACVC tests.)
28993
28994 @node Elaboration for Access-to-Subprogram Values
28995 @section Elaboration for Access-to-Subprogram Values
28996 @cindex Access-to-subprogram
28997
28998 @noindent
28999 Access-to-subprogram types (introduced in Ada 95) complicate
29000 the handling of elaboration. The trouble is that it becomes
29001 impossible to tell at compile time which procedure
29002 is being called. This means that it is not possible for the binder
29003 to analyze the elaboration requirements in this case.
29004
29005 If at the point at which the access value is created
29006 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29007 the body of the subprogram is
29008 known to have been elaborated, then the access value is safe, and its use
29009 does not require a check. This may be achieved by appropriate arrangement
29010 of the order of declarations if the subprogram is in the current unit,
29011 or, if the subprogram is in another unit, by using pragma
29012 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29013 on the referenced unit.
29014
29015 If the referenced body is not known to have been elaborated at the point
29016 the access value is created, then any use of the access value must do a
29017 dynamic check, and this dynamic check will fail and raise a
29018 @code{Program_Error} exception if the body has not been elaborated yet.
29019 GNAT will generate the necessary checks, and in addition, if the
29020 @option{-gnatwl}
29021 switch is set, will generate warnings that such checks are required.
29022
29023 The use of dynamic dispatching for tagged types similarly generates
29024 a requirement for dynamic checks, and premature calls to any primitive
29025 operation of a tagged type before the body of the operation has been
29026 elaborated, will result in the raising of @code{Program_Error}.
29027
29028 @node Summary of Procedures for Elaboration Control
29029 @section Summary of Procedures for Elaboration Control
29030 @cindex Elaboration control
29031
29032 @noindent
29033 First, compile your program with the default options, using none of
29034 the special elaboration control switches. If the binder successfully
29035 binds your program, then you can be confident that, apart from issues
29036 raised by the use of access-to-subprogram types and dynamic dispatching,
29037 the program is free of elaboration errors. If it is important that the
29038 program be portable, then use the
29039 @option{-gnatwl}
29040 switch to generate warnings about missing @code{Elaborate} or
29041 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29042
29043 If the program fails to bind using the default static elaboration
29044 handling, then you can fix the program to eliminate the binder
29045 message, or recompile the entire program with the
29046 @option{-gnatE} switch to generate dynamic elaboration checks,
29047 and, if you are sure there really are no elaboration problems,
29048 use a global pragma @code{Suppress (Elaboration_Check)}.
29049
29050 @node Other Elaboration Order Considerations
29051 @section Other Elaboration Order Considerations
29052 @noindent
29053 This section has been entirely concerned with the issue of finding a valid
29054 elaboration order, as defined by the Ada Reference Manual. In a case
29055 where several elaboration orders are valid, the task is to find one
29056 of the possible valid elaboration orders (and the static model in GNAT
29057 will ensure that this is achieved).
29058
29059 The purpose of the elaboration rules in the Ada Reference Manual is to
29060 make sure that no entity is accessed before it has been elaborated. For
29061 a subprogram, this means that the spec and body must have been elaborated
29062 before the subprogram is called. For an object, this means that the object
29063 must have been elaborated before its value is read or written. A violation
29064 of either of these two requirements is an access before elaboration order,
29065 and this section has been all about avoiding such errors.
29066
29067 In the case where more than one order of elaboration is possible, in the
29068 sense that access before elaboration errors are avoided, then any one of
29069 the orders is ``correct'' in the sense that it meets the requirements of
29070 the Ada Reference Manual, and no such error occurs.
29071
29072 However, it may be the case for a given program, that there are
29073 constraints on the order of elaboration that come not from consideration
29074 of avoiding elaboration errors, but rather from extra-lingual logic
29075 requirements. Consider this example:
29076
29077 @smallexample @c ada
29078 with Init_Constants;
29079 package Constants is
29080    X : Integer := 0;
29081    Y : Integer := 0;
29082 end Constants;
29083
29084 package Init_Constants is
29085    procedure P; -- require a body
29086 end Init_Constants;
29087
29088 with Constants;
29089 package body Init_Constants is
29090    procedure P is begin null; end;
29091 begin
29092    Constants.X := 3;
29093    Constants.Y := 4;
29094 end Init_Constants;
29095
29096 with Constants;
29097 package Calc is
29098    Z : Integer := Constants.X + Constants.Y;
29099 end Calc;
29100
29101 with Calc;
29102 with Text_IO; use Text_IO;
29103 procedure Main is
29104 begin
29105    Put_Line (Calc.Z'Img);
29106 end Main;
29107 @end smallexample
29108
29109 @noindent
29110 In this example, there is more than one valid order of elaboration. For
29111 example both the following are correct orders:
29112
29113 @smallexample
29114 Init_Constants spec
29115 Constants spec
29116 Calc spec
29117 Init_Constants body
29118 Main body
29119
29120   and
29121
29122 Init_Constants spec
29123 Init_Constants body
29124 Constants spec
29125 Calc spec
29126 Main body
29127 @end smallexample
29128
29129 @noindent
29130 There is no language rule to prefer one or the other, both are correct
29131 from an order of elaboration point of view. But the programmatic effects
29132 of the two orders are very different. In the first, the elaboration routine
29133 of @code{Calc} initializes @code{Z} to zero, and then the main program
29134 runs with this value of zero. But in the second order, the elaboration
29135 routine of @code{Calc} runs after the body of Init_Constants has set
29136 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29137 runs.
29138
29139 One could perhaps by applying pretty clever non-artificial intelligence
29140 to the situation guess that it is more likely that the second order of
29141 elaboration is the one desired, but there is no formal linguistic reason
29142 to prefer one over the other. In fact in this particular case, GNAT will
29143 prefer the second order, because of the rule that bodies are elaborated
29144 as soon as possible, but it's just luck that this is what was wanted
29145 (if indeed the second order was preferred).
29146
29147 If the program cares about the order of elaboration routines in a case like
29148 this, it is important to specify the order required. In this particular
29149 case, that could have been achieved by adding to the spec of Calc:
29150
29151 @smallexample @c ada
29152 pragma Elaborate_All (Constants);
29153 @end smallexample
29154
29155 @noindent
29156 which requires that the body (if any) and spec of @code{Constants},
29157 as well as the body and spec of any unit @code{with}'ed by
29158 @code{Constants} be elaborated before @code{Calc} is elaborated.
29159
29160 Clearly no automatic method can always guess which alternative you require,
29161 and if you are working with legacy code that had constraints of this kind
29162 which were not properly specified by adding @code{Elaborate} or
29163 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29164 compilers can choose different orders.
29165
29166 However, GNAT does attempt to diagnose the common situation where there
29167 are uninitialized variables in the visible part of a package spec, and the
29168 corresponding package body has an elaboration block that directly or
29169 indirectly initialized one or more of these variables. This is the situation
29170 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29171 a warning that suggests this addition if it detects this situation.
29172
29173 The @code{gnatbind}
29174 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29175 out problems. This switch causes bodies to be elaborated as late as possible
29176 instead of as early as possible. In the example above, it would have forced
29177 the choice of the first elaboration order. If you get different results
29178 when using this switch, and particularly if one set of results is right,
29179 and one is wrong as far as you are concerned, it shows that you have some
29180 missing @code{Elaborate} pragmas. For the example above, we have the
29181 following output:
29182
29183 @smallexample
29184 gnatmake -f -q main
29185 main
29186  7
29187 gnatmake -f -q main -bargs -p
29188 main
29189  0
29190 @end smallexample
29191
29192 @noindent
29193 It is of course quite unlikely that both these results are correct, so
29194 it is up to you in a case like this to investigate the source of the
29195 difference, by looking at the two elaboration orders that are chosen,
29196 and figuring out which is correct, and then adding the necessary
29197 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29198
29199
29200
29201 @c *******************************
29202 @node Conditional Compilation
29203 @appendix Conditional Compilation
29204 @c *******************************
29205 @cindex Conditional compilation
29206
29207 @noindent
29208 It is often necessary to arrange for a single source program
29209 to serve multiple purposes, where it is compiled in different
29210 ways to achieve these different goals. Some examples of the
29211 need for this feature are
29212
29213 @itemize @bullet
29214 @item  Adapting a program to a different hardware environment
29215 @item  Adapting a program to a different target architecture
29216 @item  Turning debugging features on and off
29217 @item  Arranging for a program to compile with different compilers
29218 @end itemize
29219
29220 @noindent
29221 In C, or C++, the typical approach would be to use the preprocessor
29222 that is defined as part of the language. The Ada language does not
29223 contain such a feature. This is not an oversight, but rather a very
29224 deliberate design decision, based on the experience that overuse of
29225 the preprocessing features in C and C++ can result in programs that
29226 are extremely difficult to maintain. For example, if we have ten
29227 switches that can be on or off, this means that there are a thousand
29228 separate programs, any one of which might not even be syntactically
29229 correct, and even if syntactically correct, the resulting program
29230 might not work correctly. Testing all combinations can quickly become
29231 impossible.
29232
29233 Nevertheless, the need to tailor programs certainly exists, and in
29234 this Appendix we will discuss how this can
29235 be achieved using Ada in general, and GNAT in particular.
29236
29237 @menu
29238 * Use of Boolean Constants::
29239 * Debugging - A Special Case::
29240 * Conditionalizing Declarations::
29241 * Use of Alternative Implementations::
29242 * Preprocessing::
29243 @end menu
29244
29245 @node Use of Boolean Constants
29246 @section Use of Boolean Constants
29247
29248 @noindent
29249 In the case where the difference is simply which code
29250 sequence is executed, the cleanest solution is to use Boolean
29251 constants to control which code is executed.
29252
29253 @smallexample @c ada
29254 @group
29255 FP_Initialize_Required : constant Boolean := True;
29256 @dots{}
29257 if FP_Initialize_Required then
29258 @dots{}
29259 end if;
29260 @end group
29261 @end smallexample
29262
29263 @noindent
29264 Not only will the code inside the @code{if} statement not be executed if
29265 the constant Boolean is @code{False}, but it will also be completely
29266 deleted from the program.
29267 However, the code is only deleted after the @code{if} statement
29268 has been checked for syntactic and semantic correctness.
29269 (In contrast, with preprocessors the code is deleted before the
29270 compiler ever gets to see it, so it is not checked until the switch
29271 is turned on.)
29272 @cindex Preprocessors (contrasted with conditional compilation)
29273
29274 Typically the Boolean constants will be in a separate package,
29275 something like:
29276
29277 @smallexample @c ada
29278 @group
29279 package Config is
29280    FP_Initialize_Required : constant Boolean := True;
29281    Reset_Available        : constant Boolean := False;
29282    @dots{}
29283 end Config;
29284 @end group
29285 @end smallexample
29286
29287 @noindent
29288 The @code{Config} package exists in multiple forms for the various targets,
29289 with an appropriate script selecting the version of @code{Config} needed.
29290 Then any other unit requiring conditional compilation can do a @code{with}
29291 of @code{Config} to make the constants visible.
29292
29293
29294 @node Debugging - A Special Case
29295 @section Debugging - A Special Case
29296
29297 @noindent
29298 A common use of conditional code is to execute statements (for example
29299 dynamic checks, or output of intermediate results) under control of a
29300 debug switch, so that the debugging behavior can be turned on and off.
29301 This can be done using a Boolean constant to control whether the code
29302 is active:
29303
29304 @smallexample @c ada
29305 @group
29306 if Debugging then
29307    Put_Line ("got to the first stage!");
29308 end if;
29309 @end group
29310 @end smallexample
29311
29312 @noindent
29313 or
29314
29315 @smallexample @c ada
29316 @group
29317 if Debugging and then Temperature > 999.0 then
29318    raise Temperature_Crazy;
29319 end if;
29320 @end group
29321 @end smallexample
29322
29323 @noindent
29324 Since this is a common case, there are special features to deal with
29325 this in a convenient manner. For the case of tests, Ada 2005 has added
29326 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29327 @cindex pragma @code{Assert}
29328 on the @code{Assert} pragma that has always been available in GNAT, so this
29329 feature may be used with GNAT even if you are not using Ada 2005 features.
29330 The use of pragma @code{Assert} is described in
29331 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29332 example, the last test could be written:
29333
29334 @smallexample @c ada
29335 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29336 @end smallexample
29337
29338 @noindent
29339 or simply
29340
29341 @smallexample @c ada
29342 pragma Assert (Temperature <= 999.0);
29343 @end smallexample
29344
29345 @noindent
29346 In both cases, if assertions are active and the temperature is excessive,
29347 the exception @code{Assert_Failure} will be raised, with the given string in
29348 the first case or a string indicating the location of the pragma in the second
29349 case used as the exception message.
29350
29351 You can turn assertions on and off by using the @code{Assertion_Policy}
29352 pragma.
29353 @cindex pragma @code{Assertion_Policy}
29354 This is an Ada 2005 pragma which is implemented in all modes by
29355 GNAT, but only in the latest versions of GNAT which include Ada 2005
29356 capability. Alternatively, you can use the @option{-gnata} switch
29357 @cindex @option{-gnata} switch
29358 to enable assertions from the command line (this is recognized by all versions
29359 of GNAT).
29360
29361 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29362 @code{Debug} can be used:
29363 @cindex pragma @code{Debug}
29364
29365 @smallexample @c ada
29366 pragma Debug (Put_Line ("got to the first stage!"));
29367 @end smallexample
29368
29369 @noindent
29370 If debug pragmas are enabled, the argument, which must be of the form of
29371 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29372 Only one call can be present, but of course a special debugging procedure
29373 containing any code you like can be included in the program and then
29374 called in a pragma @code{Debug} argument as needed.
29375
29376 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29377 construct is that pragma @code{Debug} can appear in declarative contexts,
29378 such as at the very beginning of a procedure, before local declarations have
29379 been elaborated.
29380
29381 Debug pragmas are enabled using either the @option{-gnata} switch that also
29382 controls assertions, or with a separate Debug_Policy pragma.
29383 @cindex pragma @code{Debug_Policy}
29384 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29385 in Ada 95 and Ada 83 programs as well), and is analogous to
29386 pragma @code{Assertion_Policy} to control assertions.
29387
29388 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29389 and thus they can appear in @file{gnat.adc} if you are not using a
29390 project file, or in the file designated to contain configuration pragmas
29391 in a project file.
29392 They then apply to all subsequent compilations. In practice the use of
29393 the @option{-gnata} switch is often the most convenient method of controlling
29394 the status of these pragmas.
29395
29396 Note that a pragma is not a statement, so in contexts where a statement
29397 sequence is required, you can't just write a pragma on its own. You have
29398 to add a @code{null} statement.
29399
29400 @smallexample @c ada
29401 @group
29402 if @dots{} then
29403    @dots{} -- some statements
29404 else
29405    pragma Assert (Num_Cases < 10);
29406    null;
29407 end if;
29408 @end group
29409 @end smallexample
29410
29411
29412 @node Conditionalizing Declarations
29413 @section Conditionalizing Declarations
29414
29415 @noindent
29416 In some cases, it may be necessary to conditionalize declarations to meet
29417 different requirements. For example we might want a bit string whose length
29418 is set to meet some hardware message requirement.
29419
29420 In some cases, it may be possible to do this using declare blocks controlled
29421 by conditional constants:
29422
29423 @smallexample @c ada
29424 @group
29425 if Small_Machine then
29426    declare
29427       X : Bit_String (1 .. 10);
29428    begin
29429       @dots{}
29430    end;
29431 else
29432    declare
29433       X : Large_Bit_String (1 .. 1000);
29434    begin
29435       @dots{}
29436    end;
29437 end if;
29438 @end group
29439 @end smallexample
29440
29441 @noindent
29442 Note that in this approach, both declarations are analyzed by the
29443 compiler so this can only be used where both declarations are legal,
29444 even though one of them will not be used.
29445
29446 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29447 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29448 that are parameterized by these constants. For example
29449
29450 @smallexample @c ada
29451 @group
29452 for Rec use
29453   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29454 end record;
29455 @end group
29456 @end smallexample
29457
29458 @noindent
29459 If @code{Bits_Per_Word} is set to 32, this generates either
29460
29461 @smallexample @c ada
29462 @group
29463 for Rec use
29464   Field1 at 0 range 0 .. 32;
29465 end record;
29466 @end group
29467 @end smallexample
29468
29469 @noindent
29470 for the big endian case, or
29471
29472 @smallexample @c ada
29473 @group
29474 for Rec use record
29475   Field1 at 0 range 10 .. 32;
29476 end record;
29477 @end group
29478 @end smallexample
29479
29480 @noindent
29481 for the little endian case. Since a powerful subset of Ada expression
29482 notation is usable for creating static constants, clever use of this
29483 feature can often solve quite difficult problems in conditionalizing
29484 compilation (note incidentally that in Ada 95, the little endian
29485 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29486 need to define this one yourself).
29487
29488
29489 @node Use of Alternative Implementations
29490 @section Use of Alternative Implementations
29491
29492 @noindent
29493 In some cases, none of the approaches described above are adequate. This
29494 can occur for example if the set of declarations required is radically
29495 different for two different configurations.
29496
29497 In this situation, the official Ada way of dealing with conditionalizing
29498 such code is to write separate units for the different cases. As long as
29499 this does not result in excessive duplication of code, this can be done
29500 without creating maintenance problems. The approach is to share common
29501 code as far as possible, and then isolate the code and declarations
29502 that are different. Subunits are often a convenient method for breaking
29503 out a piece of a unit that is to be conditionalized, with separate files
29504 for different versions of the subunit for different targets, where the
29505 build script selects the right one to give to the compiler.
29506 @cindex Subunits (and conditional compilation)
29507
29508 As an example, consider a situation where a new feature in Ada 2005
29509 allows something to be done in a really nice way. But your code must be able
29510 to compile with an Ada 95 compiler. Conceptually you want to say:
29511
29512 @smallexample @c ada
29513 @group
29514 if Ada_2005 then
29515    @dots{} neat Ada 2005 code
29516 else
29517    @dots{} not quite as neat Ada 95 code
29518 end if;
29519 @end group
29520 @end smallexample
29521
29522 @noindent
29523 where @code{Ada_2005} is a Boolean constant.
29524
29525 But this won't work when @code{Ada_2005} is set to @code{False},
29526 since the @code{then} clause will be illegal for an Ada 95 compiler.
29527 (Recall that although such unreachable code would eventually be deleted
29528 by the compiler, it still needs to be legal.  If it uses features
29529 introduced in Ada 2005, it will be illegal in Ada 95.)
29530
29531 So instead we write
29532
29533 @smallexample @c ada
29534 procedure Insert is separate;
29535 @end smallexample
29536
29537 @noindent
29538 Then we have two files for the subunit @code{Insert}, with the two sets of
29539 code.
29540 If the package containing this is called @code{File_Queries}, then we might
29541 have two files
29542
29543 @itemize @bullet
29544 @item    @file{file_queries-insert-2005.adb}
29545 @item    @file{file_queries-insert-95.adb}
29546 @end itemize
29547
29548 @noindent
29549 and the build script renames the appropriate file to
29550
29551 @smallexample
29552 file_queries-insert.adb
29553 @end smallexample
29554
29555 @noindent
29556 and then carries out the compilation.
29557
29558 This can also be done with project files' naming schemes. For example:
29559
29560 @smallexample @c project
29561 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29562 @end smallexample
29563
29564 @noindent
29565 Note also that with project files it is desirable to use a different extension
29566 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29567 conflict may arise through another commonly used feature: to declare as part
29568 of the project a set of directories containing all the sources obeying the
29569 default naming scheme.
29570
29571 The use of alternative units is certainly feasible in all situations,
29572 and for example the Ada part of the GNAT run-time is conditionalized
29573 based on the target architecture using this approach. As a specific example,
29574 consider the implementation of the AST feature in VMS. There is one
29575 spec:
29576
29577 @smallexample
29578 s-asthan.ads
29579 @end smallexample
29580
29581 @noindent
29582 which is the same for all architectures, and three bodies:
29583
29584 @table @file
29585 @item    s-asthan.adb
29586 used for all non-VMS operating systems
29587 @item    s-asthan-vms-alpha.adb
29588 used for VMS on the Alpha
29589 @item    s-asthan-vms-ia64.adb
29590 used for VMS on the ia64
29591 @end table
29592
29593 @noindent
29594 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29595 this operating system feature is not available, and the two remaining
29596 versions interface with the corresponding versions of VMS to provide
29597 VMS-compatible AST handling. The GNAT build script knows the architecture
29598 and operating system, and automatically selects the right version,
29599 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29600
29601 Another style for arranging alternative implementations is through Ada's
29602 access-to-subprogram facility.
29603 In case some functionality is to be conditionally included,
29604 you can declare an access-to-procedure variable @code{Ref} that is initialized
29605 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29606 when appropriate.
29607 In some library package, set @code{Ref} to @code{Proc'Access} for some
29608 procedure @code{Proc} that performs the relevant processing.
29609 The initialization only occurs if the library package is included in the
29610 program.
29611 The same idea can also be implemented using tagged types and dispatching
29612 calls.
29613
29614
29615 @node Preprocessing
29616 @section Preprocessing
29617 @cindex Preprocessing
29618
29619 @noindent
29620 Although it is quite possible to conditionalize code without the use of
29621 C-style preprocessing, as described earlier in this section, it is
29622 nevertheless convenient in some cases to use the C approach. Moreover,
29623 older Ada compilers have often provided some preprocessing capability,
29624 so legacy code may depend on this approach, even though it is not
29625 standard.
29626
29627 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29628 extent on the various preprocessors that have been used
29629 with legacy code on other compilers, to enable easier transition).
29630
29631 The preprocessor may be used in two separate modes. It can be used quite
29632 separately from the compiler, to generate a separate output source file
29633 that is then fed to the compiler as a separate step. This is the
29634 @code{gnatprep} utility, whose use is fully described in
29635 @ref{Preprocessing Using gnatprep}.
29636 @cindex @code{gnatprep}
29637
29638 The preprocessing language allows such constructs as
29639
29640 @smallexample
29641 @group
29642 #if DEBUG or PRIORITY > 4 then
29643    bunch of declarations
29644 #else
29645    completely different bunch of declarations
29646 #end if;
29647 @end group
29648 @end smallexample
29649
29650 @noindent
29651 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29652 defined either on the command line or in a separate file.
29653
29654 The other way of running the preprocessor is even closer to the C style and
29655 often more convenient. In this approach the preprocessing is integrated into
29656 the compilation process. The compiler is fed the preprocessor input which
29657 includes @code{#if} lines etc, and then the compiler carries out the
29658 preprocessing internally and processes the resulting output.
29659 For more details on this approach, see @ref{Integrated Preprocessing}.
29660
29661
29662 @c *******************************
29663 @node Inline Assembler
29664 @appendix Inline Assembler
29665 @c *******************************
29666
29667 @noindent
29668 If you need to write low-level software that interacts directly
29669 with the hardware, Ada provides two ways to incorporate assembly
29670 language code into your program.  First, you can import and invoke
29671 external routines written in assembly language, an Ada feature fully
29672 supported by GNAT@.  However, for small sections of code it may be simpler
29673 or more efficient to include assembly language statements directly
29674 in your Ada source program, using the facilities of the implementation-defined
29675 package @code{System.Machine_Code}, which incorporates the gcc
29676 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29677 including the following:
29678
29679 @itemize @bullet
29680 @item No need to use non-Ada tools
29681 @item Consistent interface over different targets
29682 @item Automatic usage of the proper calling conventions
29683 @item Access to Ada constants and variables
29684 @item Definition of intrinsic routines
29685 @item Possibility of inlining a subprogram comprising assembler code
29686 @item Code optimizer can take Inline Assembler code into account
29687 @end itemize
29688
29689 This chapter presents a series of examples to show you how to use
29690 the Inline Assembler.  Although it focuses on the Intel x86,
29691 the general approach applies also to other processors.
29692 It is assumed that you are familiar with Ada
29693 and with assembly language programming.
29694
29695 @menu
29696 * Basic Assembler Syntax::
29697 * A Simple Example of Inline Assembler::
29698 * Output Variables in Inline Assembler::
29699 * Input Variables in Inline Assembler::
29700 * Inlining Inline Assembler Code::
29701 * Other Asm Functionality::
29702 @end menu
29703
29704 @c ---------------------------------------------------------------------------
29705 @node Basic Assembler Syntax
29706 @section Basic Assembler Syntax
29707
29708 @noindent
29709 The assembler used by GNAT and gcc is based not on the Intel assembly
29710 language, but rather on a language that descends from the AT&T Unix
29711 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29712 The following table summarizes the main features of @emph{as} syntax
29713 and points out the differences from the Intel conventions.
29714 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29715 pre-processor) documentation for further information.
29716
29717 @table @asis
29718 @item Register names
29719 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29720 @*
29721 Intel: No extra punctuation; for example @code{eax}
29722
29723 @item Immediate operand
29724 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29725 @*
29726 Intel: No extra punctuation; for example @code{4}
29727
29728 @item Address
29729 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29730 @*
29731 Intel: No extra punctuation; for example @code{loc}
29732
29733 @item Memory contents
29734 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29735 @*
29736 Intel: Square brackets; for example @code{[loc]}
29737
29738 @item Register contents
29739 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29740 @*
29741 Intel: Square brackets; for example @code{[eax]}
29742
29743 @item Hexadecimal numbers
29744 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29745 @*
29746 Intel: Trailing ``h''; for example @code{A0h}
29747
29748 @item Operand size
29749 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29750 a 16-bit word
29751 @*
29752 Intel: Implicit, deduced by assembler; for example @code{mov}
29753
29754 @item Instruction repetition
29755 gcc / @emph{as}: Split into two lines; for example
29756 @*
29757 @code{rep}
29758 @*
29759 @code{stosl}
29760 @*
29761 Intel: Keep on one line; for example @code{rep stosl}
29762
29763 @item Order of operands
29764 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29765 @*
29766 Intel: Destination first; for example @code{mov eax, 4}
29767 @end table
29768
29769 @c ---------------------------------------------------------------------------
29770 @node A Simple Example of Inline Assembler
29771 @section A Simple Example of Inline Assembler
29772
29773 @noindent
29774 The following example will generate a single assembly language statement,
29775 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29776 the example will be useful in illustrating the basics of
29777 the Inline Assembler facility.
29778
29779 @smallexample @c ada
29780 @group
29781 with System.Machine_Code; use System.Machine_Code;
29782 procedure Nothing is
29783 begin
29784    Asm ("nop");
29785 end Nothing;
29786 @end group
29787 @end smallexample
29788
29789 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29790 here it takes one parameter, a @emph{template string} that must be a static
29791 expression and that will form the generated instruction.
29792 @code{Asm} may be regarded as a compile-time procedure that parses
29793 the template string and additional parameters (none here),
29794 from which it generates a sequence of assembly language instructions.
29795
29796 The examples in this chapter will illustrate several of the forms
29797 for invoking @code{Asm}; a complete specification of the syntax
29798 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29799 Manual}.
29800
29801 Under the standard GNAT conventions, the @code{Nothing} procedure
29802 should be in a file named @file{nothing.adb}.
29803 You can build the executable in the usual way:
29804 @smallexample
29805 gnatmake nothing
29806 @end smallexample
29807 However, the interesting aspect of this example is not its run-time behavior
29808 but rather the generated assembly code.
29809 To see this output, invoke the compiler as follows:
29810 @smallexample
29811    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29812 @end smallexample
29813 where the options are:
29814
29815 @table @code
29816 @item -c
29817 compile only (no bind or link)
29818 @item -S
29819 generate assembler listing
29820 @item -fomit-frame-pointer
29821 do not set up separate stack frames
29822 @item -gnatp
29823 do not add runtime checks
29824 @end table
29825
29826 This gives a human-readable assembler version of the code. The resulting
29827 file will have the same name as the Ada source file, but with a @code{.s}
29828 extension. In our example, the file @file{nothing.s} has the following
29829 contents:
29830
29831 @smallexample
29832 @group
29833 .file "nothing.adb"
29834 gcc2_compiled.:
29835 ___gnu_compiled_ada:
29836 .text
29837    .align 4
29838 .globl __ada_nothing
29839 __ada_nothing:
29840 #APP
29841    nop
29842 #NO_APP
29843    jmp L1
29844    .align 2,0x90
29845 L1:
29846    ret
29847 @end group
29848 @end smallexample
29849
29850 The assembly code you included is clearly indicated by
29851 the compiler, between the @code{#APP} and @code{#NO_APP}
29852 delimiters. The character before the 'APP' and 'NOAPP'
29853 can differ on different targets. For example, GNU/Linux uses '#APP' while
29854 on NT you will see '/APP'.
29855
29856 If you make a mistake in your assembler code (such as using the
29857 wrong size modifier, or using a wrong operand for the instruction) GNAT
29858 will report this error in a temporary file, which will be deleted when
29859 the compilation is finished.  Generating an assembler file will help
29860 in such cases, since you can assemble this file separately using the
29861 @emph{as} assembler that comes with gcc.
29862
29863 Assembling the file using the command
29864
29865 @smallexample
29866 as @file{nothing.s}
29867 @end smallexample
29868 @noindent
29869 will give you error messages whose lines correspond to the assembler
29870 input file, so you can easily find and correct any mistakes you made.
29871 If there are no errors, @emph{as} will generate an object file
29872 @file{nothing.out}.
29873
29874 @c ---------------------------------------------------------------------------
29875 @node Output Variables in Inline Assembler
29876 @section Output Variables in Inline Assembler
29877
29878 @noindent
29879 The examples in this section, showing how to access the processor flags,
29880 illustrate how to specify the destination operands for assembly language
29881 statements.
29882
29883 @smallexample @c ada
29884 @group
29885 with Interfaces; use Interfaces;
29886 with Ada.Text_IO; use Ada.Text_IO;
29887 with System.Machine_Code; use System.Machine_Code;
29888 procedure Get_Flags is
29889    Flags : Unsigned_32;
29890    use ASCII;
29891 begin
29892    Asm ("pushfl"          & LF & HT & -- push flags on stack
29893         "popl %%eax"      & LF & HT & -- load eax with flags
29894         "movl %%eax, %0",             -- store flags in variable
29895         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29896    Put_Line ("Flags register:" & Flags'Img);
29897 end Get_Flags;
29898 @end group
29899 @end smallexample
29900
29901 In order to have a nicely aligned assembly listing, we have separated
29902 multiple assembler statements in the Asm template string with linefeed
29903 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29904 The resulting section of the assembly output file is:
29905
29906 @smallexample
29907 @group
29908 #APP
29909    pushfl
29910    popl %eax
29911    movl %eax, -40(%ebp)
29912 #NO_APP
29913 @end group
29914 @end smallexample
29915
29916 It would have been legal to write the Asm invocation as:
29917
29918 @smallexample
29919 Asm ("pushfl popl %%eax movl %%eax, %0")
29920 @end smallexample
29921
29922 but in the generated assembler file, this would come out as:
29923
29924 @smallexample
29925 #APP
29926    pushfl popl %eax movl %eax, -40(%ebp)
29927 #NO_APP
29928 @end smallexample
29929
29930 which is not so convenient for the human reader.
29931
29932 We use Ada comments
29933 at the end of each line to explain what the assembler instructions
29934 actually do.  This is a useful convention.
29935
29936 When writing Inline Assembler instructions, you need to precede each register
29937 and variable name with a percent sign.  Since the assembler already requires
29938 a percent sign at the beginning of a register name, you need two consecutive
29939 percent signs for such names in the Asm template string, thus @code{%%eax}.
29940 In the generated assembly code, one of the percent signs will be stripped off.
29941
29942 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29943 variables: operands you later define using @code{Input} or @code{Output}
29944 parameters to @code{Asm}.
29945 An output variable is illustrated in
29946 the third statement in the Asm template string:
29947 @smallexample
29948 movl %%eax, %0
29949 @end smallexample
29950 The intent is to store the contents of the eax register in a variable that can
29951 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29952 necessarily work, since the compiler might optimize by using a register
29953 to hold Flags, and the expansion of the @code{movl} instruction would not be
29954 aware of this optimization.  The solution is not to store the result directly
29955 but rather to advise the compiler to choose the correct operand form;
29956 that is the purpose of the @code{%0} output variable.
29957
29958 Information about the output variable is supplied in the @code{Outputs}
29959 parameter to @code{Asm}:
29960 @smallexample
29961 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29962 @end smallexample
29963
29964 The output is defined by the @code{Asm_Output} attribute of the target type;
29965 the general format is
29966 @smallexample
29967 Type'Asm_Output (constraint_string, variable_name)
29968 @end smallexample
29969
29970 The constraint string directs the compiler how
29971 to store/access the associated variable.  In the example
29972 @smallexample
29973 Unsigned_32'Asm_Output ("=m", Flags);
29974 @end smallexample
29975 the @code{"m"} (memory) constraint tells the compiler that the variable
29976 @code{Flags} should be stored in a memory variable, thus preventing
29977 the optimizer from keeping it in a register.  In contrast,
29978 @smallexample
29979 Unsigned_32'Asm_Output ("=r", Flags);
29980 @end smallexample
29981 uses the @code{"r"} (register) constraint, telling the compiler to
29982 store the variable in a register.
29983
29984 If the constraint is preceded by the equal character (@strong{=}), it tells
29985 the compiler that the variable will be used to store data into it.
29986
29987 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29988 allowing the optimizer to choose whatever it deems best.
29989
29990 There are a fairly large number of constraints, but the ones that are
29991 most useful (for the Intel x86 processor) are the following:
29992
29993 @table @code
29994 @item =
29995 output constraint
29996 @item g
29997 global (i.e.@: can be stored anywhere)
29998 @item m
29999 in memory
30000 @item I
30001 a constant
30002 @item a
30003 use eax
30004 @item b
30005 use ebx
30006 @item c
30007 use ecx
30008 @item d
30009 use edx
30010 @item S
30011 use esi
30012 @item D
30013 use edi
30014 @item r
30015 use one of eax, ebx, ecx or edx
30016 @item q
30017 use one of eax, ebx, ecx, edx, esi or edi
30018 @end table
30019
30020 The full set of constraints is described in the gcc and @emph{as}
30021 documentation; note that it is possible to combine certain constraints
30022 in one constraint string.
30023
30024 You specify the association of an output variable with an assembler operand
30025 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30026 integer.  Thus in
30027 @smallexample @c ada
30028 @group
30029 Asm ("pushfl"          & LF & HT & -- push flags on stack
30030      "popl %%eax"      & LF & HT & -- load eax with flags
30031      "movl %%eax, %0",             -- store flags in variable
30032      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30033 @end group
30034 @end smallexample
30035 @noindent
30036 @code{%0} will be replaced in the expanded code by the appropriate operand,
30037 whatever
30038 the compiler decided for the @code{Flags} variable.
30039
30040 In general, you may have any number of output variables:
30041 @itemize @bullet
30042 @item
30043 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30044 @item
30045 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30046 of @code{Asm_Output} attributes
30047 @end itemize
30048
30049 For example:
30050 @smallexample @c ada
30051 @group
30052 Asm ("movl %%eax, %0" & LF & HT &
30053      "movl %%ebx, %1" & LF & HT &
30054      "movl %%ecx, %2",
30055      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30056                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30057                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30058 @end group
30059 @end smallexample
30060 @noindent
30061 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30062 in the Ada program.
30063
30064 As a variation on the @code{Get_Flags} example, we can use the constraints
30065 string to direct the compiler to store the eax register into the @code{Flags}
30066 variable, instead of including the store instruction explicitly in the
30067 @code{Asm} template string:
30068
30069 @smallexample @c ada
30070 @group
30071 with Interfaces; use Interfaces;
30072 with Ada.Text_IO; use Ada.Text_IO;
30073 with System.Machine_Code; use System.Machine_Code;
30074 procedure Get_Flags_2 is
30075    Flags : Unsigned_32;
30076    use ASCII;
30077 begin
30078    Asm ("pushfl"      & LF & HT & -- push flags on stack
30079         "popl %%eax",             -- save flags in eax
30080         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30081    Put_Line ("Flags register:" & Flags'Img);
30082 end Get_Flags_2;
30083 @end group
30084 @end smallexample
30085
30086 @noindent
30087 The @code{"a"} constraint tells the compiler that the @code{Flags}
30088 variable will come from the eax register. Here is the resulting code:
30089
30090 @smallexample
30091 @group
30092 #APP
30093    pushfl
30094    popl %eax
30095 #NO_APP
30096    movl %eax,-40(%ebp)
30097 @end group
30098 @end smallexample
30099
30100 @noindent
30101 The compiler generated the store of eax into Flags after
30102 expanding the assembler code.
30103
30104 Actually, there was no need to pop the flags into the eax register;
30105 more simply, we could just pop the flags directly into the program variable:
30106
30107 @smallexample @c ada
30108 @group
30109 with Interfaces; use Interfaces;
30110 with Ada.Text_IO; use Ada.Text_IO;
30111 with System.Machine_Code; use System.Machine_Code;
30112 procedure Get_Flags_3 is
30113    Flags : Unsigned_32;
30114    use ASCII;
30115 begin
30116    Asm ("pushfl"  & LF & HT & -- push flags on stack
30117         "pop %0",             -- save flags in Flags
30118         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30119    Put_Line ("Flags register:" & Flags'Img);
30120 end Get_Flags_3;
30121 @end group
30122 @end smallexample
30123
30124 @c ---------------------------------------------------------------------------
30125 @node Input Variables in Inline Assembler
30126 @section Input Variables in Inline Assembler
30127
30128 @noindent
30129 The example in this section illustrates how to specify the source operands
30130 for assembly language statements.
30131 The program simply increments its input value by 1:
30132
30133 @smallexample @c ada
30134 @group
30135 with Interfaces; use Interfaces;
30136 with Ada.Text_IO; use Ada.Text_IO;
30137 with System.Machine_Code; use System.Machine_Code;
30138 procedure Increment is
30139
30140    function Incr (Value : Unsigned_32) return Unsigned_32 is
30141       Result : Unsigned_32;
30142    begin
30143       Asm ("incl %0",
30144            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30145            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30146       return Result;
30147    end Incr;
30148
30149    Value : Unsigned_32;
30150
30151 begin
30152    Value := 5;
30153    Put_Line ("Value before is" & Value'Img);
30154    Value := Incr (Value);
30155    Put_Line ("Value after is" & Value'Img);
30156 end Increment;
30157 @end group
30158 @end smallexample
30159
30160 The @code{Outputs} parameter to @code{Asm} specifies
30161 that the result will be in the eax register and that it is to be stored
30162 in the @code{Result} variable.
30163
30164 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30165 but with an @code{Asm_Input} attribute.
30166 The @code{"="} constraint, indicating an output value, is not present.
30167
30168 You can have multiple input variables, in the same way that you can have more
30169 than one output variable.
30170
30171 The parameter count (%0, %1) etc, now starts at the first input
30172 statement, and continues with the output statements.
30173 When both parameters use the same variable, the
30174 compiler will treat them as the same %n operand, which is the case here.
30175
30176 Just as the @code{Outputs} parameter causes the register to be stored into the
30177 target variable after execution of the assembler statements, so does the
30178 @code{Inputs} parameter cause its variable to be loaded into the register
30179 before execution of the assembler statements.
30180
30181 Thus the effect of the @code{Asm} invocation is:
30182 @enumerate
30183 @item load the 32-bit value of @code{Value} into eax
30184 @item execute the @code{incl %eax} instruction
30185 @item store the contents of eax into the @code{Result} variable
30186 @end enumerate
30187
30188 The resulting assembler file (with @option{-O2} optimization) contains:
30189 @smallexample
30190 @group
30191 _increment__incr.1:
30192    subl $4,%esp
30193    movl 8(%esp),%eax
30194 #APP
30195    incl %eax
30196 #NO_APP
30197    movl %eax,%edx
30198    movl %ecx,(%esp)
30199    addl $4,%esp
30200    ret
30201 @end group
30202 @end smallexample
30203
30204 @c ---------------------------------------------------------------------------
30205 @node Inlining Inline Assembler Code
30206 @section Inlining Inline Assembler Code
30207
30208 @noindent
30209 For a short subprogram such as the @code{Incr} function in the previous
30210 section, the overhead of the call and return (creating / deleting the stack
30211 frame) can be significant, compared to the amount of code in the subprogram
30212 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30213 which directs the compiler to expand invocations of the subprogram at the
30214 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30215 Here is the resulting program:
30216
30217 @smallexample @c ada
30218 @group
30219 with Interfaces; use Interfaces;
30220 with Ada.Text_IO; use Ada.Text_IO;
30221 with System.Machine_Code; use System.Machine_Code;
30222 procedure Increment_2 is
30223
30224    function Incr (Value : Unsigned_32) return Unsigned_32 is
30225       Result : Unsigned_32;
30226    begin
30227       Asm ("incl %0",
30228            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30229            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30230       return Result;
30231    end Incr;
30232    pragma Inline (Increment);
30233
30234    Value : Unsigned_32;
30235
30236 begin
30237    Value := 5;
30238    Put_Line ("Value before is" & Value'Img);
30239    Value := Increment (Value);
30240    Put_Line ("Value after is" & Value'Img);
30241 end Increment_2;
30242 @end group
30243 @end smallexample
30244
30245 Compile the program with both optimization (@option{-O2}) and inlining
30246 (@option{-gnatn}) enabled.
30247
30248 The @code{Incr} function is still compiled as usual, but at the
30249 point in @code{Increment} where our function used to be called:
30250
30251 @smallexample
30252 @group
30253 pushl %edi
30254 call _increment__incr.1
30255 @end group
30256 @end smallexample
30257
30258 @noindent
30259 the code for the function body directly appears:
30260
30261 @smallexample
30262 @group
30263 movl %esi,%eax
30264 #APP
30265    incl %eax
30266 #NO_APP
30267    movl %eax,%edx
30268 @end group
30269 @end smallexample
30270
30271 @noindent
30272 thus saving the overhead of stack frame setup and an out-of-line call.
30273
30274 @c ---------------------------------------------------------------------------
30275 @node Other Asm Functionality
30276 @section Other @code{Asm} Functionality
30277
30278 @noindent
30279 This section describes two important parameters to the @code{Asm}
30280 procedure: @code{Clobber}, which identifies register usage;
30281 and @code{Volatile}, which inhibits unwanted optimizations.
30282
30283 @menu
30284 * The Clobber Parameter::
30285 * The Volatile Parameter::
30286 @end menu
30287
30288 @c ---------------------------------------------------------------------------
30289 @node The Clobber Parameter
30290 @subsection The @code{Clobber} Parameter
30291
30292 @noindent
30293 One of the dangers of intermixing assembly language and a compiled language
30294 such as Ada is that the compiler needs to be aware of which registers are
30295 being used by the assembly code.  In some cases, such as the earlier examples,
30296 the constraint string is sufficient to indicate register usage (e.g.,
30297 @code{"a"} for
30298 the eax register).  But more generally, the compiler needs an explicit
30299 identification of the registers that are used by the Inline Assembly
30300 statements.
30301
30302 Using a register that the compiler doesn't know about
30303 could be a side effect of an instruction (like @code{mull}
30304 storing its result in both eax and edx).
30305 It can also arise from explicit register usage in your
30306 assembly code; for example:
30307 @smallexample
30308 @group
30309 Asm ("movl %0, %%ebx" & LF & HT &
30310      "movl %%ebx, %1",
30311      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30312      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30313 @end group
30314 @end smallexample
30315 @noindent
30316 where the compiler (since it does not analyze the @code{Asm} template string)
30317 does not know you are using the ebx register.
30318
30319 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30320 to identify the registers that will be used by your assembly code:
30321
30322 @smallexample
30323 @group
30324 Asm ("movl %0, %%ebx" & LF & HT &
30325      "movl %%ebx, %1",
30326      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30327      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30328      Clobber => "ebx");
30329 @end group
30330 @end smallexample
30331
30332 The Clobber parameter is a static string expression specifying the
30333 register(s) you are using.  Note that register names are @emph{not} prefixed
30334 by a percent sign. Also, if more than one register is used then their names
30335 are separated by commas; e.g., @code{"eax, ebx"}
30336
30337 The @code{Clobber} parameter has several additional uses:
30338 @enumerate
30339 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30340 @item Use ``register'' name @code{memory} if you changed a memory location
30341 @end enumerate
30342
30343 @c ---------------------------------------------------------------------------
30344 @node The Volatile Parameter
30345 @subsection The @code{Volatile} Parameter
30346 @cindex Volatile parameter
30347
30348 @noindent
30349 Compiler optimizations in the presence of Inline Assembler may sometimes have
30350 unwanted effects.  For example, when an @code{Asm} invocation with an input
30351 variable is inside a loop, the compiler might move the loading of the input
30352 variable outside the loop, regarding it as a one-time initialization.
30353
30354 If this effect is not desired, you can disable such optimizations by setting
30355 the @code{Volatile} parameter to @code{True}; for example:
30356
30357 @smallexample @c ada
30358 @group
30359 Asm ("movl %0, %%ebx" & LF & HT &
30360      "movl %%ebx, %1",
30361      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30362      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30363      Clobber  => "ebx",
30364      Volatile => True);
30365 @end group
30366 @end smallexample
30367
30368 By default, @code{Volatile} is set to @code{False} unless there is no
30369 @code{Outputs} parameter.
30370
30371 Although setting @code{Volatile} to @code{True} prevents unwanted
30372 optimizations, it will also disable other optimizations that might be
30373 important for efficiency. In general, you should set @code{Volatile}
30374 to @code{True} only if the compiler's optimizations have created
30375 problems.
30376 @c END OF INLINE ASSEMBLER CHAPTER
30377 @c ===============================
30378
30379 @c ***********************************
30380 @c * Compatibility and Porting Guide *
30381 @c ***********************************
30382 @node Compatibility and Porting Guide
30383 @appendix Compatibility and Porting Guide
30384
30385 @noindent
30386 This chapter describes the compatibility issues that may arise between
30387 GNAT and other Ada compilation systems (including those for Ada 83),
30388 and shows how GNAT can expedite porting
30389 applications developed in other Ada environments.
30390
30391 @menu
30392 * Compatibility with Ada 83::
30393 * Compatibility between Ada 95 and Ada 2005::
30394 * Implementation-dependent characteristics::
30395 * Compatibility with Other Ada Systems::
30396 * Representation Clauses::
30397 @ifclear vms
30398 @c Brief section is only in non-VMS version
30399 @c Full chapter is in VMS version
30400 * Compatibility with HP Ada 83::
30401 @end ifclear
30402 @ifset vms
30403 * Transitioning to 64-Bit GNAT for OpenVMS::
30404 @end ifset
30405 @end menu
30406
30407 @node Compatibility with Ada 83
30408 @section Compatibility with Ada 83
30409 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30410
30411 @noindent
30412 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30413 particular, the design intention was that the difficulties associated
30414 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30415 that occur when moving from one Ada 83 system to another.
30416
30417 However, there are a number of points at which there are minor
30418 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30419 full details of these issues,
30420 and should be consulted for a complete treatment.
30421 In practice the
30422 following subsections treat the most likely issues to be encountered.
30423
30424 @menu
30425 * Legal Ada 83 programs that are illegal in Ada 95::
30426 * More deterministic semantics::
30427 * Changed semantics::
30428 * Other language compatibility issues::
30429 @end menu
30430
30431 @node Legal Ada 83 programs that are illegal in Ada 95
30432 @subsection Legal Ada 83 programs that are illegal in Ada 95
30433
30434 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30435 Ada 95 and thus also in Ada 2005:
30436
30437 @table @emph
30438 @item Character literals
30439 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30440 @code{Wide_Character} as a new predefined character type, some uses of
30441 character literals that were legal in Ada 83 are illegal in Ada 95.
30442 For example:
30443 @smallexample @c ada
30444    for Char in 'A' .. 'Z' loop @dots{} end loop;
30445 @end smallexample
30446
30447 @noindent
30448 The problem is that @code{'A'} and @code{'Z'} could be from either
30449 @code{Character} or @code{Wide_Character}.  The simplest correction
30450 is to make the type explicit; e.g.:
30451 @smallexample @c ada
30452    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30453 @end smallexample
30454
30455 @item New reserved words
30456 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30457 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30458 Existing Ada 83 code using any of these identifiers must be edited to
30459 use some alternative name.
30460
30461 @item Freezing rules
30462 The rules in Ada 95 are slightly different with regard to the point at
30463 which entities are frozen, and representation pragmas and clauses are
30464 not permitted past the freeze point.  This shows up most typically in
30465 the form of an error message complaining that a representation item
30466 appears too late, and the appropriate corrective action is to move
30467 the item nearer to the declaration of the entity to which it refers.
30468
30469 A particular case is that representation pragmas
30470 @ifset vms
30471 (including the
30472 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30473 @end ifset
30474 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30475 declaration must be introduced to which the pragma can be applied.
30476
30477 @item Optional bodies for library packages
30478 In Ada 83, a package that did not require a package body was nevertheless
30479 allowed to have one.  This lead to certain surprises in compiling large
30480 systems (situations in which the body could be unexpectedly ignored by the
30481 binder).  In Ada 95, if a package does not require a body then it is not
30482 permitted to have a body.  To fix this problem, simply remove a redundant
30483 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30484 into the spec that makes the body required.  One approach is to add a private
30485 part to the package declaration (if necessary), and define a parameterless
30486 procedure called @code{Requires_Body}, which must then be given a dummy
30487 procedure body in the package body, which then becomes required.
30488 Another approach (assuming that this does not introduce elaboration
30489 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30490 since one effect of this pragma is to require the presence of a package body.
30491
30492 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30493 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30494 @code{Constraint_Error}.
30495 This means that it is illegal to have separate exception handlers for
30496 the two exceptions.  The fix is simply to remove the handler for the
30497 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30498 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30499
30500 @item Indefinite subtypes in generics
30501 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30502 as the actual for a generic formal private type, but then the instantiation
30503 would be illegal if there were any instances of declarations of variables
30504 of this type in the generic body.  In Ada 95, to avoid this clear violation
30505 of the methodological principle known as the ``contract model'',
30506 the generic declaration explicitly indicates whether
30507 or not such instantiations are permitted.  If a generic formal parameter
30508 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30509 type name, then it can be instantiated with indefinite types, but no
30510 stand-alone variables can be declared of this type.  Any attempt to declare
30511 such a variable will result in an illegality at the time the generic is
30512 declared.  If the @code{(<>)} notation is not used, then it is illegal
30513 to instantiate the generic with an indefinite type.
30514 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30515 It will show up as a compile time error, and
30516 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30517 @end table
30518
30519 @node More deterministic semantics
30520 @subsection More deterministic semantics
30521
30522 @table @emph
30523 @item Conversions
30524 Conversions from real types to integer types round away from 0.  In Ada 83
30525 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30526 implementation freedom was intended to support unbiased rounding in
30527 statistical applications, but in practice it interfered with portability.
30528 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30529 is required.  Numeric code may be affected by this change in semantics.
30530 Note, though, that this issue is no worse than already existed in Ada 83
30531 when porting code from one vendor to another.
30532
30533 @item Tasking
30534 The Real-Time Annex introduces a set of policies that define the behavior of
30535 features that were implementation dependent in Ada 83, such as the order in
30536 which open select branches are executed.
30537 @end table
30538
30539 @node Changed semantics
30540 @subsection Changed semantics
30541
30542 @noindent
30543 The worst kind of incompatibility is one where a program that is legal in
30544 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30545 possible in Ada 83.  Fortunately this is extremely rare, but the one
30546 situation that you should be alert to is the change in the predefined type
30547 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30548
30549 @table @emph
30550 @item Range of type @code{Character}
30551 The range of @code{Standard.Character} is now the full 256 characters
30552 of Latin-1, whereas in most Ada 83 implementations it was restricted
30553 to 128 characters. Although some of the effects of
30554 this change will be manifest in compile-time rejection of legal
30555 Ada 83 programs it is possible for a working Ada 83 program to have
30556 a different effect in Ada 95, one that was not permitted in Ada 83.
30557 As an example, the expression
30558 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30559 delivers @code{255} as its value.
30560 In general, you should look at the logic of any
30561 character-processing Ada 83 program and see whether it needs to be adapted
30562 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
30563 character handling package that may be relevant if code needs to be adapted
30564 to account for the additional Latin-1 elements.
30565 The desirable fix is to
30566 modify the program to accommodate the full character set, but in some cases
30567 it may be convenient to define a subtype or derived type of Character that
30568 covers only the restricted range.
30569 @cindex Latin-1
30570 @end table
30571
30572 @node Other language compatibility issues
30573 @subsection Other language compatibility issues
30574
30575 @table @emph
30576 @item @option{-gnat83} switch
30577 All implementations of GNAT provide a switch that causes GNAT to operate
30578 in Ada 83 mode.  In this mode, some but not all compatibility problems
30579 of the type described above are handled automatically.  For example, the
30580 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30581 as identifiers as in Ada 83.
30582 However,
30583 in practice, it is usually advisable to make the necessary modifications
30584 to the program to remove the need for using this switch.
30585 See @ref{Compiling Different Versions of Ada}.
30586
30587 @item Support for removed Ada 83 pragmas and attributes
30588 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30589 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
30590 compilers are allowed, but not required, to implement these missing
30591 elements.  In contrast with some other compilers, GNAT implements all
30592 such pragmas and attributes, eliminating this compatibility concern.  These
30593 include @code{pragma Interface} and the floating point type attributes
30594 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30595 @end table
30596
30597
30598 @node Compatibility between Ada 95 and Ada 2005
30599 @section Compatibility between Ada 95 and Ada 2005
30600 @cindex Compatibility between Ada 95 and Ada 2005
30601
30602 @noindent
30603 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30604 a number of incompatibilities. Several are enumerated below;
30605 for a complete description please see the
30606 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30607 @cite{Rationale for Ada 2005}.
30608
30609 @table @emph
30610 @item New reserved words.
30611 The words @code{interface}, @code{overriding} and @code{synchronized} are
30612 reserved in Ada 2005.
30613 A pre-Ada 2005 program that uses any of these as an identifier will be
30614 illegal.
30615
30616 @item New declarations in predefined packages.
30617 A number of packages in the predefined environment contain new declarations:
30618 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30619 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30620 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30621 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30622 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30623 If an Ada 95 program does a @code{with} and @code{use} of any of these
30624 packages, the new declarations may cause name clashes.
30625
30626 @item Access parameters.
30627 A nondispatching subprogram with an access parameter cannot be renamed
30628 as a dispatching operation.  This was permitted in Ada 95.
30629
30630 @item Access types, discriminants, and constraints.
30631 Rule changes in this area have led to some incompatibilities; for example,
30632 constrained subtypes of some access types are not permitted in Ada 2005.
30633
30634 @item Aggregates for limited types.
30635 The allowance of aggregates for limited types in Ada 2005 raises the
30636 possibility of ambiguities in legal Ada 95 programs, since additional types
30637 now need to be considered in expression resolution.
30638
30639 @item Fixed-point multiplication and division.
30640 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30641 were legal in Ada 95 and invoked the predefined versions of these operations,
30642 are now ambiguous.
30643 The ambiguity may be resolved either by applying a type conversion to the
30644 expression, or by explicitly invoking the operation from package
30645 @code{Standard}.
30646
30647 @item Return-by-reference types.
30648 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
30649 can declare a function returning a value from an anonymous access type.
30650 @end table
30651
30652
30653 @node Implementation-dependent characteristics
30654 @section Implementation-dependent characteristics
30655 @noindent
30656 Although the Ada language defines the semantics of each construct as
30657 precisely as practical, in some situations (for example for reasons of
30658 efficiency, or where the effect is heavily dependent on the host or target
30659 platform) the implementation is allowed some freedom.  In porting Ada 83
30660 code to GNAT, you need to be aware of whether / how the existing code
30661 exercised such implementation dependencies.  Such characteristics fall into
30662 several categories, and GNAT offers specific support in assisting the
30663 transition from certain Ada 83 compilers.
30664
30665 @menu
30666 * Implementation-defined pragmas::
30667 * Implementation-defined attributes::
30668 * Libraries::
30669 * Elaboration order::
30670 * Target-specific aspects::
30671 @end menu
30672
30673 @node Implementation-defined pragmas
30674 @subsection Implementation-defined pragmas
30675
30676 @noindent
30677 Ada compilers are allowed to supplement the language-defined pragmas, and
30678 these are a potential source of non-portability.  All GNAT-defined pragmas
30679 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30680 Reference Manual}, and these include several that are specifically
30681 intended to correspond to other vendors' Ada 83 pragmas.
30682 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30683 For compatibility with HP Ada 83, GNAT supplies the pragmas
30684 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30685 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30686 and @code{Volatile}.
30687 Other relevant pragmas include @code{External} and @code{Link_With}.
30688 Some vendor-specific
30689 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30690 recognized, thus
30691 avoiding compiler rejection of units that contain such pragmas; they are not
30692 relevant in a GNAT context and hence are not otherwise implemented.
30693
30694 @node Implementation-defined attributes
30695 @subsection Implementation-defined attributes
30696
30697 Analogous to pragmas, the set of attributes may be extended by an
30698 implementation.  All GNAT-defined attributes are described in
30699 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30700 Manual}, and these include several that are specifically intended
30701 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
30702 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
30703 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30704 @code{Type_Class}.
30705
30706 @node Libraries
30707 @subsection Libraries
30708 @noindent
30709 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
30710 code uses vendor-specific libraries then there are several ways to manage
30711 this in Ada 95 or Ada 2005:
30712 @enumerate
30713 @item
30714 If the source code for the libraries (specs and bodies) are
30715 available, then the libraries can be migrated in the same way as the
30716 application.
30717 @item
30718 If the source code for the specs but not the bodies are
30719 available, then you can reimplement the bodies.
30720 @item
30721 Some features introduced by Ada 95 obviate the need for library support.  For
30722 example most Ada 83 vendors supplied a package for unsigned integers.  The
30723 Ada 95 modular type feature is the preferred way to handle this need, so
30724 instead of migrating or reimplementing the unsigned integer package it may
30725 be preferable to retrofit the application using modular types.
30726 @end enumerate
30727
30728 @node Elaboration order
30729 @subsection Elaboration order
30730 @noindent
30731 The implementation can choose any elaboration order consistent with the unit
30732 dependency relationship.  This freedom means that some orders can result in
30733 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30734 to invoke a subprogram its body has been elaborated, or to instantiate a
30735 generic before the generic body has been elaborated.  By default GNAT
30736 attempts to choose a safe order (one that will not encounter access before
30737 elaboration problems) by implicitly inserting @code{Elaborate} or
30738 @code{Elaborate_All} pragmas where
30739 needed.  However, this can lead to the creation of elaboration circularities
30740 and a resulting rejection of the program by gnatbind.  This issue is
30741 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30742 In brief, there are several
30743 ways to deal with this situation:
30744
30745 @itemize @bullet
30746 @item
30747 Modify the program to eliminate the circularities, e.g.@: by moving
30748 elaboration-time code into explicitly-invoked procedures
30749 @item
30750 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30751 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30752 @code{Elaborate_All}
30753 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30754 (by selectively suppressing elaboration checks via pragma
30755 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30756 @end itemize
30757
30758 @node Target-specific aspects
30759 @subsection Target-specific aspects
30760 @noindent
30761 Low-level applications need to deal with machine addresses, data
30762 representations, interfacing with assembler code, and similar issues.  If
30763 such an Ada 83 application is being ported to different target hardware (for
30764 example where the byte endianness has changed) then you will need to
30765 carefully examine the program logic; the porting effort will heavily depend
30766 on the robustness of the original design.  Moreover, Ada 95 (and thus
30767 Ada 2005) are sometimes
30768 incompatible with typical Ada 83 compiler practices regarding implicit
30769 packing, the meaning of the Size attribute, and the size of access values.
30770 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30771
30772 @node Compatibility with Other Ada Systems
30773 @section Compatibility with Other Ada Systems
30774
30775 @noindent
30776 If programs avoid the use of implementation dependent and
30777 implementation defined features, as documented in the @cite{Ada
30778 Reference Manual}, there should be a high degree of portability between
30779 GNAT and other Ada systems.  The following are specific items which
30780 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30781 compilers, but do not affect porting code to GNAT@.
30782 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30783 the following issues may or may not arise for Ada 2005 programs
30784 when other compilers appear.)
30785
30786 @table @emph
30787 @item Ada 83 Pragmas and Attributes
30788 Ada 95 compilers are allowed, but not required, to implement the missing
30789 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30790 GNAT implements all such pragmas and attributes, eliminating this as
30791 a compatibility concern, but some other Ada 95 compilers reject these
30792 pragmas and attributes.
30793
30794 @item Specialized Needs Annexes
30795 GNAT implements the full set of special needs annexes.  At the
30796 current time, it is the only Ada 95 compiler to do so.  This means that
30797 programs making use of these features may not be portable to other Ada
30798 95 compilation systems.
30799
30800 @item Representation Clauses
30801 Some other Ada 95 compilers implement only the minimal set of
30802 representation clauses required by the Ada 95 reference manual.  GNAT goes
30803 far beyond this minimal set, as described in the next section.
30804 @end table
30805
30806 @node Representation Clauses
30807 @section Representation Clauses
30808
30809 @noindent
30810 The Ada 83 reference manual was quite vague in describing both the minimal
30811 required implementation of representation clauses, and also their precise
30812 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
30813 minimal set of capabilities required is still quite limited.
30814
30815 GNAT implements the full required set of capabilities in
30816 Ada 95 and Ada 2005, but also goes much further, and in particular
30817 an effort has been made to be compatible with existing Ada 83 usage to the
30818 greatest extent possible.
30819
30820 A few cases exist in which Ada 83 compiler behavior is incompatible with
30821 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
30822 intentional or accidental dependence on specific implementation dependent
30823 characteristics of these Ada 83 compilers.  The following is a list of
30824 the cases most likely to arise in existing Ada 83 code.
30825
30826 @table @emph
30827 @item Implicit Packing
30828 Some Ada 83 compilers allowed a Size specification to cause implicit
30829 packing of an array or record.  This could cause expensive implicit
30830 conversions for change of representation in the presence of derived
30831 types, and the Ada design intends to avoid this possibility.
30832 Subsequent AI's were issued to make it clear that such implicit
30833 change of representation in response to a Size clause is inadvisable,
30834 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30835 Reference Manuals as implementation advice that is followed by GNAT@.
30836 The problem will show up as an error
30837 message rejecting the size clause.  The fix is simply to provide
30838 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30839 a Component_Size clause.
30840
30841 @item Meaning of Size Attribute
30842 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30843 the minimal number of bits required to hold values of the type.  For example,
30844 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30845 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
30846 some 32 in this situation.  This problem will usually show up as a compile
30847 time error, but not always.  It is a good idea to check all uses of the
30848 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
30849 Object_Size can provide a useful way of duplicating the behavior of
30850 some Ada 83 compiler systems.
30851
30852 @item Size of Access Types
30853 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30854 and that therefore it will be the same size as a System.Address value.  This
30855 assumption is true for GNAT in most cases with one exception.  For the case of
30856 a pointer to an unconstrained array type (where the bounds may vary from one
30857 value of the access type to another), the default is to use a ``fat pointer'',
30858 which is represented as two separate pointers, one to the bounds, and one to
30859 the array.  This representation has a number of advantages, including improved
30860 efficiency.  However, it may cause some difficulties in porting existing Ada 83
30861 code which makes the assumption that, for example, pointers fit in 32 bits on
30862 a machine with 32-bit addressing.
30863
30864 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30865 access types in this case (where the designated type is an unconstrained array
30866 type).  These thin pointers are indeed the same size as a System.Address value.
30867 To specify a thin pointer, use a size clause for the type, for example:
30868
30869 @smallexample @c ada
30870 type X is access all String;
30871 for X'Size use Standard'Address_Size;
30872 @end smallexample
30873
30874 @noindent
30875 which will cause the type X to be represented using a single pointer.
30876 When using this representation, the bounds are right behind the array.
30877 This representation is slightly less efficient, and does not allow quite
30878 such flexibility in the use of foreign pointers or in using the
30879 Unrestricted_Access attribute to create pointers to non-aliased objects.
30880 But for any standard portable use of the access type it will work in
30881 a functionally correct manner and allow porting of existing code.
30882 Note that another way of forcing a thin pointer representation
30883 is to use a component size clause for the element size in an array,
30884 or a record representation clause for an access field in a record.
30885 @end table
30886
30887 @ifclear vms
30888 @c This brief section is only in the non-VMS version
30889 @c The complete chapter on HP Ada is in the VMS version
30890 @node Compatibility with HP Ada 83
30891 @section Compatibility with HP Ada 83
30892
30893 @noindent
30894 The VMS version of GNAT fully implements all the pragmas and attributes
30895 provided by HP Ada 83, as well as providing the standard HP Ada 83
30896 libraries, including Starlet.  In addition, data layouts and parameter
30897 passing conventions are highly compatible.  This means that porting
30898 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30899 most other porting efforts.  The following are some of the most
30900 significant differences between GNAT and HP Ada 83.
30901
30902 @table @emph
30903 @item Default floating-point representation
30904 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30905 it is VMS format.  GNAT does implement the necessary pragmas
30906 (Long_Float, Float_Representation) for changing this default.
30907
30908 @item System
30909 The package System in GNAT exactly corresponds to the definition in the
30910 Ada 95 reference manual, which means that it excludes many of the
30911 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
30912 that contains the additional definitions, and a special pragma,
30913 Extend_System allows this package to be treated transparently as an
30914 extension of package System.
30915
30916 @item To_Address
30917 The definitions provided by Aux_DEC are exactly compatible with those
30918 in the HP Ada 83 version of System, with one exception.
30919 HP Ada provides the following declarations:
30920
30921 @smallexample @c ada
30922 TO_ADDRESS (INTEGER)
30923 TO_ADDRESS (UNSIGNED_LONGWORD)
30924 TO_ADDRESS (@i{universal_integer})
30925 @end smallexample
30926
30927 @noindent
30928 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30929 an extension to Ada 83 not strictly compatible with the reference manual.
30930 In GNAT, we are constrained to be exactly compatible with the standard,
30931 and this means we cannot provide this capability.  In HP Ada 83, the
30932 point of this definition is to deal with a call like:
30933
30934 @smallexample @c ada
30935 TO_ADDRESS (16#12777#);
30936 @end smallexample
30937
30938 @noindent
30939 Normally, according to the Ada 83 standard, one would expect this to be
30940 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30941 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
30942 definition using @i{universal_integer} takes precedence.
30943
30944 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30945 is not possible to be 100% compatible.  Since there are many programs using
30946 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30947 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30948 declarations provided in the GNAT version of AUX_Dec are:
30949
30950 @smallexample @c ada
30951 function To_Address (X : Integer) return Address;
30952 pragma Pure_Function (To_Address);
30953
30954 function To_Address_Long (X : Unsigned_Longword)
30955  return Address;
30956 pragma Pure_Function (To_Address_Long);
30957 @end smallexample
30958
30959 @noindent
30960 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30961 change the name to TO_ADDRESS_LONG@.
30962
30963 @item Task_Id values
30964 The Task_Id values assigned will be different in the two systems, and GNAT
30965 does not provide a specified value for the Task_Id of the environment task,
30966 which in GNAT is treated like any other declared task.
30967 @end table
30968
30969 @noindent
30970 For full details on these and other less significant compatibility issues,
30971 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30972 Overview and Comparison on HP Platforms}.
30973
30974 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30975 attributes are recognized, although only a subset of them can sensibly
30976 be implemented.  The description of pragmas in @ref{Implementation
30977 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30978 indicates whether or not they are applicable to non-VMS systems.
30979 @end ifclear
30980
30981 @ifset vms
30982 @node Transitioning to 64-Bit GNAT for OpenVMS
30983 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30984
30985 @noindent
30986 This section is meant to assist users of pre-2006 @value{EDITION}
30987 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30988 the version of the GNAT technology supplied in 2006 and later for
30989 OpenVMS on both Alpha and I64.
30990
30991 @menu
30992 * Introduction to transitioning::
30993 * Migration of 32 bit code::
30994 * Taking advantage of 64 bit addressing::
30995 * Technical details::
30996 @end menu
30997
30998 @node Introduction to transitioning
30999 @subsection Introduction
31000
31001 @noindent
31002 64-bit @value{EDITION} for Open VMS has been designed to meet
31003 three main goals:
31004
31005 @enumerate
31006 @item
31007 Providing a full conforming implementation of Ada 95 and Ada 2005
31008
31009 @item
31010 Allowing maximum backward compatibility, thus easing migration of existing
31011 Ada source code
31012
31013 @item
31014 Supplying a path for exploiting the full 64-bit address range
31015 @end enumerate
31016
31017 @noindent
31018 Ada's strong typing semantics has made it
31019 impractical to have different 32-bit and 64-bit modes. As soon as
31020 one object could possibly be outside the 32-bit address space, this
31021 would make it necessary for the @code{System.Address} type to be 64 bits.
31022 In particular, this would cause inconsistencies if 32-bit code is
31023 called from 64-bit code that raises an exception.
31024
31025 This issue has been resolved by always using 64-bit addressing
31026 at the system level, but allowing for automatic conversions between
31027 32-bit and 64-bit addresses where required. Thus users who
31028 do not currently require 64-bit addressing capabilities, can
31029 recompile their code with only minimal changes (and indeed
31030 if the code is written in portable Ada, with no assumptions about
31031 the size of the @code{Address} type, then no changes at all are necessary).
31032 At the same time,
31033 this approach provides a simple, gradual upgrade path to future
31034 use of larger memories than available for 32-bit systems.
31035 Also, newly written applications or libraries will by default
31036 be fully compatible with future systems exploiting 64-bit
31037 addressing capabilities.
31038
31039 @ref{Migration of 32 bit code}, will focus on porting applications
31040 that do not require more than 2 GB of
31041 addressable memory. This code will be referred to as
31042 @emph{32-bit code}.
31043 For applications intending to exploit the full 64-bit address space,
31044 @ref{Taking advantage of 64 bit addressing},
31045 will consider further changes that may be required.
31046 Such code will be referred to below as @emph{64-bit code}.
31047
31048 @node Migration of 32 bit code
31049 @subsection Migration of 32-bit code
31050
31051 @menu
31052 * Address types::
31053 * Access types::
31054 * Unchecked conversions::
31055 * Predefined constants::
31056 * Interfacing with C::
31057 * Experience with source compatibility::
31058 @end menu
31059
31060 @node Address types
31061 @subsubsection Address types
31062
31063 @noindent
31064 To solve the problem of mixing 64-bit and 32-bit addressing,
31065 while maintaining maximum backward compatibility, the following
31066 approach has been taken:
31067
31068 @itemize @bullet
31069 @item
31070 @code{System.Address} always has a size of 64 bits
31071
31072 @item
31073 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31074 @end itemize
31075
31076 @noindent
31077 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31078 a @code{Short_Address}
31079 may be used where an @code{Address} is required, and vice versa, without
31080 needing explicit type conversions.
31081 By virtue of the Open VMS parameter passing conventions,
31082 even imported
31083 and exported subprograms that have 32-bit address parameters are
31084 compatible with those that have 64-bit address parameters.
31085 (See @ref{Making code 64 bit clean} for details.)
31086
31087 The areas that may need attention are those where record types have
31088 been defined that contain components of the type @code{System.Address}, and
31089 where objects of this type are passed to code expecting a record layout with
31090 32-bit addresses.
31091
31092 Different compilers on different platforms cannot be
31093 expected to represent the same type in the same way,
31094 since alignment constraints
31095 and other system-dependent properties affect the compiler's decision.
31096 For that reason, Ada code
31097 generally uses representation clauses to specify the expected
31098 layout where required.
31099
31100 If such a representation clause uses 32 bits for a component having
31101 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31102 will detect that error and produce a specific diagnostic message.
31103 The developer should then determine whether the representation
31104 should be 64 bits or not and make either of two changes:
31105 change the size to 64 bits and leave the type as @code{System.Address}, or
31106 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31107 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31108 required in any code setting or accessing the field; the compiler will
31109 automatically perform any needed conversions between address
31110 formats.
31111
31112 @node Access types
31113 @subsubsection Access types
31114
31115 @noindent
31116 By default, objects designated by access values are always
31117 allocated in the 32-bit
31118 address space. Thus legacy code will never contain
31119 any objects that are not addressable with 32-bit addresses, and
31120 the compiler will never raise exceptions as result of mixing
31121 32-bit and 64-bit addresses.
31122
31123 However, the access values themselves are represented in 64 bits, for optimum
31124 performance and future compatibility with 64-bit code. As was
31125 the case with @code{System.Address}, the compiler will give an error message
31126 if an object or record component has a representation clause that
31127 requires the access value to fit in 32 bits. In such a situation,
31128 an explicit size clause for the access type, specifying 32 bits,
31129 will have the desired effect.
31130
31131 General access types (declared with @code{access all}) can never be
31132 32 bits, as values of such types must be able to refer to any object
31133 of the  designated type,
31134 including objects residing outside the 32-bit address range.
31135 Existing Ada 83 code will not contain such type definitions,
31136 however, since general access types were introduced in Ada 95.
31137
31138 @node Unchecked conversions
31139 @subsubsection Unchecked conversions
31140
31141 @noindent
31142 In the case of an @code{Unchecked_Conversion} where the source type is a
31143 64-bit access type or the type @code{System.Address}, and the target
31144 type is a 32-bit type, the compiler will generate a warning.
31145 Even though the generated code will still perform the required
31146 conversions, it is highly recommended in these cases to use
31147 respectively a 32-bit access type or @code{System.Short_Address}
31148 as the source type.
31149
31150 @node Predefined constants
31151 @subsubsection Predefined constants
31152
31153 @noindent
31154 The following table shows the correspondence between pre-2006 versions of
31155 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31156 (``New''):
31157
31158 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31159 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31160 @item   @code{System.Word_Size}          @tab 32      @tab 64
31161 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31162 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31163 @item   @code{System.Address_Size}       @tab 32      @tab 64
31164 @end multitable
31165
31166 @noindent
31167 If you need to refer to the specific
31168 memory size of a 32-bit implementation, instead of the
31169 actual memory size, use @code{System.Short_Memory_Size}
31170 rather than @code{System.Memory_Size}.
31171 Similarly, references to @code{System.Address_Size} may need
31172 to be replaced by @code{System.Short_Address'Size}.
31173 The program @command{gnatfind} may be useful for locating
31174 references to the above constants, so that you can verify that they
31175 are still correct.
31176
31177 @node Interfacing with C
31178 @subsubsection Interfacing with C
31179
31180 @noindent
31181 In order to minimize the impact of the transition to 64-bit addresses on
31182 legacy programs, some fundamental types in the @code{Interfaces.C}
31183 package hierarchy continue to be represented in 32 bits.
31184 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31185 This eases integration with the default HP C layout choices, for example
31186 as found in the system routines in @code{DECC$SHR.EXE}.
31187 Because of this implementation choice, the type fully compatible with
31188 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31189 Depending on the context the compiler will issue a
31190 warning or an error when type @code{Address} is used, alerting the user to a
31191 potential problem. Otherwise 32-bit programs that use
31192 @code{Interfaces.C} should normally not require code modifications
31193
31194 The other issue arising with C interfacing concerns pragma @code{Convention}.
31195 For VMS 64-bit systems, there is an issue of the appropriate default size
31196 of C convention pointers in the absence of an explicit size clause. The HP
31197 C compiler can choose either 32 or 64 bits depending on compiler options.
31198 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31199 clause is given. This proves a better choice for porting 32-bit legacy
31200 applications. In order to have a 64-bit representation, it is necessary to
31201 specify a size representation clause. For example:
31202
31203 @smallexample @c ada
31204 type int_star is access Interfaces.C.int;
31205 pragma Convention(C, int_star);
31206 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31207 @end smallexample
31208
31209 @node Experience with source compatibility
31210 @subsubsection Experience with source compatibility
31211
31212 @noindent
31213 The Security Server and STARLET on I64 provide an interesting ``test case''
31214 for source compatibility issues, since it is in such system code
31215 where assumptions about @code{Address} size might be expected to occur.
31216 Indeed, there were a small number of occasions in the Security Server
31217 file @file{jibdef.ads}
31218 where a representation clause for a record type specified
31219 32 bits for a component of type @code{Address}.
31220 All of these errors were detected by the compiler.
31221 The repair was obvious and immediate; to simply replace @code{Address} by
31222 @code{Short_Address}.
31223
31224 In the case of STARLET, there were several record types that should
31225 have had representation clauses but did not.  In these record types
31226 there was an implicit assumption that an @code{Address} value occupied
31227 32 bits.
31228 These compiled without error, but their usage resulted in run-time error
31229 returns from STARLET system calls.
31230 Future GNAT technology enhancements may include a tool that detects and flags
31231 these sorts of potential source code porting problems.
31232
31233 @c ****************************************
31234 @node Taking advantage of 64 bit addressing
31235 @subsection Taking advantage of 64-bit addressing
31236
31237 @menu
31238 * Making code 64 bit clean::
31239 * Allocating memory from the 64 bit storage pool::
31240 * Restrictions on use of 64 bit objects::
31241 * Using 64 bit storage pools by default::
31242 * General access types::
31243 * STARLET and other predefined libraries::
31244 @end menu
31245
31246 @node Making code 64 bit clean
31247 @subsubsection Making code 64-bit clean
31248
31249 @noindent
31250 In order to prevent problems that may occur when (parts of) a
31251 system start using memory outside the 32-bit address range,
31252 we recommend some additional guidelines:
31253
31254 @itemize @bullet
31255 @item
31256 For imported subprograms that take parameters of the
31257 type @code{System.Address}, ensure that these subprograms can
31258 indeed handle 64-bit addresses. If not, or when in doubt,
31259 change the subprogram declaration to specify
31260 @code{System.Short_Address} instead.
31261
31262 @item
31263 Resolve all warnings related to size mismatches in
31264 unchecked conversions. Failing to do so causes
31265 erroneous execution if the source object is outside
31266 the 32-bit address space.
31267
31268 @item
31269 (optional) Explicitly use the 32-bit storage pool
31270 for access types used in a 32-bit context, or use
31271 generic access types where possible
31272 (@pxref{Restrictions on use of 64 bit objects}).
31273 @end itemize
31274
31275 @noindent
31276 If these rules are followed, the compiler will automatically insert
31277 any necessary checks to ensure that no addresses or access values
31278 passed to 32-bit code ever refer to objects outside the 32-bit
31279 address range.
31280 Any attempt to do this will raise @code{Constraint_Error}.
31281
31282 @node Allocating memory from the 64 bit storage pool
31283 @subsubsection Allocating memory from the 64-bit storage pool
31284
31285 @noindent
31286 For any access type @code{T} that potentially requires memory allocations
31287 beyond the 32-bit address space,
31288 use the following representation clause:
31289
31290 @smallexample @c ada
31291    for T'Storage_Pool use System.Pool_64;
31292 @end smallexample
31293
31294 @node Restrictions on use of 64 bit objects
31295 @subsubsection Restrictions on use of 64-bit objects
31296
31297 @noindent
31298 Taking the address of an object allocated from a 64-bit storage pool,
31299 and then passing this address to a subprogram expecting
31300 @code{System.Short_Address},
31301 or assigning it to a variable of type @code{Short_Address}, will cause
31302 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31303 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31304 no exception is raised and execution
31305 will become erroneous.
31306
31307 @node Using 64 bit storage pools by default
31308 @subsubsection Using 64-bit storage pools by default
31309
31310 @noindent
31311 In some cases it may be desirable to have the compiler allocate
31312 from 64-bit storage pools by default. This may be the case for
31313 libraries that are 64-bit clean, but may be used in both 32-bit
31314 and 64-bit contexts. For these cases the following configuration
31315 pragma may be specified:
31316
31317 @smallexample @c ada
31318   pragma Pool_64_Default;
31319 @end smallexample
31320
31321 @noindent
31322 Any code compiled in the context of this pragma will by default
31323 use the @code{System.Pool_64} storage pool. This default may be overridden
31324 for a specific access type @code{T} by the representation clause:
31325
31326 @smallexample @c ada
31327    for T'Storage_Pool use System.Pool_32;
31328 @end smallexample
31329
31330 @noindent
31331 Any object whose address may be passed to a subprogram with a
31332 @code{Short_Address} argument, or assigned to a variable of type
31333 @code{Short_Address}, needs to be allocated from this pool.
31334
31335 @node General access types
31336 @subsubsection General access types
31337
31338 @noindent
31339 Objects designated by access values from a
31340 general access type (declared with @code{access all}) are never allocated
31341 from a 64-bit storage pool. Code that uses general access types will
31342 accept objects allocated in either 32-bit or 64-bit address spaces,
31343 but never allocate objects outside the 32-bit address space.
31344 Using general access types ensures maximum compatibility with both
31345 32-bit and 64-bit code.
31346
31347 @node STARLET and other predefined libraries
31348 @subsubsection STARLET and other predefined libraries
31349
31350 @noindent
31351 All code that comes as part of GNAT is 64-bit clean, but the
31352 restrictions given in @ref{Restrictions on use of 64 bit objects},
31353 still apply. Look at the package
31354 specs to see in which contexts objects allocated
31355 in 64-bit address space are acceptable.
31356
31357 @node Technical details
31358 @subsection Technical details
31359
31360 @noindent
31361 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31362 Ada standard with respect to the type of @code{System.Address}. Previous
31363 versions of GNAT Pro have defined this type as private and implemented it as a
31364 modular type.
31365
31366 In order to allow defining @code{System.Short_Address} as a proper subtype,
31367 and to match the implicit sign extension in parameter passing,
31368 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31369 visible (i.e., non-private) integer type.
31370 Standard operations on the type, such as the binary operators ``+'', ``-'',
31371 etc., that take @code{Address} operands and return an @code{Address} result,
31372 have been hidden by declaring these
31373 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31374 ambiguities that would otherwise result from overloading.
31375 (Note that, although @code{Address} is a visible integer type,
31376 good programming practice dictates against exploiting the type's
31377 integer properties such as literals, since this will compromise
31378 code portability.)
31379
31380 Defining @code{Address} as a visible integer type helps achieve
31381 maximum compatibility for existing Ada code,
31382 without sacrificing the capabilities of the 64-bit architecture.
31383 @end ifset
31384
31385 @c ************************************************
31386 @ifset unw
31387 @node Microsoft Windows Topics
31388 @appendix Microsoft Windows Topics
31389 @cindex Windows NT
31390 @cindex Windows 95
31391 @cindex Windows 98
31392
31393 @noindent
31394 This chapter describes topics that are specific to the Microsoft Windows
31395 platforms (NT, 2000, and XP Professional).
31396
31397 @menu
31398 * Using GNAT on Windows::
31399 * Using a network installation of GNAT::
31400 * CONSOLE and WINDOWS subsystems::
31401 * Temporary Files::
31402 * Mixed-Language Programming on Windows::
31403 * Windows Calling Conventions::
31404 * Introduction to Dynamic Link Libraries (DLLs)::
31405 * Using DLLs with GNAT::
31406 * Building DLLs with GNAT::
31407 * Building DLLs with GNAT Project files::
31408 * Building DLLs with gnatdll::
31409 * GNAT and Windows Resources::
31410 * Debugging a DLL::
31411 * Setting Stack Size from gnatlink::
31412 * Setting Heap Size from gnatlink::
31413 @end menu
31414
31415 @node Using GNAT on Windows
31416 @section Using GNAT on Windows
31417
31418 @noindent
31419 One of the strengths of the GNAT technology is that its tool set
31420 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31421 @code{gdb} debugger, etc.) is used in the same way regardless of the
31422 platform.
31423
31424 On Windows this tool set is complemented by a number of Microsoft-specific
31425 tools that have been provided to facilitate interoperability with Windows
31426 when this is required. With these tools:
31427
31428 @itemize @bullet
31429
31430 @item
31431 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31432 subsystems.
31433
31434 @item
31435 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31436 relocatable and non-relocatable DLLs are supported).
31437
31438 @item
31439 You can build Ada DLLs for use in other applications. These applications
31440 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31441 relocatable and non-relocatable Ada DLLs are supported.
31442
31443 @item
31444 You can include Windows resources in your Ada application.
31445
31446 @item
31447 You can use or create COM/DCOM objects.
31448 @end itemize
31449
31450 @noindent
31451 Immediately below are listed all known general GNAT-for-Windows restrictions.
31452 Other restrictions about specific features like Windows Resources and DLLs
31453 are listed in separate sections below.
31454
31455 @itemize @bullet
31456
31457 @item
31458 It is not possible to use @code{GetLastError} and @code{SetLastError}
31459 when tasking, protected records, or exceptions are used. In these
31460 cases, in order to implement Ada semantics, the GNAT run-time system
31461 calls certain Win32 routines that set the last error variable to 0 upon
31462 success. It should be possible to use @code{GetLastError} and
31463 @code{SetLastError} when tasking, protected record, and exception
31464 features are not used, but it is not guaranteed to work.
31465
31466 @item
31467 It is not possible to link against Microsoft libraries except for
31468 import libraries. The library must be built to be compatible with
31469 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31470 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31471 not be compatible with the GNAT runtime. Even if the library is
31472 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31473
31474 @item
31475 When the compilation environment is located on FAT32 drives, users may
31476 experience recompilations of the source files that have not changed if
31477 Daylight Saving Time (DST) state has changed since the last time files
31478 were compiled. NTFS drives do not have this problem.
31479
31480 @item
31481 No components of the GNAT toolset use any entries in the Windows
31482 registry. The only entries that can be created are file associations and
31483 PATH settings, provided the user has chosen to create them at installation
31484 time, as well as some minimal book-keeping information needed to correctly
31485 uninstall or integrate different GNAT products.
31486 @end itemize
31487
31488 @node Using a network installation of GNAT
31489 @section Using a network installation of GNAT
31490
31491 @noindent
31492 Make sure the system on which GNAT is installed is accessible from the
31493 current machine, i.e., the install location is shared over the network.
31494 Shared resources are accessed on Windows by means of UNC paths, which
31495 have the format @code{\\server\sharename\path}
31496
31497 In order to use such a network installation, simply add the UNC path of the
31498 @file{bin} directory of your GNAT installation in front of your PATH. For
31499 example, if GNAT is installed in @file{\GNAT} directory of a share location
31500 called @file{c-drive} on a machine @file{LOKI}, the following command will
31501 make it available:
31502
31503 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31504
31505 Be aware that every compilation using the network installation results in the
31506 transfer of large amounts of data across the network and will likely cause
31507 serious performance penalty.
31508
31509 @node CONSOLE and WINDOWS subsystems
31510 @section CONSOLE and WINDOWS subsystems
31511 @cindex CONSOLE Subsystem
31512 @cindex WINDOWS Subsystem
31513 @cindex -mwindows
31514
31515 @noindent
31516 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31517 (which is the default subsystem) will always create a console when
31518 launching the application. This is not something desirable when the
31519 application has a Windows GUI. To get rid of this console the
31520 application must be using the @code{WINDOWS} subsystem. To do so
31521 the @option{-mwindows} linker option must be specified.
31522
31523 @smallexample
31524 $ gnatmake winprog -largs -mwindows
31525 @end smallexample
31526
31527 @node Temporary Files
31528 @section Temporary Files
31529 @cindex Temporary files
31530
31531 @noindent
31532 It is possible to control where temporary files gets created by setting
31533 the @env{TMP} environment variable. The file will be created:
31534
31535 @itemize
31536 @item Under the directory pointed to by the @env{TMP} environment variable if
31537 this directory exists.
31538
31539 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31540 set (or not pointing to a directory) and if this directory exists.
31541
31542 @item Under the current working directory otherwise.
31543 @end itemize
31544
31545 @noindent
31546 This allows you to determine exactly where the temporary
31547 file will be created. This is particularly useful in networked
31548 environments where you may not have write access to some
31549 directories.
31550
31551 @node Mixed-Language Programming on Windows
31552 @section Mixed-Language Programming on Windows
31553
31554 @noindent
31555 Developing pure Ada applications on Windows is no different than on
31556 other GNAT-supported platforms. However, when developing or porting an
31557 application that contains a mix of Ada and C/C++, the choice of your
31558 Windows C/C++ development environment conditions your overall
31559 interoperability strategy.
31560
31561 If you use @command{gcc} to compile the non-Ada part of your application,
31562 there are no Windows-specific restrictions that affect the overall
31563 interoperability with your Ada code. If you plan to use
31564 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31565 the following limitations:
31566
31567 @itemize @bullet
31568 @item
31569 You cannot link your Ada code with an object or library generated with
31570 Microsoft tools if these use the @code{.tls} section (Thread Local
31571 Storage section) since the GNAT linker does not yet support this section.
31572
31573 @item
31574 You cannot link your Ada code with an object or library generated with
31575 Microsoft tools if these use I/O routines other than those provided in
31576 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31577 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31578 libraries can cause a conflict with @code{msvcrt.dll} services. For
31579 instance Visual C++ I/O stream routines conflict with those in
31580 @code{msvcrt.dll}.
31581 @end itemize
31582
31583 @noindent
31584 If you do want to use the Microsoft tools for your non-Ada code and hit one
31585 of the above limitations, you have two choices:
31586
31587 @enumerate
31588 @item
31589 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31590 application. In this case, use the Microsoft or whatever environment to
31591 build the DLL and use GNAT to build your executable
31592 (@pxref{Using DLLs with GNAT}).
31593
31594 @item
31595 Or you can encapsulate your Ada code in a DLL to be linked with the
31596 other part of your application. In this case, use GNAT to build the DLL
31597 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31598 environment to build your executable.
31599 @end enumerate
31600
31601 @node Windows Calling Conventions
31602 @section Windows Calling Conventions
31603 @findex Stdcall
31604 @findex APIENTRY
31605
31606 @menu
31607 * C Calling Convention::
31608 * Stdcall Calling Convention::
31609 * Win32 Calling Convention::
31610 * DLL Calling Convention::
31611 @end menu
31612
31613 @noindent
31614 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31615 (callee), there are several ways to push @code{G}'s parameters on the
31616 stack and there are several possible scenarios to clean up the stack
31617 upon @code{G}'s return. A calling convention is an agreed upon software
31618 protocol whereby the responsibilities between the caller (@code{F}) and
31619 the callee (@code{G}) are clearly defined. Several calling conventions
31620 are available for Windows:
31621
31622 @itemize @bullet
31623 @item
31624 @code{C} (Microsoft defined)
31625
31626 @item
31627 @code{Stdcall} (Microsoft defined)
31628
31629 @item
31630 @code{Win32} (GNAT specific)
31631
31632 @item
31633 @code{DLL} (GNAT specific)
31634 @end itemize
31635
31636 @node C Calling Convention
31637 @subsection @code{C} Calling Convention
31638
31639 @noindent
31640 This is the default calling convention used when interfacing to C/C++
31641 routines compiled with either @command{gcc} or Microsoft Visual C++.
31642
31643 In the @code{C} calling convention subprogram parameters are pushed on the
31644 stack by the caller from right to left. The caller itself is in charge of
31645 cleaning up the stack after the call. In addition, the name of a routine
31646 with @code{C} calling convention is mangled by adding a leading underscore.
31647
31648 The name to use on the Ada side when importing (or exporting) a routine
31649 with @code{C} calling convention is the name of the routine. For
31650 instance the C function:
31651
31652 @smallexample
31653 int get_val (long);
31654 @end smallexample
31655
31656 @noindent
31657 should be imported from Ada as follows:
31658
31659 @smallexample @c ada
31660 @group
31661 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31662 pragma Import (C, Get_Val, External_Name => "get_val");
31663 @end group
31664 @end smallexample
31665
31666 @noindent
31667 Note that in this particular case the @code{External_Name} parameter could
31668 have been omitted since, when missing, this parameter is taken to be the
31669 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31670 is missing, as in the above example, this parameter is set to be the
31671 @code{External_Name} with a leading underscore.
31672
31673 When importing a variable defined in C, you should always use the @code{C}
31674 calling convention unless the object containing the variable is part of a
31675 DLL (in which case you should use the @code{Stdcall} calling
31676 convention, @pxref{Stdcall Calling Convention}).
31677
31678 @node Stdcall Calling Convention
31679 @subsection @code{Stdcall} Calling Convention
31680
31681 @noindent
31682 This convention, which was the calling convention used for Pascal
31683 programs, is used by Microsoft for all the routines in the Win32 API for
31684 efficiency reasons. It must be used to import any routine for which this
31685 convention was specified.
31686
31687 In the @code{Stdcall} calling convention subprogram parameters are pushed
31688 on the stack by the caller from right to left. The callee (and not the
31689 caller) is in charge of cleaning the stack on routine exit. In addition,
31690 the name of a routine with @code{Stdcall} calling convention is mangled by
31691 adding a leading underscore (as for the @code{C} calling convention) and a
31692 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31693 bytes) of the parameters passed to the routine.
31694
31695 The name to use on the Ada side when importing a C routine with a
31696 @code{Stdcall} calling convention is the name of the C routine. The leading
31697 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31698 the compiler. For instance the Win32 function:
31699
31700 @smallexample
31701 @b{APIENTRY} int get_val (long);
31702 @end smallexample
31703
31704 @noindent
31705 should be imported from Ada as follows:
31706
31707 @smallexample @c ada
31708 @group
31709 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31710 pragma Import (Stdcall, Get_Val);
31711 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31712 @end group
31713 @end smallexample
31714
31715 @noindent
31716 As for the @code{C} calling convention, when the @code{External_Name}
31717 parameter is missing, it is taken to be the name of the Ada entity in lower
31718 case. If instead of writing the above import pragma you write:
31719
31720 @smallexample @c ada
31721 @group
31722 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31723 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31724 @end group
31725 @end smallexample
31726
31727 @noindent
31728 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31729 of specifying the @code{External_Name} parameter you specify the
31730 @code{Link_Name} as in the following example:
31731
31732 @smallexample @c ada
31733 @group
31734 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31735 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31736 @end group
31737 @end smallexample
31738
31739 @noindent
31740 then the imported routine is @code{retrieve_val}, that is, there is no
31741 decoration at all. No leading underscore and no Stdcall suffix
31742 @code{@@}@code{@var{nn}}.
31743
31744 @noindent
31745 This is especially important as in some special cases a DLL's entry
31746 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31747 name generated for a call has it.
31748
31749 @noindent
31750 It is also possible to import variables defined in a DLL by using an
31751 import pragma for a variable. As an example, if a DLL contains a
31752 variable defined as:
31753
31754 @smallexample
31755 int my_var;
31756 @end smallexample
31757
31758 @noindent
31759 then, to access this variable from Ada you should write:
31760
31761 @smallexample @c ada
31762 @group
31763 My_Var : Interfaces.C.int;
31764 pragma Import (Stdcall, My_Var);
31765 @end group
31766 @end smallexample
31767
31768 @noindent
31769 Note that to ease building cross-platform bindings this convention
31770 will be handled as a @code{C} calling convention on non-Windows platforms.
31771
31772 @node Win32 Calling Convention
31773 @subsection @code{Win32} Calling Convention
31774
31775 @noindent
31776 This convention, which is GNAT-specific is fully equivalent to the
31777 @code{Stdcall} calling convention described above.
31778
31779 @node DLL Calling Convention
31780 @subsection @code{DLL} Calling Convention
31781
31782 @noindent
31783 This convention, which is GNAT-specific is fully equivalent to the
31784 @code{Stdcall} calling convention described above.
31785
31786 @node Introduction to Dynamic Link Libraries (DLLs)
31787 @section Introduction to Dynamic Link Libraries (DLLs)
31788 @findex DLL
31789
31790 @noindent
31791 A Dynamically Linked Library (DLL) is a library that can be shared by
31792 several applications running under Windows. A DLL can contain any number of
31793 routines and variables.
31794
31795 One advantage of DLLs is that you can change and enhance them without
31796 forcing all the applications that depend on them to be relinked or
31797 recompiled. However, you should be aware than all calls to DLL routines are
31798 slower since, as you will understand below, such calls are indirect.
31799
31800 To illustrate the remainder of this section, suppose that an application
31801 wants to use the services of a DLL @file{API.dll}. To use the services
31802 provided by @file{API.dll} you must statically link against the DLL or
31803 an import library which contains a jump table with an entry for each
31804 routine and variable exported by the DLL. In the Microsoft world this
31805 import library is called @file{API.lib}. When using GNAT this import
31806 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31807 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31808
31809 After you have linked your application with the DLL or the import library
31810 and you run your application, here is what happens:
31811
31812 @enumerate
31813 @item
31814 Your application is loaded into memory.
31815
31816 @item
31817 The DLL @file{API.dll} is mapped into the address space of your
31818 application. This means that:
31819
31820 @itemize @bullet
31821 @item
31822 The DLL will use the stack of the calling thread.
31823
31824 @item
31825 The DLL will use the virtual address space of the calling process.
31826
31827 @item
31828 The DLL will allocate memory from the virtual address space of the calling
31829 process.
31830
31831 @item
31832 Handles (pointers) can be safely exchanged between routines in the DLL
31833 routines and routines in the application using the DLL.
31834 @end itemize
31835
31836 @item
31837 The entries in the jump table (from the import library @file{libAPI.dll.a}
31838 or @file{API.lib} or automatically created when linking against a DLL)
31839 which is part of your application are initialized with the addresses
31840 of the routines and variables in @file{API.dll}.
31841
31842 @item
31843 If present in @file{API.dll}, routines @code{DllMain} or
31844 @code{DllMainCRTStartup} are invoked. These routines typically contain
31845 the initialization code needed for the well-being of the routines and
31846 variables exported by the DLL.
31847 @end enumerate
31848
31849 @noindent
31850 There is an additional point which is worth mentioning. In the Windows
31851 world there are two kind of DLLs: relocatable and non-relocatable
31852 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31853 in the target application address space. If the addresses of two
31854 non-relocatable DLLs overlap and these happen to be used by the same
31855 application, a conflict will occur and the application will run
31856 incorrectly. Hence, when possible, it is always preferable to use and
31857 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31858 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31859 User's Guide) removes the debugging symbols from the DLL but the DLL can
31860 still be relocated.
31861
31862 As a side note, an interesting difference between Microsoft DLLs and
31863 Unix shared libraries, is the fact that on most Unix systems all public
31864 routines are exported by default in a Unix shared library, while under
31865 Windows it is possible (but not required) to list exported routines in
31866 a definition file (@pxref{The Definition File}).
31867
31868 @node Using DLLs with GNAT
31869 @section Using DLLs with GNAT
31870
31871 @menu
31872 * Creating an Ada Spec for the DLL Services::
31873 * Creating an Import Library::
31874 @end menu
31875
31876 @noindent
31877 To use the services of a DLL, say @file{API.dll}, in your Ada application
31878 you must have:
31879
31880 @enumerate
31881 @item
31882 The Ada spec for the routines and/or variables you want to access in
31883 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31884 header files provided with the DLL.
31885
31886 @item
31887 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31888 mentioned an import library is a statically linked library containing the
31889 import table which will be filled at load time to point to the actual
31890 @file{API.dll} routines. Sometimes you don't have an import library for the
31891 DLL you want to use. The following sections will explain how to build
31892 one. Note that this is optional.
31893
31894 @item
31895 The actual DLL, @file{API.dll}.
31896 @end enumerate
31897
31898 @noindent
31899 Once you have all the above, to compile an Ada application that uses the
31900 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31901 you simply issue the command
31902
31903 @smallexample
31904 $ gnatmake my_ada_app -largs -lAPI
31905 @end smallexample
31906
31907 @noindent
31908 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31909 tells the GNAT linker to look first for a library named @file{API.lib}
31910 (Microsoft-style name) and if not found for a libraries named
31911 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31912 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31913 contains the following pragma
31914
31915 @smallexample @c ada
31916 pragma Linker_Options ("-lAPI");
31917 @end smallexample
31918
31919 @noindent
31920 you do not have to add @option{-largs -lAPI} at the end of the
31921 @command{gnatmake} command.
31922
31923 If any one of the items above is missing you will have to create it
31924 yourself. The following sections explain how to do so using as an
31925 example a fictitious DLL called @file{API.dll}.
31926
31927 @node Creating an Ada Spec for the DLL Services
31928 @subsection Creating an Ada Spec for the DLL Services
31929
31930 @noindent
31931 A DLL typically comes with a C/C++ header file which provides the
31932 definitions of the routines and variables exported by the DLL. The Ada
31933 equivalent of this header file is a package spec that contains definitions
31934 for the imported entities. If the DLL you intend to use does not come with
31935 an Ada spec you have to generate one such spec yourself. For example if
31936 the header file of @file{API.dll} is a file @file{api.h} containing the
31937 following two definitions:
31938
31939 @smallexample
31940 @group
31941 @cartouche
31942 int some_var;
31943 int get (char *);
31944 @end cartouche
31945 @end group
31946 @end smallexample
31947
31948 @noindent
31949 then the equivalent Ada spec could be:
31950
31951 @smallexample @c ada
31952 @group
31953 @cartouche
31954 with Interfaces.C.Strings;
31955 package API is
31956    use Interfaces;
31957
31958    Some_Var : C.int;
31959    function Get (Str : C.Strings.Chars_Ptr) return C.int;
31960
31961 private
31962    pragma Import (C, Get);
31963    pragma Import (DLL, Some_Var);
31964 end API;
31965 @end cartouche
31966 @end group
31967 @end smallexample
31968
31969 @noindent
31970 Note that a variable is
31971 @strong{always imported with a Stdcall convention}. A function
31972 can have @code{C} or @code{Stdcall} convention.
31973 (@pxref{Windows Calling Conventions}).
31974
31975 @node Creating an Import Library
31976 @subsection Creating an Import Library
31977 @cindex Import library
31978
31979 @menu
31980 * The Definition File::
31981 * GNAT-Style Import Library::
31982 * Microsoft-Style Import Library::
31983 @end menu
31984
31985 @noindent
31986 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31987 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31988 with @file{API.dll} you can skip this section. You can also skip this
31989 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31990 as in this case it is possible to link directly against the
31991 DLL. Otherwise read on.
31992
31993 @node The Definition File
31994 @subsubsection The Definition File
31995 @cindex Definition file
31996 @findex .def
31997
31998 @noindent
31999 As previously mentioned, and unlike Unix systems, the list of symbols
32000 that are exported from a DLL must be provided explicitly in Windows.
32001 The main goal of a definition file is precisely that: list the symbols
32002 exported by a DLL. A definition file (usually a file with a @code{.def}
32003 suffix) has the following structure:
32004
32005 @smallexample
32006 @group
32007 @cartouche
32008 @r{[}LIBRARY @var{name}@r{]}
32009 @r{[}DESCRIPTION @var{string}@r{]}
32010 EXPORTS
32011    @var{symbol1}
32012    @var{symbol2}
32013    @dots{}
32014 @end cartouche
32015 @end group
32016 @end smallexample
32017
32018 @table @code
32019 @item LIBRARY @var{name}
32020 This section, which is optional, gives the name of the DLL.
32021
32022 @item DESCRIPTION @var{string}
32023 This section, which is optional, gives a description string that will be
32024 embedded in the import library.
32025
32026 @item EXPORTS
32027 This section gives the list of exported symbols (procedures, functions or
32028 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32029 section of @file{API.def} looks like:
32030
32031 @smallexample
32032 @group
32033 @cartouche
32034 EXPORTS
32035    some_var
32036    get
32037 @end cartouche
32038 @end group
32039 @end smallexample
32040 @end table
32041
32042 @noindent
32043 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32044 (@pxref{Windows Calling Conventions}) for a Stdcall
32045 calling convention function in the exported symbols list.
32046
32047 @noindent
32048 There can actually be other sections in a definition file, but these
32049 sections are not relevant to the discussion at hand.
32050
32051 @node GNAT-Style Import Library
32052 @subsubsection GNAT-Style Import Library
32053
32054 @noindent
32055 To create a static import library from @file{API.dll} with the GNAT tools
32056 you should proceed as follows:
32057
32058 @enumerate
32059 @item
32060 Create the definition file @file{API.def} (@pxref{The Definition File}).
32061 For that use the @code{dll2def} tool as follows:
32062
32063 @smallexample
32064 $ dll2def API.dll > API.def
32065 @end smallexample
32066
32067 @noindent
32068 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32069 to standard output the list of entry points in the DLL. Note that if
32070 some routines in the DLL have the @code{Stdcall} convention
32071 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32072 suffix then you'll have to edit @file{api.def} to add it, and specify
32073 @option{-k} to @command{gnatdll} when creating the import library.
32074
32075 @noindent
32076 Here are some hints to find the right @code{@@}@var{nn} suffix.
32077
32078 @enumerate
32079 @item
32080 If you have the Microsoft import library (.lib), it is possible to get
32081 the right symbols by using Microsoft @code{dumpbin} tool (see the
32082 corresponding Microsoft documentation for further details).
32083
32084 @smallexample
32085 $ dumpbin /exports api.lib
32086 @end smallexample
32087
32088 @item
32089 If you have a message about a missing symbol at link time the compiler
32090 tells you what symbol is expected. You just have to go back to the
32091 definition file and add the right suffix.
32092 @end enumerate
32093
32094 @item
32095 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32096 (@pxref{Using gnatdll}) as follows:
32097
32098 @smallexample
32099 $ gnatdll -e API.def -d API.dll
32100 @end smallexample
32101
32102 @noindent
32103 @code{gnatdll} takes as input a definition file @file{API.def} and the
32104 name of the DLL containing the services listed in the definition file
32105 @file{API.dll}. The name of the static import library generated is
32106 computed from the name of the definition file as follows: if the
32107 definition file name is @var{xyz}@code{.def}, the import library name will
32108 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32109 @option{-e} could have been removed because the name of the definition
32110 file (before the ``@code{.def}'' suffix) is the same as the name of the
32111 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32112 @end enumerate
32113
32114 @node Microsoft-Style Import Library
32115 @subsubsection Microsoft-Style Import Library
32116
32117 @noindent
32118 With GNAT you can either use a GNAT-style or Microsoft-style import
32119 library. A Microsoft import library is needed only if you plan to make an
32120 Ada DLL available to applications developed with Microsoft
32121 tools (@pxref{Mixed-Language Programming on Windows}).
32122
32123 To create a Microsoft-style import library for @file{API.dll} you
32124 should proceed as follows:
32125
32126 @enumerate
32127 @item
32128 Create the definition file @file{API.def} from the DLL. For this use either
32129 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32130 tool (see the corresponding Microsoft documentation for further details).
32131
32132 @item
32133 Build the actual import library using Microsoft's @code{lib} utility:
32134
32135 @smallexample
32136 $ lib -machine:IX86 -def:API.def -out:API.lib
32137 @end smallexample
32138
32139 @noindent
32140 If you use the above command the definition file @file{API.def} must
32141 contain a line giving the name of the DLL:
32142
32143 @smallexample
32144 LIBRARY      "API"
32145 @end smallexample
32146
32147 @noindent
32148 See the Microsoft documentation for further details about the usage of
32149 @code{lib}.
32150 @end enumerate
32151
32152 @node Building DLLs with GNAT
32153 @section Building DLLs with GNAT
32154 @cindex DLLs, building
32155
32156 @noindent
32157 This section explain how to build DLLs using the GNAT built-in DLL
32158 support. With the following procedure it is straight forward to build
32159 and use DLLs with GNAT.
32160
32161 @enumerate
32162
32163 @item building object files
32164
32165 The first step is to build all objects files that are to be included
32166 into the DLL. This is done by using the standard @command{gnatmake} tool.
32167
32168 @item building the DLL
32169
32170 To build the DLL you must use @command{gcc}'s @option{-shared}
32171 option. It is quite simple to use this method:
32172
32173 @smallexample
32174 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32175 @end smallexample
32176
32177 It is important to note that in this case all symbols found in the
32178 object files are automatically exported. It is possible to restrict
32179 the set of symbols to export by passing to @command{gcc} a definition
32180 file, @pxref{The Definition File}. For example:
32181
32182 @smallexample
32183 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32184 @end smallexample
32185
32186 If you use a definition file you must export the elaboration procedures
32187 for every package that required one. Elaboration procedures are named
32188 using the package name followed by "_E".
32189
32190 @item preparing DLL to be used
32191
32192 For the DLL to be used by client programs the bodies must be hidden
32193 from it and the .ali set with read-only attribute. This is very important
32194 otherwise GNAT will recompile all packages and will not actually use
32195 the code in the DLL. For example:
32196
32197 @smallexample
32198 $ mkdir apilib
32199 $ copy *.ads *.ali api.dll apilib
32200 $ attrib +R apilib\*.ali
32201 @end smallexample
32202
32203 @end enumerate
32204
32205 At this point it is possible to use the DLL by directly linking
32206 against it. Note that you must use the GNAT shared runtime when using
32207 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32208 option.
32209
32210 @smallexample
32211 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32212 @end smallexample
32213
32214 @node Building DLLs with GNAT Project files
32215 @section Building DLLs with GNAT Project files
32216 @cindex DLLs, building
32217
32218 @noindent
32219 There is nothing specific to Windows in the build process.
32220 @pxref{Library Projects}.
32221
32222 @noindent
32223 Due to a system limitation, it is not possible under Windows to create threads
32224 when inside the @code{DllMain} routine which is used for auto-initialization
32225 of shared libraries, so it is not possible to have library level tasks in SALs.
32226
32227 @node Building DLLs with gnatdll
32228 @section Building DLLs with gnatdll
32229 @cindex DLLs, building
32230
32231 @menu
32232 * Limitations When Using Ada DLLs from Ada::
32233 * Exporting Ada Entities::
32234 * Ada DLLs and Elaboration::
32235 * Ada DLLs and Finalization::
32236 * Creating a Spec for Ada DLLs::
32237 * Creating the Definition File::
32238 * Using gnatdll::
32239 @end menu
32240
32241 @noindent
32242 Note that it is preferred to use the built-in GNAT DLL support
32243 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32244 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32245
32246 This section explains how to build DLLs containing Ada code using
32247 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32248 remainder of this section.
32249
32250 The steps required to build an Ada DLL that is to be used by Ada as well as
32251 non-Ada applications are as follows:
32252
32253 @enumerate
32254 @item
32255 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32256 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32257 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32258 skip this step if you plan to use the Ada DLL only from Ada applications.
32259
32260 @item
32261 Your Ada code must export an initialization routine which calls the routine
32262 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32263 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32264 routine exported by the Ada DLL must be invoked by the clients of the DLL
32265 to initialize the DLL.
32266
32267 @item
32268 When useful, the DLL should also export a finalization routine which calls
32269 routine @code{adafinal} generated by @command{gnatbind} to perform the
32270 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32271 The finalization routine exported by the Ada DLL must be invoked by the
32272 clients of the DLL when the DLL services are no further needed.
32273
32274 @item
32275 You must provide a spec for the services exported by the Ada DLL in each
32276 of the programming languages to which you plan to make the DLL available.
32277
32278 @item
32279 You must provide a definition file listing the exported entities
32280 (@pxref{The Definition File}).
32281
32282 @item
32283 Finally you must use @code{gnatdll} to produce the DLL and the import
32284 library (@pxref{Using gnatdll}).
32285 @end enumerate
32286
32287 @noindent
32288 Note that a relocatable DLL stripped using the @code{strip}
32289 binutils tool will not be relocatable anymore. To build a DLL without
32290 debug information pass @code{-largs -s} to @code{gnatdll}. This
32291 restriction does not apply to a DLL built using a Library Project.
32292 @pxref{Library Projects}.
32293
32294 @node Limitations When Using Ada DLLs from Ada
32295 @subsection Limitations When Using Ada DLLs from Ada
32296
32297 @noindent
32298 When using Ada DLLs from Ada applications there is a limitation users
32299 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32300 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32301 each Ada DLL includes the services of the GNAT run time that are necessary
32302 to the Ada code inside the DLL. As a result, when an Ada program uses an
32303 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32304 one in the main program.
32305
32306 It is therefore not possible to exchange GNAT run-time objects between the
32307 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32308 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32309 types, etc.
32310
32311 It is completely safe to exchange plain elementary, array or record types,
32312 Windows object handles, etc.
32313
32314 @node Exporting Ada Entities
32315 @subsection Exporting Ada Entities
32316 @cindex Export table
32317
32318 @noindent
32319 Building a DLL is a way to encapsulate a set of services usable from any
32320 application. As a result, the Ada entities exported by a DLL should be
32321 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32322 any Ada name mangling. As an example here is an Ada package
32323 @code{API}, spec and body, exporting two procedures, a function, and a
32324 variable:
32325
32326 @smallexample @c ada
32327 @group
32328 @cartouche
32329 with Interfaces.C; use Interfaces;
32330 package API is
32331    Count : C.int := 0;
32332    function Factorial (Val : C.int) return C.int;
32333
32334    procedure Initialize_API;
32335    procedure Finalize_API;
32336    --  Initialization & Finalization routines. More in the next section.
32337 private
32338    pragma Export (C, Initialize_API);
32339    pragma Export (C, Finalize_API);
32340    pragma Export (C, Count);
32341    pragma Export (C, Factorial);
32342 end API;
32343 @end cartouche
32344 @end group
32345 @end smallexample
32346
32347 @smallexample @c ada
32348 @group
32349 @cartouche
32350 package body API is
32351    function Factorial (Val : C.int) return C.int is
32352       Fact : C.int := 1;
32353    begin
32354       Count := Count + 1;
32355       for K in 1 .. Val loop
32356          Fact := Fact * K;
32357       end loop;
32358       return Fact;
32359    end Factorial;
32360
32361    procedure Initialize_API is
32362       procedure Adainit;
32363       pragma Import (C, Adainit);
32364    begin
32365       Adainit;
32366    end Initialize_API;
32367
32368    procedure Finalize_API is
32369       procedure Adafinal;
32370       pragma Import (C, Adafinal);
32371    begin
32372       Adafinal;
32373    end Finalize_API;
32374 end API;
32375 @end cartouche
32376 @end group
32377 @end smallexample
32378
32379 @noindent
32380 If the Ada DLL you are building will only be used by Ada applications
32381 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32382 convention. As an example, the previous package could be written as
32383 follows:
32384
32385 @smallexample @c ada
32386 @group
32387 @cartouche
32388 package API is
32389    Count : Integer := 0;
32390    function Factorial (Val : Integer) return Integer;
32391
32392    procedure Initialize_API;
32393    procedure Finalize_API;
32394    --  Initialization and Finalization routines.
32395 end API;
32396 @end cartouche
32397 @end group
32398 @end smallexample
32399
32400 @smallexample @c ada
32401 @group
32402 @cartouche
32403 package body API is
32404    function Factorial (Val : Integer) return Integer is
32405       Fact : Integer := 1;
32406    begin
32407       Count := Count + 1;
32408       for K in 1 .. Val loop
32409          Fact := Fact * K;
32410       end loop;
32411       return Fact;
32412    end Factorial;
32413
32414    @dots{}
32415    --  The remainder of this package body is unchanged.
32416 end API;
32417 @end cartouche
32418 @end group
32419 @end smallexample
32420
32421 @noindent
32422 Note that if you do not export the Ada entities with a @code{C} or
32423 @code{Stdcall} convention you will have to provide the mangled Ada names
32424 in the definition file of the Ada DLL
32425 (@pxref{Creating the Definition File}).
32426
32427 @node Ada DLLs and Elaboration
32428 @subsection Ada DLLs and Elaboration
32429 @cindex DLLs and elaboration
32430
32431 @noindent
32432 The DLL that you are building contains your Ada code as well as all the
32433 routines in the Ada library that are needed by it. The first thing a
32434 user of your DLL must do is elaborate the Ada code
32435 (@pxref{Elaboration Order Handling in GNAT}).
32436
32437 To achieve this you must export an initialization routine
32438 (@code{Initialize_API} in the previous example), which must be invoked
32439 before using any of the DLL services. This elaboration routine must call
32440 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32441 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32442 @code{Initialize_Api} for an example. Note that the GNAT binder is
32443 automatically invoked during the DLL build process by the @code{gnatdll}
32444 tool (@pxref{Using gnatdll}).
32445
32446 When a DLL is loaded, Windows systematically invokes a routine called
32447 @code{DllMain}. It would therefore be possible to call @code{adainit}
32448 directly from @code{DllMain} without having to provide an explicit
32449 initialization routine. Unfortunately, it is not possible to call
32450 @code{adainit} from the @code{DllMain} if your program has library level
32451 tasks because access to the @code{DllMain} entry point is serialized by
32452 the system (that is, only a single thread can execute ``through'' it at a
32453 time), which means that the GNAT run time will deadlock waiting for the
32454 newly created task to complete its initialization.
32455
32456 @node Ada DLLs and Finalization
32457 @subsection Ada DLLs and Finalization
32458 @cindex DLLs and finalization
32459
32460 @noindent
32461 When the services of an Ada DLL are no longer needed, the client code should
32462 invoke the DLL finalization routine, if available. The DLL finalization
32463 routine is in charge of releasing all resources acquired by the DLL. In the
32464 case of the Ada code contained in the DLL, this is achieved by calling
32465 routine @code{adafinal} generated by the GNAT binder
32466 (@pxref{Binding with Non-Ada Main Programs}).
32467 See the body of @code{Finalize_Api} for an
32468 example. As already pointed out the GNAT binder is automatically invoked
32469 during the DLL build process by the @code{gnatdll} tool
32470 (@pxref{Using gnatdll}).
32471
32472 @node Creating a Spec for Ada DLLs
32473 @subsection Creating a Spec for Ada DLLs
32474
32475 @noindent
32476 To use the services exported by the Ada DLL from another programming
32477 language (e.g.@: C), you have to translate the specs of the exported Ada
32478 entities in that language. For instance in the case of @code{API.dll},
32479 the corresponding C header file could look like:
32480
32481 @smallexample
32482 @group
32483 @cartouche
32484 extern int *_imp__count;
32485 #define count (*_imp__count)
32486 int factorial (int);
32487 @end cartouche
32488 @end group
32489 @end smallexample
32490
32491 @noindent
32492 It is important to understand that when building an Ada DLL to be used by
32493 other Ada applications, you need two different specs for the packages
32494 contained in the DLL: one for building the DLL and the other for using
32495 the DLL. This is because the @code{DLL} calling convention is needed to
32496 use a variable defined in a DLL, but when building the DLL, the variable
32497 must have either the @code{Ada} or @code{C} calling convention. As an
32498 example consider a DLL comprising the following package @code{API}:
32499
32500 @smallexample @c ada
32501 @group
32502 @cartouche
32503 package API is
32504    Count : Integer := 0;
32505    @dots{}
32506    --  Remainder of the package omitted.
32507 end API;
32508 @end cartouche
32509 @end group
32510 @end smallexample
32511
32512 @noindent
32513 After producing a DLL containing package @code{API}, the spec that
32514 must be used to import @code{API.Count} from Ada code outside of the
32515 DLL is:
32516
32517 @smallexample @c ada
32518 @group
32519 @cartouche
32520 package API is
32521    Count : Integer;
32522    pragma Import (DLL, Count);
32523 end API;
32524 @end cartouche
32525 @end group
32526 @end smallexample
32527
32528 @node Creating the Definition File
32529 @subsection Creating the Definition File
32530
32531 @noindent
32532 The definition file is the last file needed to build the DLL. It lists
32533 the exported symbols. As an example, the definition file for a DLL
32534 containing only package @code{API} (where all the entities are exported
32535 with a @code{C} calling convention) is:
32536
32537 @smallexample
32538 @group
32539 @cartouche
32540 EXPORTS
32541     count
32542     factorial
32543     finalize_api
32544     initialize_api
32545 @end cartouche
32546 @end group
32547 @end smallexample
32548
32549 @noindent
32550 If the @code{C} calling convention is missing from package @code{API},
32551 then the definition file contains the mangled Ada names of the above
32552 entities, which in this case are:
32553
32554 @smallexample
32555 @group
32556 @cartouche
32557 EXPORTS
32558     api__count
32559     api__factorial
32560     api__finalize_api
32561     api__initialize_api
32562 @end cartouche
32563 @end group
32564 @end smallexample
32565
32566 @node Using gnatdll
32567 @subsection Using @code{gnatdll}
32568 @findex gnatdll
32569
32570 @menu
32571 * gnatdll Example::
32572 * gnatdll behind the Scenes::
32573 * Using dlltool::
32574 @end menu
32575
32576 @noindent
32577 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32578 and non-Ada sources that make up your DLL have been compiled.
32579 @code{gnatdll} is actually in charge of two distinct tasks: build the
32580 static import library for the DLL and the actual DLL. The form of the
32581 @code{gnatdll} command is
32582
32583 @smallexample
32584 @cartouche
32585 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32586 @end cartouche
32587 @end smallexample
32588
32589 @noindent
32590 where @var{list-of-files} is a list of ALI and object files. The object
32591 file list must be the exact list of objects corresponding to the non-Ada
32592 sources whose services are to be included in the DLL. The ALI file list
32593 must be the exact list of ALI files for the corresponding Ada sources
32594 whose services are to be included in the DLL. If @var{list-of-files} is
32595 missing, only the static import library is generated.
32596
32597 @noindent
32598 You may specify any of the following switches to @code{gnatdll}:
32599
32600 @table @code
32601 @item -a@ovar{address}
32602 @cindex @option{-a} (@code{gnatdll})
32603 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32604 specified the default address @var{0x11000000} will be used. By default,
32605 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32606 advise the reader to build relocatable DLL.
32607
32608 @item -b @var{address}
32609 @cindex @option{-b} (@code{gnatdll})
32610 Set the relocatable DLL base address. By default the address is
32611 @code{0x11000000}.
32612
32613 @item -bargs @var{opts}
32614 @cindex @option{-bargs} (@code{gnatdll})
32615 Binder options. Pass @var{opts} to the binder.
32616
32617 @item -d @var{dllfile}
32618 @cindex @option{-d} (@code{gnatdll})
32619 @var{dllfile} is the name of the DLL. This switch must be present for
32620 @code{gnatdll} to do anything. The name of the generated import library is
32621 obtained algorithmically from @var{dllfile} as shown in the following
32622 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32623 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32624 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32625 as shown in the following example:
32626 if @var{dllfile} is @code{xyz.dll}, the definition
32627 file used is @code{xyz.def}.
32628
32629 @item -e @var{deffile}
32630 @cindex @option{-e} (@code{gnatdll})
32631 @var{deffile} is the name of the definition file.
32632
32633 @item -g
32634 @cindex @option{-g} (@code{gnatdll})
32635 Generate debugging information. This information is stored in the object
32636 file and copied from there to the final DLL file by the linker,
32637 where it can be read by the debugger. You must use the
32638 @option{-g} switch if you plan on using the debugger or the symbolic
32639 stack traceback.
32640
32641 @item -h
32642 @cindex @option{-h} (@code{gnatdll})
32643 Help mode. Displays @code{gnatdll} switch usage information.
32644
32645 @item -Idir
32646 @cindex @option{-I} (@code{gnatdll})
32647 Direct @code{gnatdll} to search the @var{dir} directory for source and
32648 object files needed to build the DLL.
32649 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32650
32651 @item -k
32652 @cindex @option{-k} (@code{gnatdll})
32653 Removes the @code{@@}@var{nn} suffix from the import library's exported
32654 names, but keeps them for the link names. You must specify this
32655 option if you want to use a @code{Stdcall} function in a DLL for which
32656 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32657 of the Windows NT DLL for example. This option has no effect when
32658 @option{-n} option is specified.
32659
32660 @item -l @var{file}
32661 @cindex @option{-l} (@code{gnatdll})
32662 The list of ALI and object files used to build the DLL are listed in
32663 @var{file}, instead of being given in the command line. Each line in
32664 @var{file} contains the name of an ALI or object file.
32665
32666 @item -n
32667 @cindex @option{-n} (@code{gnatdll})
32668 No Import. Do not create the import library.
32669
32670 @item -q
32671 @cindex @option{-q} (@code{gnatdll})
32672 Quiet mode. Do not display unnecessary messages.
32673
32674 @item -v
32675 @cindex @option{-v} (@code{gnatdll})
32676 Verbose mode. Display extra information.
32677
32678 @item -largs @var{opts}
32679 @cindex @option{-largs} (@code{gnatdll})
32680 Linker options. Pass @var{opts} to the linker.
32681 @end table
32682
32683 @node gnatdll Example
32684 @subsubsection @code{gnatdll} Example
32685
32686 @noindent
32687 As an example the command to build a relocatable DLL from @file{api.adb}
32688 once @file{api.adb} has been compiled and @file{api.def} created is
32689
32690 @smallexample
32691 $ gnatdll -d api.dll api.ali
32692 @end smallexample
32693
32694 @noindent
32695 The above command creates two files: @file{libapi.dll.a} (the import
32696 library) and @file{api.dll} (the actual DLL). If you want to create
32697 only the DLL, just type:
32698
32699 @smallexample
32700 $ gnatdll -d api.dll -n api.ali
32701 @end smallexample
32702
32703 @noindent
32704 Alternatively if you want to create just the import library, type:
32705
32706 @smallexample
32707 $ gnatdll -d api.dll
32708 @end smallexample
32709
32710 @node gnatdll behind the Scenes
32711 @subsubsection @code{gnatdll} behind the Scenes
32712
32713 @noindent
32714 This section details the steps involved in creating a DLL. @code{gnatdll}
32715 does these steps for you. Unless you are interested in understanding what
32716 goes on behind the scenes, you should skip this section.
32717
32718 We use the previous example of a DLL containing the Ada package @code{API},
32719 to illustrate the steps necessary to build a DLL. The starting point is a
32720 set of objects that will make up the DLL and the corresponding ALI
32721 files. In the case of this example this means that @file{api.o} and
32722 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32723 the following:
32724
32725 @enumerate
32726 @item
32727 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32728 the information necessary to generate relocation information for the
32729 DLL.
32730
32731 @smallexample
32732 @group
32733 $ gnatbind -n api
32734 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32735 @end group
32736 @end smallexample
32737
32738 @noindent
32739 In addition to the base file, the @command{gnatlink} command generates an
32740 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32741 asks @command{gnatlink} to generate the routines @code{DllMain} and
32742 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32743 is loaded into memory.
32744
32745 @item
32746 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32747 export table (@file{api.exp}). The export table contains the relocation
32748 information in a form which can be used during the final link to ensure
32749 that the Windows loader is able to place the DLL anywhere in memory.
32750
32751 @smallexample
32752 @group
32753 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32754           --output-exp api.exp
32755 @end group
32756 @end smallexample
32757
32758 @item
32759 @code{gnatdll} builds the base file using the new export table. Note that
32760 @command{gnatbind} must be called once again since the binder generated file
32761 has been deleted during the previous call to @command{gnatlink}.
32762
32763 @smallexample
32764 @group
32765 $ gnatbind -n api
32766 $ gnatlink api -o api.jnk api.exp -mdll
32767       -Wl,--base-file,api.base
32768 @end group
32769 @end smallexample
32770
32771 @item
32772 @code{gnatdll} builds the new export table using the new base file and
32773 generates the DLL import library @file{libAPI.dll.a}.
32774
32775 @smallexample
32776 @group
32777 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32778           --output-exp api.exp --output-lib libAPI.a
32779 @end group
32780 @end smallexample
32781
32782 @item
32783 Finally @code{gnatdll} builds the relocatable DLL using the final export
32784 table.
32785
32786 @smallexample
32787 @group
32788 $ gnatbind -n api
32789 $ gnatlink api api.exp -o api.dll -mdll
32790 @end group
32791 @end smallexample
32792 @end enumerate
32793
32794 @node Using dlltool
32795 @subsubsection Using @code{dlltool}
32796
32797 @noindent
32798 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32799 DLLs and static import libraries. This section summarizes the most
32800 common @code{dlltool} switches. The form of the @code{dlltool} command
32801 is
32802
32803 @smallexample
32804 $ dlltool @ovar{switches}
32805 @end smallexample
32806
32807 @noindent
32808 @code{dlltool} switches include:
32809
32810 @table @option
32811 @item --base-file @var{basefile}
32812 @cindex @option{--base-file} (@command{dlltool})
32813 Read the base file @var{basefile} generated by the linker. This switch
32814 is used to create a relocatable DLL.
32815
32816 @item --def @var{deffile}
32817 @cindex @option{--def} (@command{dlltool})
32818 Read the definition file.
32819
32820 @item --dllname @var{name}
32821 @cindex @option{--dllname} (@command{dlltool})
32822 Gives the name of the DLL. This switch is used to embed the name of the
32823 DLL in the static import library generated by @code{dlltool} with switch
32824 @option{--output-lib}.
32825
32826 @item -k
32827 @cindex @option{-k} (@command{dlltool})
32828 Kill @code{@@}@var{nn} from exported names
32829 (@pxref{Windows Calling Conventions}
32830 for a discussion about @code{Stdcall}-style symbols.
32831
32832 @item --help
32833 @cindex @option{--help} (@command{dlltool})
32834 Prints the @code{dlltool} switches with a concise description.
32835
32836 @item --output-exp @var{exportfile}
32837 @cindex @option{--output-exp} (@command{dlltool})
32838 Generate an export file @var{exportfile}. The export file contains the
32839 export table (list of symbols in the DLL) and is used to create the DLL.
32840
32841 @item --output-lib @var{libfile}
32842 @cindex @option{--output-lib} (@command{dlltool})
32843 Generate a static import library @var{libfile}.
32844
32845 @item -v
32846 @cindex @option{-v} (@command{dlltool})
32847 Verbose mode.
32848
32849 @item --as @var{assembler-name}
32850 @cindex @option{--as} (@command{dlltool})
32851 Use @var{assembler-name} as the assembler. The default is @code{as}.
32852 @end table
32853
32854 @node GNAT and Windows Resources
32855 @section GNAT and Windows Resources
32856 @cindex Resources, windows
32857
32858 @menu
32859 * Building Resources::
32860 * Compiling Resources::
32861 * Using Resources::
32862 @end menu
32863
32864 @noindent
32865 Resources are an easy way to add Windows specific objects to your
32866 application. The objects that can be added as resources include:
32867
32868 @itemize @bullet
32869 @item
32870 menus
32871
32872 @item
32873 accelerators
32874
32875 @item
32876 dialog boxes
32877
32878 @item
32879 string tables
32880
32881 @item
32882 bitmaps
32883
32884 @item
32885 cursors
32886
32887 @item
32888 icons
32889
32890 @item
32891 fonts
32892 @end itemize
32893
32894 @noindent
32895 This section explains how to build, compile and use resources.
32896
32897 @node Building Resources
32898 @subsection Building Resources
32899 @cindex Resources, building
32900
32901 @noindent
32902 A resource file is an ASCII file. By convention resource files have an
32903 @file{.rc} extension.
32904 The easiest way to build a resource file is to use Microsoft tools
32905 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32906 @code{dlgedit.exe} to build dialogs.
32907 It is always possible to build an @file{.rc} file yourself by writing a
32908 resource script.
32909
32910 It is not our objective to explain how to write a resource file. A
32911 complete description of the resource script language can be found in the
32912 Microsoft documentation.
32913
32914 @node Compiling Resources
32915 @subsection Compiling Resources
32916 @findex rc
32917 @findex windres
32918 @cindex Resources, compiling
32919
32920 @noindent
32921 This section describes how to build a GNAT-compatible (COFF) object file
32922 containing the resources. This is done using the Resource Compiler
32923 @code{windres} as follows:
32924
32925 @smallexample
32926 $ windres -i myres.rc -o myres.o
32927 @end smallexample
32928
32929 @noindent
32930 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32931 file. You can specify an alternate preprocessor (usually named
32932 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32933 parameter. A list of all possible options may be obtained by entering
32934 the command @code{windres} @option{--help}.
32935
32936 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32937 to produce a @file{.res} file (binary resource file). See the
32938 corresponding Microsoft documentation for further details. In this case
32939 you need to use @code{windres} to translate the @file{.res} file to a
32940 GNAT-compatible object file as follows:
32941
32942 @smallexample
32943 $ windres -i myres.res -o myres.o
32944 @end smallexample
32945
32946 @node Using Resources
32947 @subsection Using Resources
32948 @cindex Resources, using
32949
32950 @noindent
32951 To include the resource file in your program just add the
32952 GNAT-compatible object file for the resource(s) to the linker
32953 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32954 option:
32955
32956 @smallexample
32957 $ gnatmake myprog -largs myres.o
32958 @end smallexample
32959
32960 @node Debugging a DLL
32961 @section Debugging a DLL
32962 @cindex DLL debugging
32963
32964 @menu
32965 * Program and DLL Both Built with GCC/GNAT::
32966 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32967 @end menu
32968
32969 @noindent
32970 Debugging a DLL is similar to debugging a standard program. But
32971 we have to deal with two different executable parts: the DLL and the
32972 program that uses it. We have the following four possibilities:
32973
32974 @enumerate 1
32975 @item
32976 The program and the DLL are built with @code{GCC/GNAT}.
32977 @item
32978 The program is built with foreign tools and the DLL is built with
32979 @code{GCC/GNAT}.
32980 @item
32981 The program is built with @code{GCC/GNAT} and the DLL is built with
32982 foreign tools.
32983 @item
32984 @end enumerate
32985
32986 @noindent
32987 In this section we address only cases one and two above.
32988 There is no point in trying to debug
32989 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32990 information in it. To do so you must use a debugger compatible with the
32991 tools suite used to build the DLL.
32992
32993 @node Program and DLL Both Built with GCC/GNAT
32994 @subsection Program and DLL Both Built with GCC/GNAT
32995
32996 @noindent
32997 This is the simplest case. Both the DLL and the program have @code{GDB}
32998 compatible debugging information. It is then possible to break anywhere in
32999 the process. Let's suppose here that the main procedure is named
33000 @code{ada_main} and that in the DLL there is an entry point named
33001 @code{ada_dll}.
33002
33003 @noindent
33004 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33005 program must have been built with the debugging information (see GNAT -g
33006 switch). Here are the step-by-step instructions for debugging it:
33007
33008 @enumerate 1
33009 @item Launch @code{GDB} on the main program.
33010
33011 @smallexample
33012 $ gdb -nw ada_main
33013 @end smallexample
33014
33015 @item Start the program and stop at the beginning of the main procedure
33016
33017 @smallexample
33018 (gdb) start
33019 @end smallexample
33020
33021 @noindent
33022 This step is required to be able to set a breakpoint inside the DLL. As long
33023 as the program is not run, the DLL is not loaded. This has the
33024 consequence that the DLL debugging information is also not loaded, so it is not
33025 possible to set a breakpoint in the DLL.
33026
33027 @item Set a breakpoint inside the DLL
33028
33029 @smallexample
33030 (gdb) break ada_dll
33031 (gdb) cont
33032 @end smallexample
33033
33034 @end enumerate
33035
33036 @noindent
33037 At this stage a breakpoint is set inside the DLL. From there on
33038 you can use the standard approach to debug the whole program
33039 (@pxref{Running and Debugging Ada Programs}).
33040
33041 @ignore
33042 @c This used to work, probably because the DLLs were non-relocatable
33043 @c keep this section around until the problem is sorted out.
33044
33045 To break on the @code{DllMain} routine it is not possible to follow
33046 the procedure above. At the time the program stop on @code{ada_main}
33047 the @code{DllMain} routine as already been called. Either you can use
33048 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33049
33050 @enumerate 1
33051 @item Launch @code{GDB} on the main program.
33052
33053 @smallexample
33054 $ gdb ada_main
33055 @end smallexample
33056
33057 @item Load DLL symbols
33058
33059 @smallexample
33060 (gdb) add-sym api.dll
33061 @end smallexample
33062
33063 @item Set a breakpoint inside the DLL
33064
33065 @smallexample
33066 (gdb) break ada_dll.adb:45
33067 @end smallexample
33068
33069 Note that at this point it is not possible to break using the routine symbol
33070 directly as the program is not yet running. The solution is to break
33071 on the proper line (break in @file{ada_dll.adb} line 45).
33072
33073 @item Start the program
33074
33075 @smallexample
33076 (gdb) run
33077 @end smallexample
33078
33079 @end enumerate
33080 @end ignore
33081
33082 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33083 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33084
33085 @menu
33086 * Debugging the DLL Directly::
33087 * Attaching to a Running Process::
33088 @end menu
33089
33090 @noindent
33091 In this case things are slightly more complex because it is not possible to
33092 start the main program and then break at the beginning to load the DLL and the
33093 associated DLL debugging information. It is not possible to break at the
33094 beginning of the program because there is no @code{GDB} debugging information,
33095 and therefore there is no direct way of getting initial control. This
33096 section addresses this issue by describing some methods that can be used
33097 to break somewhere in the DLL to debug it.
33098
33099 @noindent
33100 First suppose that the main procedure is named @code{main} (this is for
33101 example some C code built with Microsoft Visual C) and that there is a
33102 DLL named @code{test.dll} containing an Ada entry point named
33103 @code{ada_dll}.
33104
33105 @noindent
33106 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33107 been built with debugging information (see GNAT -g option).
33108
33109 @node Debugging the DLL Directly
33110 @subsubsection Debugging the DLL Directly
33111
33112 @enumerate 1
33113 @item
33114 Find out the executable starting address
33115
33116 @smallexample
33117 $ objdump --file-header main.exe
33118 @end smallexample
33119
33120 The starting address is reported on the last line. For example:
33121
33122 @smallexample
33123 main.exe:     file format pei-i386
33124 architecture: i386, flags 0x0000010a:
33125 EXEC_P, HAS_DEBUG, D_PAGED
33126 start address 0x00401010
33127 @end smallexample
33128
33129 @item
33130 Launch the debugger on the executable.
33131
33132 @smallexample
33133 $ gdb main.exe
33134 @end smallexample
33135
33136 @item
33137 Set a breakpoint at the starting address, and launch the program.
33138
33139 @smallexample
33140 $ (gdb) break *0x00401010
33141 $ (gdb) run
33142 @end smallexample
33143
33144 The program will stop at the given address.
33145
33146 @item
33147 Set a breakpoint on a DLL subroutine.
33148
33149 @smallexample
33150 (gdb) break ada_dll.adb:45
33151 @end smallexample
33152
33153 Or if you want to break using a symbol on the DLL, you need first to
33154 select the Ada language (language used by the DLL).
33155
33156 @smallexample
33157 (gdb) set language ada
33158 (gdb) break ada_dll
33159 @end smallexample
33160
33161 @item
33162 Continue the program.
33163
33164 @smallexample
33165 (gdb) cont
33166 @end smallexample
33167
33168 @noindent
33169 This will run the program until it reaches the breakpoint that has been
33170 set. From that point you can use the standard way to debug a program
33171 as described in (@pxref{Running and Debugging Ada Programs}).
33172
33173 @end enumerate
33174
33175 @noindent
33176 It is also possible to debug the DLL by attaching to a running process.
33177
33178 @node Attaching to a Running Process
33179 @subsubsection Attaching to a Running Process
33180 @cindex DLL debugging, attach to process
33181
33182 @noindent
33183 With @code{GDB} it is always possible to debug a running process by
33184 attaching to it. It is possible to debug a DLL this way. The limitation
33185 of this approach is that the DLL must run long enough to perform the
33186 attach operation. It may be useful for instance to insert a time wasting
33187 loop in the code of the DLL to meet this criterion.
33188
33189 @enumerate 1
33190
33191 @item Launch the main program @file{main.exe}.
33192
33193 @smallexample
33194 $ main
33195 @end smallexample
33196
33197 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33198 that the process PID for @file{main.exe} is 208.
33199
33200 @item Launch gdb.
33201
33202 @smallexample
33203 $ gdb
33204 @end smallexample
33205
33206 @item Attach to the running process to be debugged.
33207
33208 @smallexample
33209 (gdb) attach 208
33210 @end smallexample
33211
33212 @item Load the process debugging information.
33213
33214 @smallexample
33215 (gdb) symbol-file main.exe
33216 @end smallexample
33217
33218 @item Break somewhere in the DLL.
33219
33220 @smallexample
33221 (gdb) break ada_dll
33222 @end smallexample
33223
33224 @item Continue process execution.
33225
33226 @smallexample
33227 (gdb) cont
33228 @end smallexample
33229
33230 @end enumerate
33231
33232 @noindent
33233 This last step will resume the process execution, and stop at
33234 the breakpoint we have set. From there you can use the standard
33235 approach to debug a program as described in
33236 (@pxref{Running and Debugging Ada Programs}).
33237
33238 @node Setting Stack Size from gnatlink
33239 @section Setting Stack Size from @command{gnatlink}
33240
33241 @noindent
33242 It is possible to specify the program stack size at link time. On modern
33243 versions of Windows, starting with XP, this is mostly useful to set the size of
33244 the main stack (environment task). The other task stacks are set with pragma
33245 Storage_Size or with the @command{gnatbind -d} command.
33246
33247 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33248 reserve size of individual tasks, the link-time stack size applies to all
33249 tasks, and pragma Storage_Size has no effect.
33250 In particular, Stack Overflow checks are made against this
33251 link-time specified size.
33252
33253 This setting can be done with
33254 @command{gnatlink} using either:
33255
33256 @itemize @bullet
33257
33258 @item using @option{-Xlinker} linker option
33259
33260 @smallexample
33261 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33262 @end smallexample
33263
33264 This sets the stack reserve size to 0x10000 bytes and the stack commit
33265 size to 0x1000 bytes.
33266
33267 @item using @option{-Wl} linker option
33268
33269 @smallexample
33270 $ gnatlink hello -Wl,--stack=0x1000000
33271 @end smallexample
33272
33273 This sets the stack reserve size to 0x1000000 bytes. Note that with
33274 @option{-Wl} option it is not possible to set the stack commit size
33275 because the coma is a separator for this option.
33276
33277 @end itemize
33278
33279 @node Setting Heap Size from gnatlink
33280 @section Setting Heap Size from @command{gnatlink}
33281
33282 @noindent
33283 Under Windows systems, it is possible to specify the program heap size from
33284 @command{gnatlink} using either:
33285
33286 @itemize @bullet
33287
33288 @item using @option{-Xlinker} linker option
33289
33290 @smallexample
33291 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33292 @end smallexample
33293
33294 This sets the heap reserve size to 0x10000 bytes and the heap commit
33295 size to 0x1000 bytes.
33296
33297 @item using @option{-Wl} linker option
33298
33299 @smallexample
33300 $ gnatlink hello -Wl,--heap=0x1000000
33301 @end smallexample
33302
33303 This sets the heap reserve size to 0x1000000 bytes. Note that with
33304 @option{-Wl} option it is not possible to set the heap commit size
33305 because the coma is a separator for this option.
33306
33307 @end itemize
33308
33309 @end ifset
33310
33311 @c **********************************
33312 @c * GNU Free Documentation License *
33313 @c **********************************
33314 @include fdl.texi
33315 @c GNU Free Documentation License
33316
33317 @node Index,,GNU Free Documentation License, Top
33318 @unnumbered Index
33319
33320 @printindex cp
33321
33322 @contents
33323 @c Put table of contents at end, otherwise it precedes the "title page" in
33324 @c the .txt version
33325 @c Edit the pdf file to move the contents to the beginning, after the title
33326 @c page
33327
33328 @bye