OSDN Git Service

2009-05-06 Gary Dismukes <dismukes@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-2005, 2006, 2007, 2008 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'Class;
3282   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3283
3284   function Constructor (v : Integer) return Root'Class;
3285   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3286
3287   function Constructor (v, w : Integer) return Root'Class;
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.
3349
3350 @smallexample @c ada
3351   Obj5 : DT;
3352   Obj6 : DT := Function_Returning_DT (50);
3353 @end smallexample
3354
3355 The declaration of @code{Obj5} invokes the default constructors: the
3356 C++ default constructor of the parent type takes care of the initialization
3357 of the components inherited from Root, and GNAT takes care of the default
3358 initialization of the additional Ada components of type DT (that is,
3359 @code{C_Value} is initialized to value 2009). The order of invocation of
3360 the constructors is consistent with the order of elaboration required by
3361 Ada and C++. That is, the constructor of the parent type is always called
3362 before the constructor of the derived type.
3363
3364 Let us now consider a record that has components whose type is imported
3365 from C++. For example:
3366
3367 @smallexample @c ada
3368   type Rec1 is limited record
3369      Data1 : Root := Constructor (10);
3370      Value : Natural := 1000;
3371   end record;
3372
3373   type Rec2 (D : Integer := 20) is limited record
3374      Rec   : Rec1;
3375      Data2 : Root := Constructor (D, 30);
3376   end record;
3377 @end smallexample
3378
3379 The initialization of an object of type @code{Rec2} will call the
3380 non-default C++ constructors specified for the imported components.
3381 For example:
3382
3383 @smallexample @c ada
3384   Obj7 : Rec2 (40);
3385 @end smallexample
3386
3387 Using Ada 2005 we can use limited aggregates to initialize an object
3388 invoking C++ constructors that differ from those specified in the type
3389 declarations. For example:
3390
3391 @smallexample @c ada
3392   Obj8 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3393                           others => <>),
3394                   others => <>);
3395 @end smallexample
3396
3397 The above declaration uses an Ada 2005 limited aggregate to
3398 initialize @code{Obj8}, and the C++ constructor that has two integer
3399 arguments is invoked to initialize the @code{Data1} component instead
3400 of the constructor specified in the declaration of type @code{Rec1}. In
3401 Ada 2005 the box in the aggregate indicates that unspecified components
3402 are initialized using the expression (if any) available in the component
3403 declaration. That is, in this case discriminant @code{D} is initialized
3404 to value @code{20}, @code{Value} is initialized to value 1000, and the
3405 non-default C++ constructor that handles two integers takes care of
3406 initializing component @code{Data2} with values @code{20,30}.
3407
3408 In Ada 2005 we can use the extended return statement to build the Ada
3409 equivalent to C++ non-default constructors. For example:
3410
3411 @smallexample @c ada
3412   function Constructor (V : Integer) return Rec2 is
3413   begin
3414      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3415                                    others => <>),
3416                            others => <>) do
3417         --  Further actions required for construction of
3418         --  objects of type Rec2
3419         ...
3420      end record;
3421   end Constructor;
3422 @end smallexample
3423
3424 In this example the extended return statement construct is used to
3425 build in place the returned object whose components are initialized
3426 by means of a limited aggregate. Any further action associated with
3427 the constructor can be placed inside the construct.
3428
3429 @node Interfacing with C++ at the Class Level
3430 @subsection Interfacing with C++ at the Class Level
3431 @noindent
3432 In this section we demonstrate the GNAT features for interfacing with
3433 C++ by means of an example making use of Ada 2005 abstract interface
3434 types. This example consists of a classification of animals; classes
3435 have been used to model our main classification of animals, and
3436 interfaces provide support for the management of secondary
3437 classifications. We first demonstrate a case in which the types and
3438 constructors are defined on the C++ side and imported from the Ada
3439 side, and latter the reverse case.
3440
3441 The root of our derivation will be the @code{Animal} class, with a
3442 single private attribute (the @code{Age} of the animal) and two public
3443 primitives to set and get the value of this attribute.
3444
3445 @smallexample
3446 @b{class} Animal @{
3447  @b{public}:
3448    @b{virtual} void Set_Age (int New_Age);
3449    @b{virtual} int Age ();
3450  @b{private}:
3451    int Age_Count;
3452 @};
3453 @end smallexample
3454
3455 Abstract interface types are defined in C++ by means of classes with pure
3456 virtual functions and no data members. In our example we will use two
3457 interfaces that provide support for the common management of @code{Carnivore}
3458 and @code{Domestic} animals:
3459
3460 @smallexample
3461 @b{class} Carnivore @{
3462 @b{public}:
3463    @b{virtual} int Number_Of_Teeth () = 0;
3464 @};
3465
3466 @b{class} Domestic @{
3467 @b{public}:
3468    @b{virtual void} Set_Owner (char* Name) = 0;
3469 @};
3470 @end smallexample
3471
3472 Using these declarations, we can now say that a @code{Dog} is an animal that is
3473 both Carnivore and Domestic, that is:
3474
3475 @smallexample
3476 @b{class} Dog : Animal, Carnivore, Domestic @{
3477  @b{public}:
3478    @b{virtual} int  Number_Of_Teeth ();
3479    @b{virtual} void Set_Owner (char* Name);
3480
3481    Dog(); // Constructor
3482  @b{private}:
3483    int  Tooth_Count;
3484    char *Owner;
3485 @};
3486 @end smallexample
3487
3488 In the following examples we will assume that the previous declarations are
3489 located in a file named @code{animals.h}. The following package demonstrates
3490 how to import these C++ declarations from the Ada side:
3491
3492 @smallexample @c ada
3493 with Interfaces.C.Strings; use Interfaces.C.Strings;
3494 package Animals is
3495   type Carnivore is interface;
3496   pragma Convention (C_Plus_Plus, Carnivore);
3497   function Number_Of_Teeth (X : Carnivore)
3498      return Natural is abstract;
3499
3500   type Domestic is interface;
3501   pragma Convention (C_Plus_Plus, Set_Owner);
3502   procedure Set_Owner
3503     (X    : in out Domestic;
3504      Name : Chars_Ptr) is abstract;
3505
3506   type Animal is tagged record
3507     Age : Natural := 0;
3508   end record;
3509   pragma Import (C_Plus_Plus, Animal);
3510
3511   procedure Set_Age (X : in out Animal; Age : Integer);
3512   pragma Import (C_Plus_Plus, Set_Age);
3513
3514   function Age (X : Animal) return Integer;
3515   pragma Import (C_Plus_Plus, Age);
3516
3517   type Dog is new Animal and Carnivore and Domestic with record
3518     Tooth_Count : Natural;
3519     Owner       : String (1 .. 30);
3520   end record;
3521   pragma Import (C_Plus_Plus, Dog);
3522
3523   function Number_Of_Teeth (A : Dog) return Integer;
3524   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3525
3526   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3527   pragma Import (C_Plus_Plus, Set_Owner);
3528
3529   function New_Dog return Dog'Class;
3530   pragma CPP_Constructor (New_Dog);
3531   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3532 end Animals;
3533 @end smallexample
3534
3535 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3536 interfacing with these C++ classes is easy. The only requirement is that all
3537 the primitives and components must be declared exactly in the same order in
3538 the two languages.
3539
3540 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3541 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3542 the arguments to the called primitives will be the same as for C++. For the
3543 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3544 to indicate that they have been defined on the C++ side; this is required
3545 because the dispatch table associated with these tagged types will be built
3546 in the C++ side and therefore will not contain the predefined Ada primitives
3547 which Ada would otherwise expect.
3548
3549 As the reader can see there is no need to indicate the C++ mangled names
3550 associated with each subprogram because it is assumed that all the calls to
3551 these primitives will be dispatching calls. The only exception is the
3552 constructor, which must be registered with the compiler by means of
3553 @code{pragma CPP_Constructor} and needs to provide its associated C++
3554 mangled name because the Ada compiler generates direct calls to it.
3555
3556 With the above packages we can now declare objects of type Dog on the Ada side
3557 and dispatch calls to the corresponding subprograms on the C++ side. We can
3558 also extend the tagged type Dog with further fields and primitives, and
3559 override some of its C++ primitives on the Ada side. For example, here we have
3560 a type derivation defined on the Ada side that inherits all the dispatching
3561 primitives of the ancestor from the C++ side.
3562
3563 @smallexample
3564 @b{with} Animals; @b{use} Animals;
3565 @b{package} Vaccinated_Animals @b{is}
3566   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3567   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3568 @b{end} Vaccinated_Animals;
3569 @end smallexample
3570
3571 It is important to note that, because of the ABI compatibility, the programmer
3572 does not need to add any further information to indicate either the object
3573 layout or the dispatch table entry associated with each dispatching operation.
3574
3575 Now let us define all the types and constructors on the Ada side and export
3576 them to C++, using the same hierarchy of our previous example:
3577
3578 @smallexample @c ada
3579 with Interfaces.C.Strings;
3580 use Interfaces.C.Strings;
3581 package Animals is
3582   type Carnivore is interface;
3583   pragma Convention (C_Plus_Plus, Carnivore);
3584   function Number_Of_Teeth (X : Carnivore)
3585      return Natural is abstract;
3586
3587   type Domestic is interface;
3588   pragma Convention (C_Plus_Plus, Set_Owner);
3589   procedure Set_Owner
3590     (X    : in out Domestic;
3591      Name : Chars_Ptr) is abstract;
3592
3593   type Animal is tagged record
3594     Age : Natural := 0;
3595   end record;
3596   pragma Convention (C_Plus_Plus, Animal);
3597
3598   procedure Set_Age (X : in out Animal; Age : Integer);
3599   pragma Export (C_Plus_Plus, Set_Age);
3600
3601   function Age (X : Animal) return Integer;
3602   pragma Export (C_Plus_Plus, Age);
3603
3604   type Dog is new Animal and Carnivore and Domestic with record
3605     Tooth_Count : Natural;
3606     Owner       : String (1 .. 30);
3607   end record;
3608   pragma Convention (C_Plus_Plus, Dog);
3609
3610   function Number_Of_Teeth (A : Dog) return Integer;
3611   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3612
3613   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3614   pragma Export (C_Plus_Plus, Set_Owner);
3615
3616   function New_Dog return Dog'Class;
3617   pragma Export (C_Plus_Plus, New_Dog);
3618 end Animals;
3619 @end smallexample
3620
3621 Compared with our previous example the only difference is the use of
3622 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3623 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3624 nothing else to be done; as explained above, the only requirement is that all
3625 the primitives and components are declared in exactly the same order.
3626
3627 For completeness, let us see a brief C++ main program that uses the
3628 declarations available in @code{animals.h} (presented in our first example) to
3629 import and use the declarations from the Ada side, properly initializing and
3630 finalizing the Ada run-time system along the way:
3631
3632 @smallexample
3633 @b{#include} "animals.h"
3634 @b{#include} <iostream>
3635 @b{using namespace} std;
3636
3637 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3638 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3639 void Check_Animal (Animal *obj)       @{@dots{}@}
3640 void Check_Dog (Dog *obj)             @{@dots{}@}
3641
3642 @b{extern} "C" @{
3643   void adainit (void);
3644   void adafinal (void);
3645   Dog* new_dog ();
3646 @}
3647
3648 void test ()
3649 @{
3650   Dog *obj = new_dog();  // Ada constructor
3651   Check_Carnivore (obj); // Check secondary DT
3652   Check_Domestic (obj);  // Check secondary DT
3653   Check_Animal (obj);    // Check primary DT
3654   Check_Dog (obj);       // Check primary DT
3655 @}
3656
3657 int main ()
3658 @{
3659   adainit ();  test();  adafinal ();
3660   return 0;
3661 @}
3662 @end smallexample
3663
3664 @node Comparison between GNAT and C/C++ Compilation Models
3665 @section Comparison between GNAT and C/C++ Compilation Models
3666
3667 @noindent
3668 The GNAT model of compilation is close to the C and C++ models. You can
3669 think of Ada specs as corresponding to header files in C. As in C, you
3670 don't need to compile specs; they are compiled when they are used. The
3671 Ada @code{with} is similar in effect to the @code{#include} of a C
3672 header.
3673
3674 One notable difference is that, in Ada, you may compile specs separately
3675 to check them for semantic and syntactic accuracy. This is not always
3676 possible with C headers because they are fragments of programs that have
3677 less specific syntactic or semantic rules.
3678
3679 The other major difference is the requirement for running the binder,
3680 which performs two important functions. First, it checks for
3681 consistency. In C or C++, the only defense against assembling
3682 inconsistent programs lies outside the compiler, in a makefile, for
3683 example. The binder satisfies the Ada requirement that it be impossible
3684 to construct an inconsistent program when the compiler is used in normal
3685 mode.
3686
3687 @cindex Elaboration order control
3688 The other important function of the binder is to deal with elaboration
3689 issues. There are also elaboration issues in C++ that are handled
3690 automatically. This automatic handling has the advantage of being
3691 simpler to use, but the C++ programmer has no control over elaboration.
3692 Where @code{gnatbind} might complain there was no valid order of
3693 elaboration, a C++ compiler would simply construct a program that
3694 malfunctioned at run time.
3695 @end ifclear
3696
3697 @node Comparison between GNAT and Conventional Ada Library Models
3698 @section Comparison between GNAT and Conventional Ada Library Models
3699
3700 @noindent
3701 This section is intended for Ada programmers who have
3702 used an Ada compiler implementing the traditional Ada library
3703 model, as described in the Ada Reference Manual.
3704
3705 @cindex GNAT library
3706 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3707 source files themselves acts as the library. Compiling Ada programs does
3708 not generate any centralized information, but rather an object file and
3709 a ALI file, which are of interest only to the binder and linker.
3710 In a traditional system, the compiler reads information not only from
3711 the source file being compiled, but also from the centralized library.
3712 This means that the effect of a compilation depends on what has been
3713 previously compiled. In particular:
3714
3715 @itemize @bullet
3716 @item
3717 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3718 to the version of the unit most recently compiled into the library.
3719
3720 @item
3721 Inlining is effective only if the necessary body has already been
3722 compiled into the library.
3723
3724 @item
3725 Compiling a unit may obsolete other units in the library.
3726 @end itemize
3727
3728 @noindent
3729 In GNAT, compiling one unit never affects the compilation of any other
3730 units because the compiler reads only source files. Only changes to source
3731 files can affect the results of a compilation. In particular:
3732
3733 @itemize @bullet
3734 @item
3735 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3736 to the source version of the unit that is currently accessible to the
3737 compiler.
3738
3739 @item
3740 @cindex Inlining
3741 Inlining requires the appropriate source files for the package or
3742 subprogram bodies to be available to the compiler. Inlining is always
3743 effective, independent of the order in which units are complied.
3744
3745 @item
3746 Compiling a unit never affects any other compilations. The editing of
3747 sources may cause previous compilations to be out of date if they
3748 depended on the source file being modified.
3749 @end itemize
3750
3751 @noindent
3752 The most important result of these differences is that order of compilation
3753 is never significant in GNAT. There is no situation in which one is
3754 required to do one compilation before another. What shows up as order of
3755 compilation requirements in the traditional Ada library becomes, in
3756 GNAT, simple source dependencies; in other words, there is only a set
3757 of rules saying what source files must be present when a file is
3758 compiled.
3759
3760 @ifset vms
3761 @node Placement of temporary files
3762 @section Placement of temporary files
3763 @cindex Temporary files (user control over placement)
3764
3765 @noindent
3766 GNAT creates temporary files in the directory designated by the environment
3767 variable @env{TMPDIR}.
3768 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3769 for detailed information on how environment variables are resolved.
3770 For most users the easiest way to make use of this feature is to simply
3771 define @env{TMPDIR} as a job level logical name).
3772 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3773 for compiler temporary files, then you can include something like the
3774 following command in your @file{LOGIN.COM} file:
3775
3776 @smallexample
3777 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3778 @end smallexample
3779
3780 @noindent
3781 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3782 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3783 designated by @env{TEMP}.
3784 If none of these environment variables are defined then GNAT uses the
3785 directory designated by the logical name @code{SYS$SCRATCH:}
3786 (by default the user's home directory). If all else fails
3787 GNAT uses the current directory for temporary files.
3788 @end ifset
3789
3790 @c *************************
3791 @node Compiling Using gcc
3792 @chapter Compiling Using @command{gcc}
3793
3794 @noindent
3795 This chapter discusses how to compile Ada programs using the @command{gcc}
3796 command. It also describes the set of switches
3797 that can be used to control the behavior of the compiler.
3798 @menu
3799 * Compiling Programs::
3800 * Switches for gcc::
3801 * Search Paths and the Run-Time Library (RTL)::
3802 * Order of Compilation Issues::
3803 * Examples::
3804 @end menu
3805
3806 @node Compiling Programs
3807 @section Compiling Programs
3808
3809 @noindent
3810 The first step in creating an executable program is to compile the units
3811 of the program using the @command{gcc} command. You must compile the
3812 following files:
3813
3814 @itemize @bullet
3815 @item
3816 the body file (@file{.adb}) for a library level subprogram or generic
3817 subprogram
3818
3819 @item
3820 the spec file (@file{.ads}) for a library level package or generic
3821 package that has no body
3822
3823 @item
3824 the body file (@file{.adb}) for a library level package
3825 or generic package that has a body
3826
3827 @end itemize
3828
3829 @noindent
3830 You need @emph{not} compile the following files
3831
3832 @itemize @bullet
3833
3834 @item
3835 the spec of a library unit which has a body
3836
3837 @item
3838 subunits
3839 @end itemize
3840
3841 @noindent
3842 because they are compiled as part of compiling related units. GNAT
3843 package specs
3844 when the corresponding body is compiled, and subunits when the parent is
3845 compiled.
3846
3847 @cindex cannot generate code
3848 If you attempt to compile any of these files, you will get one of the
3849 following error messages (where @var{fff} is the name of the file you compiled):
3850
3851 @smallexample
3852 cannot generate code for file @var{fff} (package spec)
3853 to check package spec, use -gnatc
3854
3855 cannot generate code for file @var{fff} (missing subunits)
3856 to check parent unit, use -gnatc
3857
3858 cannot generate code for file @var{fff} (subprogram spec)
3859 to check subprogram spec, use -gnatc
3860
3861 cannot generate code for file @var{fff} (subunit)
3862 to check subunit, use -gnatc
3863 @end smallexample
3864
3865 @noindent
3866 As indicated by the above error messages, if you want to submit
3867 one of these files to the compiler to check for correct semantics
3868 without generating code, then use the @option{-gnatc} switch.
3869
3870 The basic command for compiling a file containing an Ada unit is
3871
3872 @smallexample
3873 $ gcc -c @ovar{switches} @file{file name}
3874 @end smallexample
3875
3876 @noindent
3877 where @var{file name} is the name of the Ada file (usually
3878 having an extension
3879 @file{.ads} for a spec or @file{.adb} for a body).
3880 @ifclear vms
3881 You specify the
3882 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3883 @end ifclear
3884 The result of a successful compilation is an object file, which has the
3885 same name as the source file but an extension of @file{.o} and an Ada
3886 Library Information (ALI) file, which also has the same name as the
3887 source file, but with @file{.ali} as the extension. GNAT creates these
3888 two output files in the current directory, but you may specify a source
3889 file in any directory using an absolute or relative path specification
3890 containing the directory information.
3891
3892 @findex gnat1
3893 @command{gcc} is actually a driver program that looks at the extensions of
3894 the file arguments and loads the appropriate compiler. For example, the
3895 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3896 These programs are in directories known to the driver program (in some
3897 configurations via environment variables you set), but need not be in
3898 your path. The @command{gcc} driver also calls the assembler and any other
3899 utilities needed to complete the generation of the required object
3900 files.
3901
3902 It is possible to supply several file names on the same @command{gcc}
3903 command. This causes @command{gcc} to call the appropriate compiler for
3904 each file. For example, the following command lists three separate
3905 files to be compiled:
3906
3907 @smallexample
3908 $ gcc -c x.adb y.adb z.c
3909 @end smallexample
3910
3911 @noindent
3912 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3913 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3914 The compiler generates three object files @file{x.o}, @file{y.o} and
3915 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3916 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3917 @ifclear vms
3918 except for
3919 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3920 @end ifclear
3921
3922 @node Switches for gcc
3923 @section Switches for @command{gcc}
3924
3925 @noindent
3926 The @command{gcc} command accepts switches that control the
3927 compilation process. These switches are fully described in this section.
3928 First we briefly list all the switches, in alphabetical order, then we
3929 describe the switches in more detail in functionally grouped sections.
3930
3931 More switches exist for GCC than those documented here, especially
3932 for specific targets. However, their use is not recommended as
3933 they may change code generation in ways that are incompatible with
3934 the Ada run-time library, or can cause inconsistencies between
3935 compilation units.
3936
3937 @menu
3938 * Output and Error Message Control::
3939 * Warning Message Control::
3940 * Debugging and Assertion Control::
3941 * Validity Checking::
3942 * Style Checking::
3943 * Run-Time Checks::
3944 * Using gcc for Syntax Checking::
3945 * Using gcc for Semantic Checking::
3946 * Compiling Different Versions of Ada::
3947 * Character Set Control::
3948 * File Naming Control::
3949 * Subprogram Inlining Control::
3950 * Auxiliary Output Control::
3951 * Debugging Control::
3952 * Exception Handling Control::
3953 * Units to Sources Mapping Files::
3954 * Integrated Preprocessing::
3955 * Code Generation Control::
3956 @ifset vms
3957 * Return Codes::
3958 @end ifset
3959 @end menu
3960
3961 @table @option
3962 @c !sort!
3963 @ifclear vms
3964 @cindex @option{-b} (@command{gcc})
3965 @item -b @var{target}
3966 Compile your program to run on @var{target}, which is the name of a
3967 system configuration. You must have a GNAT cross-compiler built if
3968 @var{target} is not the same as your host system.
3969
3970 @item -B@var{dir}
3971 @cindex @option{-B} (@command{gcc})
3972 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3973 from @var{dir} instead of the default location. Only use this switch
3974 when multiple versions of the GNAT compiler are available.
3975 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3976 GNU Compiler Collection (GCC)}, for further details. You would normally
3977 use the @option{-b} or @option{-V} switch instead.
3978
3979 @item -c
3980 @cindex @option{-c} (@command{gcc})
3981 Compile. Always use this switch when compiling Ada programs.
3982
3983 Note: for some other languages when using @command{gcc}, notably in
3984 the case of C and C++, it is possible to use
3985 use @command{gcc} without a @option{-c} switch to
3986 compile and link in one step. In the case of GNAT, you
3987 cannot use this approach, because the binder must be run
3988 and @command{gcc} cannot be used to run the GNAT binder.
3989 @end ifclear
3990
3991 @item -fno-inline
3992 @cindex @option{-fno-inline} (@command{gcc})
3993 Suppresses all back-end inlining, even if other optimization or inlining
3994 switches are set.
3995 This includes suppression of inlining that results
3996 from the use of the pragma @code{Inline_Always}.
3997 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3998 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3999 effect if this switch is present.
4000
4001 @item -fno-inline-functions
4002 @cindex @option{-fno-inline-functions} (@command{gcc})
4003 Suppresses automatic inlining of simple subprograms, which is enabled
4004 if @option{-O3} is used.
4005
4006 @item -fno-inline-small-functions
4007 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4008 Suppresses automatic inlining of small subprograms, which is enabled
4009 if @option{-O2} is used.
4010
4011 @item -fno-inline-functions-called-once
4012 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4013 Suppresses inlining of subprograms local to the unit and called once
4014 from within it, which is enabled if @option{-O1} is used.
4015
4016 @item -fno-ivopts
4017 @cindex @option{-fno-ivopts} (@command{gcc})
4018 Suppresses high-level loop induction variable optimizations, which are
4019 enabled if @option{-O1} is used. These optimizations are generally
4020 profitable but, for some specific cases of loops with numerous uses
4021 of the iteration variable that follow a common pattern, they may end
4022 up destroying the regularity that could be exploited at a lower level
4023 and thus producing inferior code.
4024
4025 @item -fno-strict-aliasing
4026 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4027 Causes the compiler to avoid assumptions regarding non-aliasing
4028 of objects of different types. See
4029 @ref{Optimization and Strict Aliasing} for details.
4030
4031 @item -fstack-check
4032 @cindex @option{-fstack-check} (@command{gcc})
4033 Activates stack checking.
4034 See @ref{Stack Overflow Checking} for details.
4035
4036 @item -fstack-usage
4037 @cindex @option{-fstack-usage} (@command{gcc})
4038 Makes the compiler output stack usage information for the program, on a
4039 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4040
4041 @item -fcallgraph-info@r{[}=su@r{]}
4042 @cindex @option{-fcallgraph-info} (@command{gcc})
4043 Makes the compiler output callgraph information for the program, on a
4044 per-file basis.  The information is generated in the VCG format.  It can
4045 be decorated with stack-usage per-node information.
4046
4047 @item ^-g^/DEBUG^
4048 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4049 Generate debugging information. This information is stored in the object
4050 file and copied from there to the final executable file by the linker,
4051 where it can be read by the debugger. You must use the
4052 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4053
4054 @item -gnat83
4055 @cindex @option{-gnat83} (@command{gcc})
4056 Enforce Ada 83 restrictions.
4057
4058 @item -gnat95
4059 @cindex @option{-gnat95} (@command{gcc})
4060 Enforce Ada 95 restrictions.
4061
4062 @item -gnat05
4063 @cindex @option{-gnat05} (@command{gcc})
4064 Allow full Ada 2005 features.
4065
4066 @item -gnata
4067 @cindex @option{-gnata} (@command{gcc})
4068 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4069 activated. Note that these pragmas can also be controlled using the
4070 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4071 It also activates pragmas @code{Check}, @code{Precondition}, and
4072 @code{Postcondition}. Note that these pragmas can also be controlled
4073 using the configuration pragma @code{Check_Policy}.
4074
4075 @item -gnatA
4076 @cindex @option{-gnatA} (@command{gcc})
4077 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4078 it will be ignored.
4079
4080 @item -gnatb
4081 @cindex @option{-gnatb} (@command{gcc})
4082 Generate brief messages to @file{stderr} even if verbose mode set.
4083
4084 @item -gnatB
4085 @cindex @option{-gnatB} (@command{gcc})
4086 Assume no invalid (bad) values except for 'Valid attribute use.
4087
4088 @item -gnatc
4089 @cindex @option{-gnatc} (@command{gcc})
4090 Check syntax and semantics only (no code generation attempted).
4091
4092 @item -gnatd
4093 @cindex @option{-gnatd} (@command{gcc})
4094 Specify debug options for the compiler. The string of characters after
4095 the @option{-gnatd} specify the specific debug options. The possible
4096 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4097 compiler source file @file{debug.adb} for details of the implemented
4098 debug options. Certain debug options are relevant to applications
4099 programmers, and these are documented at appropriate points in this
4100 users guide.
4101
4102 @ifclear vms
4103 @item -gnatD
4104 @cindex @option{-gnatD[nn]} (@command{gcc})
4105 @end ifclear
4106 @ifset vms
4107 @item /XDEBUG /LXDEBUG=nnn
4108 @end ifset
4109 Create expanded source files for source level debugging. This switch
4110 also suppress generation of cross-reference information
4111 (see @option{-gnatx}).
4112
4113 @item -gnatec=@var{path}
4114 @cindex @option{-gnatec} (@command{gcc})
4115 Specify a configuration pragma file
4116 @ifclear vms
4117 (the equal sign is optional)
4118 @end ifclear
4119 (@pxref{The Configuration Pragmas Files}).
4120
4121 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4122 @cindex @option{-gnateD} (@command{gcc})
4123 Defines a symbol, associated with @var{value}, for preprocessing.
4124 (@pxref{Integrated Preprocessing}).
4125
4126 @item -gnatef
4127 @cindex @option{-gnatef} (@command{gcc})
4128 Display full source path name in brief error messages.
4129
4130 @item -gnateG
4131 @cindex @option{-gnateG} (@command{gcc})
4132 Save result of preprocessing in a text file.
4133
4134 @item -gnatem=@var{path}
4135 @cindex @option{-gnatem} (@command{gcc})
4136 Specify a mapping file
4137 @ifclear vms
4138 (the equal sign is optional)
4139 @end ifclear
4140 (@pxref{Units to Sources Mapping Files}).
4141
4142 @item -gnatep=@var{file}
4143 @cindex @option{-gnatep} (@command{gcc})
4144 Specify a preprocessing data file
4145 @ifclear vms
4146 (the equal sign is optional)
4147 @end ifclear
4148 (@pxref{Integrated Preprocessing}).
4149
4150 @item -gnatE
4151 @cindex @option{-gnatE} (@command{gcc})
4152 Full dynamic elaboration checks.
4153
4154 @item -gnatf
4155 @cindex @option{-gnatf} (@command{gcc})
4156 Full errors. Multiple errors per line, all undefined references, do not
4157 attempt to suppress cascaded errors.
4158
4159 @item -gnatF
4160 @cindex @option{-gnatF} (@command{gcc})
4161 Externals names are folded to all uppercase.
4162
4163 @item ^-gnatg^/GNAT_INTERNAL^
4164 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4165 Internal GNAT implementation mode. This should not be used for
4166 applications programs, it is intended only for use by the compiler
4167 and its run-time library. For documentation, see the GNAT sources.
4168 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4169 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4170 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4171 so that all standard warnings and all standard style options are turned on.
4172 All warnings and style error messages are treated as errors.
4173
4174 @ifclear vms
4175 @item -gnatG=nn
4176 @cindex @option{-gnatG[nn]} (@command{gcc})
4177 @end ifclear
4178 @ifset vms
4179 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4180 @end ifset
4181 List generated expanded code in source form.
4182
4183 @item ^-gnath^/HELP^
4184 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4185 Output usage information. The output is written to @file{stdout}.
4186
4187 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4188 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4189 Identifier character set
4190 @ifclear vms
4191 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4192 @end ifclear
4193 For details of the possible selections for @var{c},
4194 see @ref{Character Set Control}.
4195
4196 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4197 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4198 Ignore representation clauses. When this switch is used,
4199 representation clauses are treated as comments. This is useful
4200 when initially porting code where you want to ignore rep clause
4201 problems, and also for compiling foreign code (particularly
4202 for use with ASIS). The representation clauses that are ignored
4203 are: enumeration_representation_clause, record_representation_clause,
4204 and attribute_definition_clause for the following attributes:
4205 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4206 Object_Size, Size, Small, Stream_Size, and Value_Size.
4207 Note that this option should be used only for compiling -- the
4208 code is likely to malfunction at run time.
4209
4210 @item -gnatjnn
4211 @cindex @option{-gnatjnn} (@command{gcc})
4212 Reformat error messages to fit on nn character lines
4213
4214 @item -gnatk=@var{n}
4215 @cindex @option{-gnatk} (@command{gcc})
4216 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4217
4218 @item -gnatl
4219 @cindex @option{-gnatl} (@command{gcc})
4220 Output full source listing with embedded error messages.
4221
4222 @item -gnatL
4223 @cindex @option{-gnatL} (@command{gcc})
4224 Used in conjunction with -gnatG or -gnatD to intersperse original
4225 source lines (as comment lines with line numbers) in the expanded
4226 source output.
4227
4228 @item -gnatm=@var{n}
4229 @cindex @option{-gnatm} (@command{gcc})
4230 Limit number of detected error or warning messages to @var{n}
4231 where @var{n} is in the range 1..999999. The default setting if
4232 no switch is given is 9999. If the number of warnings reaches this
4233 limit, then a message is output and further warnings are suppressed,
4234 but the compilation is continued. If the number of error messages
4235 reaches this limit, then a message is output and the compilation
4236 is abandoned. The equal sign here is optional. A value of zero
4237 means that no limit applies.
4238
4239 @item -gnatn
4240 @cindex @option{-gnatn} (@command{gcc})
4241 Activate inlining for subprograms for which
4242 pragma @code{inline} is specified. This inlining is performed
4243 by the GCC back-end.
4244
4245 @item -gnatN
4246 @cindex @option{-gnatN} (@command{gcc})
4247 Activate front end inlining for subprograms for which
4248 pragma @code{Inline} is specified. This inlining is performed
4249 by the front end and will be visible in the
4250 @option{-gnatG} output.
4251
4252 When using a gcc-based back end (in practice this means using any version
4253 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4254 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4255 Historically front end inlining was more extensive than the gcc back end
4256 inlining, but that is no longer the case.
4257
4258 @item -gnato
4259 @cindex @option{-gnato} (@command{gcc})
4260 Enable numeric overflow checking (which is not normally enabled by
4261 default). Note that division by zero is a separate check that is not
4262 controlled by this switch (division by zero checking is on by default).
4263
4264 @item -gnatp
4265 @cindex @option{-gnatp} (@command{gcc})
4266 Suppress all checks. See @ref{Run-Time Checks} for details.
4267
4268 @item -gnatP
4269 @cindex @option{-gnatP} (@command{gcc})
4270 Enable polling. This is required on some systems (notably Windows NT) to
4271 obtain asynchronous abort and asynchronous transfer of control capability.
4272 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4273 details.
4274
4275 @item -gnatq
4276 @cindex @option{-gnatq} (@command{gcc})
4277 Don't quit. Try semantics, even if parse errors.
4278
4279 @item -gnatQ
4280 @cindex @option{-gnatQ} (@command{gcc})
4281 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4282
4283 @item -gnatr
4284 @cindex @option{-gnatr} (@command{gcc})
4285 Treat pragma Restrictions as Restriction_Warnings.
4286
4287 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4288 @cindex @option{-gnatR} (@command{gcc})
4289 Output representation information for declared types and objects.
4290
4291 @item -gnats
4292 @cindex @option{-gnats} (@command{gcc})
4293 Syntax check only.
4294
4295 @item -gnatS
4296 @cindex @option{-gnatS} (@command{gcc})
4297 Print package Standard.
4298
4299 @item -gnatt
4300 @cindex @option{-gnatt} (@command{gcc})
4301 Generate tree output file.
4302
4303 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4304 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4305 All compiler tables start at @var{nnn} times usual starting size.
4306
4307 @item -gnatu
4308 @cindex @option{-gnatu} (@command{gcc})
4309 List units for this compilation.
4310
4311 @item -gnatU
4312 @cindex @option{-gnatU} (@command{gcc})
4313 Tag all error messages with the unique string ``error:''
4314
4315 @item -gnatv
4316 @cindex @option{-gnatv} (@command{gcc})
4317 Verbose mode. Full error output with source lines to @file{stdout}.
4318
4319 @item -gnatV
4320 @cindex @option{-gnatV} (@command{gcc})
4321 Control level of validity checking. See separate section describing
4322 this feature.
4323
4324 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4325 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4326 Warning mode where
4327 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4328 the exact warnings that
4329 are enabled or disabled (@pxref{Warning Message Control}).
4330
4331 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4332 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4333 Wide character encoding method
4334 @ifclear vms
4335 (@var{e}=n/h/u/s/e/8).
4336 @end ifclear
4337 @ifset vms
4338 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4339 @end ifset
4340
4341 @item -gnatx
4342 @cindex @option{-gnatx} (@command{gcc})
4343 Suppress generation of cross-reference information.
4344
4345 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4346 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4347 Enable built-in style checks (@pxref{Style Checking}).
4348
4349 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4350 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4351 Distribution stub generation and compilation
4352 @ifclear vms
4353 (@var{m}=r/c for receiver/caller stubs).
4354 @end ifclear
4355 @ifset vms
4356 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4357 to be generated and compiled).
4358 @end ifset
4359
4360 @item ^-I^/SEARCH=^@var{dir}
4361 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4362 @cindex RTL
4363 Direct GNAT to search the @var{dir} directory for source files needed by
4364 the current compilation
4365 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4366
4367 @item ^-I-^/NOCURRENT_DIRECTORY^
4368 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4369 @cindex RTL
4370 Except for the source file named in the command line, do not look for source
4371 files in the directory containing the source file named in the command line
4372 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4373
4374 @ifclear vms
4375 @item -mbig-switch
4376 @cindex @option{-mbig-switch} (@command{gcc})
4377 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4378 This standard gcc switch causes the compiler to use larger offsets in its
4379 jump table representation for @code{case} statements.
4380 This may result in less efficient code, but is sometimes necessary
4381 (for example on HP-UX targets)
4382 @cindex HP-UX and @option{-mbig-switch} option
4383 in order to compile large and/or nested @code{case} statements.
4384
4385 @item -o @var{file}
4386 @cindex @option{-o} (@command{gcc})
4387 This switch is used in @command{gcc} to redirect the generated object file
4388 and its associated ALI file. Beware of this switch with GNAT, because it may
4389 cause the object file and ALI file to have different names which in turn
4390 may confuse the binder and the linker.
4391 @end ifclear
4392
4393 @item -nostdinc
4394 @cindex @option{-nostdinc} (@command{gcc})
4395 Inhibit the search of the default location for the GNAT Run Time
4396 Library (RTL) source files.
4397
4398 @item -nostdlib
4399 @cindex @option{-nostdlib} (@command{gcc})
4400 Inhibit the search of the default location for the GNAT Run Time
4401 Library (RTL) ALI files.
4402
4403 @ifclear vms
4404 @item -O@ovar{n}
4405 @cindex @option{-O} (@command{gcc})
4406 @var{n} controls the optimization level.
4407
4408 @table @asis
4409 @item n = 0
4410 No optimization, the default setting if no @option{-O} appears
4411
4412 @item n = 1
4413 Normal optimization, the default if you specify @option{-O} without
4414 an operand. A good compromise between code quality and compilation
4415 time.
4416
4417 @item n = 2
4418 Extensive optimization, may improve execution time, possibly at the cost of
4419 substantially increased compilation time.
4420
4421 @item n = 3
4422 Same as @option{-O2}, and also includes inline expansion for small subprograms
4423 in the same unit.
4424
4425 @item n = s
4426 Optimize space usage
4427 @end table
4428
4429 @noindent
4430 See also @ref{Optimization Levels}.
4431 @end ifclear
4432
4433 @ifset vms
4434 @item  /NOOPTIMIZE
4435 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4436 Equivalent to @option{/OPTIMIZE=NONE}.
4437 This is the default behavior in the absence of an @option{/OPTIMIZE}
4438 qualifier.
4439
4440 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4441 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4442 Selects the level of optimization for your program. The supported
4443 keywords are as follows:
4444 @table @code
4445 @item   ALL
4446 Perform most optimizations, including those that
4447 are expensive.
4448 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4449 without keyword options.
4450
4451 @item   NONE
4452 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4453
4454 @item SOME
4455 Perform some optimizations, but omit ones that are costly.
4456
4457 @item   DEVELOPMENT
4458 Same as @code{SOME}.
4459
4460 @item INLINING
4461 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4462 automatic inlining of small subprograms within a unit
4463
4464 @item   UNROLL_LOOPS
4465 Try to unroll loops. This keyword may be specified together with
4466 any keyword above other than @code{NONE}. Loop unrolling
4467 usually, but not always, improves the performance of programs.
4468
4469 @item SPACE
4470 Optimize space usage
4471 @end table
4472
4473 @noindent
4474 See also @ref{Optimization Levels}.
4475 @end ifset
4476
4477 @ifclear vms
4478 @item -pass-exit-codes
4479 @cindex @option{-pass-exit-codes} (@command{gcc})
4480 Catch exit codes from the compiler and use the most meaningful as
4481 exit status.
4482 @end ifclear
4483
4484 @item --RTS=@var{rts-path}
4485 @cindex @option{--RTS} (@command{gcc})
4486 Specifies the default location of the runtime library. Same meaning as the
4487 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4488
4489 @item ^-S^/ASM^
4490 @cindex @option{^-S^/ASM^} (@command{gcc})
4491 ^Used in place of @option{-c} to^Used to^
4492 cause the assembler source file to be
4493 generated, using @file{^.s^.S^} as the extension,
4494 instead of the object file.
4495 This may be useful if you need to examine the generated assembly code.
4496
4497 @item ^-fverbose-asm^/VERBOSE_ASM^
4498 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4499 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4500 to cause the generated assembly code file to be annotated with variable
4501 names, making it significantly easier to follow.
4502
4503 @item ^-v^/VERBOSE^
4504 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4505 Show commands generated by the @command{gcc} driver. Normally used only for
4506 debugging purposes or if you need to be sure what version of the
4507 compiler you are executing.
4508
4509 @ifclear vms
4510 @item -V @var{ver}
4511 @cindex @option{-V} (@command{gcc})
4512 Execute @var{ver} version of the compiler. This is the @command{gcc}
4513 version, not the GNAT version.
4514 @end ifclear
4515
4516 @item ^-w^/NO_BACK_END_WARNINGS^
4517 @cindex @option{-w} (@command{gcc})
4518 Turn off warnings generated by the back end of the compiler. Use of
4519 this switch also causes the default for front end warnings to be set
4520 to suppress (as though @option{-gnatws} had appeared at the start of
4521 the options).
4522
4523 @end table
4524
4525 @ifclear vms
4526 @c Combining qualifiers does not work on VMS
4527 You may combine a sequence of GNAT switches into a single switch. For
4528 example, the combined switch
4529
4530 @cindex Combining GNAT switches
4531 @smallexample
4532 -gnatofi3
4533 @end smallexample
4534
4535 @noindent
4536 is equivalent to specifying the following sequence of switches:
4537
4538 @smallexample
4539 -gnato -gnatf -gnati3
4540 @end smallexample
4541 @end ifclear
4542
4543 @noindent
4544 The following restrictions apply to the combination of switches
4545 in this manner:
4546
4547 @itemize @bullet
4548 @item
4549 The switch @option{-gnatc} if combined with other switches must come
4550 first in the string.
4551
4552 @item
4553 The switch @option{-gnats} if combined with other switches must come
4554 first in the string.
4555
4556 @item
4557 The switches
4558 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4559 may not be combined with any other switches.
4560
4561 @ifclear vms
4562 @item
4563 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4564 switch), then all further characters in the switch are interpreted
4565 as style modifiers (see description of @option{-gnaty}).
4566
4567 @item
4568 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4569 switch), then all further characters in the switch are interpreted
4570 as debug flags (see description of @option{-gnatd}).
4571
4572 @item
4573 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4574 switch), then all further characters in the switch are interpreted
4575 as warning mode modifiers (see description of @option{-gnatw}).
4576
4577 @item
4578 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4579 switch), then all further characters in the switch are interpreted
4580 as validity checking options (see description of @option{-gnatV}).
4581 @end ifclear
4582 @end itemize
4583
4584 @node Output and Error Message Control
4585 @subsection Output and Error Message Control
4586 @findex stderr
4587
4588 @noindent
4589 The standard default format for error messages is called ``brief format''.
4590 Brief format messages are written to @file{stderr} (the standard error
4591 file) and have the following form:
4592
4593 @smallexample
4594 e.adb:3:04: Incorrect spelling of keyword "function"
4595 e.adb:4:20: ";" should be "is"
4596 @end smallexample
4597
4598 @noindent
4599 The first integer after the file name is the line number in the file,
4600 and the second integer is the column number within the line.
4601 @ifclear vms
4602 @code{GPS} can parse the error messages
4603 and point to the referenced character.
4604 @end ifclear
4605 The following switches provide control over the error message
4606 format:
4607
4608 @table @option
4609 @c !sort!
4610 @item -gnatv
4611 @cindex @option{-gnatv} (@command{gcc})
4612 @findex stdout
4613 @ifclear vms
4614 The v stands for verbose.
4615 @end ifclear
4616 The effect of this setting is to write long-format error
4617 messages to @file{stdout} (the standard output file.
4618 The same program compiled with the
4619 @option{-gnatv} switch would generate:
4620
4621 @smallexample
4622 @cartouche
4623 3. funcion X (Q : Integer)
4624    |
4625 >>> Incorrect spelling of keyword "function"
4626 4. return Integer;
4627                  |
4628 >>> ";" should be "is"
4629 @end cartouche
4630 @end smallexample
4631
4632 @noindent
4633 The vertical bar indicates the location of the error, and the @samp{>>>}
4634 prefix can be used to search for error messages. When this switch is
4635 used the only source lines output are those with errors.
4636
4637 @item -gnatl
4638 @cindex @option{-gnatl} (@command{gcc})
4639 @ifclear vms
4640 The @code{l} stands for list.
4641 @end ifclear
4642 This switch causes a full listing of
4643 the file to be generated. In the case where a body is
4644 compiled, the corresponding spec is also listed, along
4645 with any subunits. Typical output from compiling a package
4646 body @file{p.adb} might look like:
4647
4648 @smallexample @c ada
4649 @cartouche
4650  Compiling: p.adb
4651
4652      1. package body p is
4653      2.    procedure a;
4654      3.    procedure a is separate;
4655      4. begin
4656      5.    null
4657                |
4658         >>> missing ";"
4659
4660      6. end;
4661
4662 Compiling: p.ads
4663
4664      1. package p is
4665      2.    pragma Elaborate_Body
4666                                 |
4667         >>> missing ";"
4668
4669      3. end p;
4670
4671 Compiling: p-a.adb
4672
4673      1. separate p
4674                 |
4675         >>> missing "("
4676
4677      2. procedure a is
4678      3. begin
4679      4.    null
4680                |
4681         >>> missing ";"
4682
4683      5. end;
4684 @end cartouche
4685 @end smallexample
4686
4687 @noindent
4688 @findex stderr
4689 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4690 standard output is redirected, a brief summary is written to
4691 @file{stderr} (standard error) giving the number of error messages and
4692 warning messages generated.
4693
4694 @item -^gnatl^OUTPUT_FILE^=file
4695 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4696 This has the same effect as @option{-gnatl} except that the output is
4697 written to a file instead of to standard output. If the given name
4698 @file{fname} does not start with a period, then it is the full name
4699 of the file to be written. If @file{fname} is an extension, it is
4700 appended to the name of the file being compiled. For example, if
4701 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4702 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4703
4704 @item -gnatU
4705 @cindex @option{-gnatU} (@command{gcc})
4706 This switch forces all error messages to be preceded by the unique
4707 string ``error:''. This means that error messages take a few more
4708 characters in space, but allows easy searching for and identification
4709 of error messages.
4710
4711 @item -gnatb
4712 @cindex @option{-gnatb} (@command{gcc})
4713 @ifclear vms
4714 The @code{b} stands for brief.
4715 @end ifclear
4716 This switch causes GNAT to generate the
4717 brief format error messages to @file{stderr} (the standard error
4718 file) as well as the verbose
4719 format message or full listing (which as usual is written to
4720 @file{stdout} (the standard output file).
4721
4722 @item -gnatm=@var{n}
4723 @cindex @option{-gnatm} (@command{gcc})
4724 @ifclear vms
4725 The @code{m} stands for maximum.
4726 @end ifclear
4727 @var{n} is a decimal integer in the
4728 range of 1 to 999999 and limits the number of error or warning
4729 messages to be generated. For example, using
4730 @option{-gnatm2} might yield
4731
4732 @smallexample
4733 e.adb:3:04: Incorrect spelling of keyword "function"
4734 e.adb:5:35: missing ".."
4735 fatal error: maximum number of errors detected
4736 compilation abandoned
4737 @end smallexample
4738
4739 @noindent
4740 The default setting if
4741 no switch is given is 9999. If the number of warnings reaches this
4742 limit, then a message is output and further warnings are suppressed,
4743 but the compilation is continued. If the number of error messages
4744 reaches this limit, then a message is output and the compilation
4745 is abandoned. A value of zero means that no limit applies.
4746
4747 @noindent
4748 Note that the equal sign is optional, so the switches
4749 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4750
4751 @item -gnatf
4752 @cindex @option{-gnatf} (@command{gcc})
4753 @cindex Error messages, suppressing
4754 @ifclear vms
4755 The @code{f} stands for full.
4756 @end ifclear
4757 Normally, the compiler suppresses error messages that are likely to be
4758 redundant. This switch causes all error
4759 messages to be generated. In particular, in the case of
4760 references to undefined variables. If a given variable is referenced
4761 several times, the normal format of messages is
4762 @smallexample
4763 e.adb:7:07: "V" is undefined (more references follow)
4764 @end smallexample
4765
4766 @noindent
4767 where the parenthetical comment warns that there are additional
4768 references to the variable @code{V}. Compiling the same program with the
4769 @option{-gnatf} switch yields
4770
4771 @smallexample
4772 e.adb:7:07: "V" is undefined
4773 e.adb:8:07: "V" is undefined
4774 e.adb:8:12: "V" is undefined
4775 e.adb:8:16: "V" is undefined
4776 e.adb:9:07: "V" is undefined
4777 e.adb:9:12: "V" is undefined
4778 @end smallexample
4779
4780 @noindent
4781 The @option{-gnatf} switch also generates additional information for
4782 some error messages.  Some examples are:
4783
4784 @itemize @bullet
4785 @item
4786 Full details on entities not available in high integrity mode
4787 @item
4788 Details on possibly non-portable unchecked conversion
4789 @item
4790 List possible interpretations for ambiguous calls
4791 @item
4792 Additional details on incorrect parameters
4793 @end itemize
4794
4795 @item -gnatjnn
4796 @cindex @option{-gnatjnn} (@command{gcc})
4797 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4798 with continuation lines are treated as though the continuation lines were
4799 separate messages (and so a warning with two continuation lines counts as
4800 three warnings, and is listed as three separate messages).
4801
4802 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4803 messages are output in a different manner. A message and all its continuation
4804 lines are treated as a unit, and count as only one warning or message in the
4805 statistics totals. Furthermore, the message is reformatted so that no line
4806 is longer than nn characters.
4807
4808 @item -gnatq
4809 @cindex @option{-gnatq} (@command{gcc})
4810 @ifclear vms
4811 The @code{q} stands for quit (really ``don't quit'').
4812 @end ifclear
4813 In normal operation mode, the compiler first parses the program and
4814 determines if there are any syntax errors. If there are, appropriate
4815 error messages are generated and compilation is immediately terminated.
4816 This switch tells
4817 GNAT to continue with semantic analysis even if syntax errors have been
4818 found. This may enable the detection of more errors in a single run. On
4819 the other hand, the semantic analyzer is more likely to encounter some
4820 internal fatal error when given a syntactically invalid tree.
4821
4822 @item -gnatQ
4823 @cindex @option{-gnatQ} (@command{gcc})
4824 In normal operation mode, the @file{ALI} file is not generated if any
4825 illegalities are detected in the program. The use of @option{-gnatQ} forces
4826 generation of the @file{ALI} file. This file is marked as being in
4827 error, so it cannot be used for binding purposes, but it does contain
4828 reasonably complete cross-reference information, and thus may be useful
4829 for use by tools (e.g., semantic browsing tools or integrated development
4830 environments) that are driven from the @file{ALI} file. This switch
4831 implies @option{-gnatq}, since the semantic phase must be run to get a
4832 meaningful ALI file.
4833
4834 In addition, if @option{-gnatt} is also specified, then the tree file is
4835 generated even if there are illegalities. It may be useful in this case
4836 to also specify @option{-gnatq} to ensure that full semantic processing
4837 occurs. The resulting tree file can be processed by ASIS, for the purpose
4838 of providing partial information about illegal units, but if the error
4839 causes the tree to be badly malformed, then ASIS may crash during the
4840 analysis.
4841
4842 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4843 being in error, @command{gnatmake} will attempt to recompile the source when it
4844 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4845
4846 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4847 since ALI files are never generated if @option{-gnats} is set.
4848
4849 @end table
4850
4851 @node Warning Message Control
4852 @subsection Warning Message Control
4853 @cindex Warning messages
4854 @noindent
4855 In addition to error messages, which correspond to illegalities as defined
4856 in the Ada Reference Manual, the compiler detects two kinds of warning
4857 situations.
4858
4859 First, the compiler considers some constructs suspicious and generates a
4860 warning message to alert you to a possible error. Second, if the
4861 compiler detects a situation that is sure to raise an exception at
4862 run time, it generates a warning message. The following shows an example
4863 of warning messages:
4864 @smallexample
4865 e.adb:4:24: warning: creation of object may raise Storage_Error
4866 e.adb:10:17: warning: static value out of range
4867 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4868 @end smallexample
4869
4870 @noindent
4871 GNAT considers a large number of situations as appropriate
4872 for the generation of warning messages. As always, warnings are not
4873 definite indications of errors. For example, if you do an out-of-range
4874 assignment with the deliberate intention of raising a
4875 @code{Constraint_Error} exception, then the warning that may be
4876 issued does not indicate an error. Some of the situations for which GNAT
4877 issues warnings (at least some of the time) are given in the following
4878 list. This list is not complete, and new warnings are often added to
4879 subsequent versions of GNAT. The list is intended to give a general idea
4880 of the kinds of warnings that are generated.
4881
4882 @itemize @bullet
4883 @item
4884 Possible infinitely recursive calls
4885
4886 @item
4887 Out-of-range values being assigned
4888
4889 @item
4890 Possible order of elaboration problems
4891
4892 @item
4893 Assertions (pragma Assert) that are sure to fail
4894
4895 @item
4896 Unreachable code
4897
4898 @item
4899 Address clauses with possibly unaligned values, or where an attempt is
4900 made to overlay a smaller variable with a larger one.
4901
4902 @item
4903 Fixed-point type declarations with a null range
4904
4905 @item
4906 Direct_IO or Sequential_IO instantiated with a type that has access values
4907
4908 @item
4909 Variables that are never assigned a value
4910
4911 @item
4912 Variables that are referenced before being initialized
4913
4914 @item
4915 Task entries with no corresponding @code{accept} statement
4916
4917 @item
4918 Duplicate accepts for the same task entry in a @code{select}
4919
4920 @item
4921 Objects that take too much storage
4922
4923 @item
4924 Unchecked conversion between types of differing sizes
4925
4926 @item
4927 Missing @code{return} statement along some execution path in a function
4928
4929 @item
4930 Incorrect (unrecognized) pragmas
4931
4932 @item
4933 Incorrect external names
4934
4935 @item
4936 Allocation from empty storage pool
4937
4938 @item
4939 Potentially blocking operation in protected type
4940
4941 @item
4942 Suspicious parenthesization of expressions
4943
4944 @item
4945 Mismatching bounds in an aggregate
4946
4947 @item
4948 Attempt to return local value by reference
4949
4950 @item
4951 Premature instantiation of a generic body
4952
4953 @item
4954 Attempt to pack aliased components
4955
4956 @item
4957 Out of bounds array subscripts
4958
4959 @item
4960 Wrong length on string assignment
4961
4962 @item
4963 Violations of style rules if style checking is enabled
4964
4965 @item
4966 Unused @code{with} clauses
4967
4968 @item
4969 @code{Bit_Order} usage that does not have any effect
4970
4971 @item
4972 @code{Standard.Duration} used to resolve universal fixed expression
4973
4974 @item
4975 Dereference of possibly null value
4976
4977 @item
4978 Declaration that is likely to cause storage error
4979
4980 @item
4981 Internal GNAT unit @code{with}'ed by application unit
4982
4983 @item
4984 Values known to be out of range at compile time
4985
4986 @item
4987 Unreferenced labels and variables
4988
4989 @item
4990 Address overlays that could clobber memory
4991
4992 @item
4993 Unexpected initialization when address clause present
4994
4995 @item
4996 Bad alignment for address clause
4997
4998 @item
4999 Useless type conversions
5000
5001 @item
5002 Redundant assignment statements and other redundant constructs
5003
5004 @item
5005 Useless exception handlers
5006
5007 @item
5008 Accidental hiding of name by child unit
5009
5010 @item
5011 Access before elaboration detected at compile time
5012
5013 @item
5014 A range in a @code{for} loop that is known to be null or might be null
5015
5016 @end itemize
5017
5018 @noindent
5019 The following section lists compiler switches that are available
5020 to control the handling of warning messages. It is also possible
5021 to exercise much finer control over what warnings are issued and
5022 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5023 gnat_rm, GNAT Reference manual}.
5024
5025 @table @option
5026 @c !sort!
5027 @item -gnatwa
5028 @emph{Activate all optional errors.}
5029 @cindex @option{-gnatwa} (@command{gcc})
5030 This switch activates most optional warning messages, see remaining list
5031 in this section for details on optional warning messages that can be
5032 individually controlled.  The warnings that are not turned on by this
5033 switch are
5034 @option{-gnatwd} (implicit dereferencing),
5035 @option{-gnatwh} (hiding),
5036 @option{-gnatwl} (elaboration warnings),
5037 @option{-gnatw.o} (warn on values set by out parameters ignored)
5038 and @option{-gnatwt} (tracking of deleted conditional code).
5039 All other optional warnings are turned on.
5040
5041 @item -gnatwA
5042 @emph{Suppress all optional errors.}
5043 @cindex @option{-gnatwA} (@command{gcc})
5044 This switch suppresses all optional warning messages, see remaining list
5045 in this section for details on optional warning messages that can be
5046 individually controlled.
5047
5048 @item -gnatw.a
5049 @emph{Activate warnings on failing assertions.}
5050 @cindex @option{-gnatw.a} (@command{gcc})
5051 @cindex Assert failures
5052 This switch activates warnings for assertions where the compiler can tell at
5053 compile time that the assertion will fail. Note that this warning is given
5054 even if assertions are disabled. The default is that such warnings are
5055 generated.
5056
5057 @item -gnatw.A
5058 @emph{Suppress warnings on failing assertions.}
5059 @cindex @option{-gnatw.A} (@command{gcc})
5060 @cindex Assert failures
5061 This switch suppresses warnings for assertions where the compiler can tell at
5062 compile time that the assertion will fail.
5063
5064 @item -gnatwb
5065 @emph{Activate warnings on bad fixed values.}
5066 @cindex @option{-gnatwb} (@command{gcc})
5067 @cindex Bad fixed values
5068 @cindex Fixed-point Small value
5069 @cindex Small value
5070 This switch activates warnings for static fixed-point expressions whose
5071 value is not an exact multiple of Small. Such values are implementation
5072 dependent, since an implementation is free to choose either of the multiples
5073 that surround the value. GNAT always chooses the closer one, but this is not
5074 required behavior, and it is better to specify a value that is an exact
5075 multiple, ensuring predictable execution. The default is that such warnings
5076 are not generated.
5077
5078 @item -gnatwB
5079 @emph{Suppress warnings on bad fixed values.}
5080 @cindex @option{-gnatwB} (@command{gcc})
5081 This switch suppresses warnings for static fixed-point expressions whose
5082 value is not an exact multiple of Small.
5083
5084 @item -gnatw.b
5085 @emph{Activate warnings on biased representation.}
5086 @cindex @option{-gnatw.b} (@command{gcc})
5087 @cindex Biased representation
5088 This switch activates warnings when a size clause, value size clause, component
5089 clause, or component size clause forces the use of biased representation for an
5090 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5091 to represent 10/11). The default is that such warnings are generated.
5092
5093 @item -gnatw.B
5094 @emph{Suppress warnings on biased representation.}
5095 @cindex @option{-gnatwB} (@command{gcc})
5096 This switch suppresses warnings for representation clauses that force the use
5097 of biased representation.
5098
5099 @item -gnatwc
5100 @emph{Activate warnings on conditionals.}
5101 @cindex @option{-gnatwc} (@command{gcc})
5102 @cindex Conditionals, constant
5103 This switch activates warnings for conditional expressions used in
5104 tests that are known to be True or False at compile time. The default
5105 is that such warnings are not generated.
5106 Note that this warning does
5107 not get issued for the use of boolean variables or constants whose
5108 values are known at compile time, since this is a standard technique
5109 for conditional compilation in Ada, and this would generate too many
5110 false positive warnings.
5111
5112 This warning option also activates a special test for comparisons using
5113 the operators ``>='' and`` <=''.
5114 If the compiler can tell that only the equality condition is possible,
5115 then it will warn that the ``>'' or ``<'' part of the test
5116 is useless and that the operator could be replaced by ``=''.
5117 An example would be comparing a @code{Natural} variable <= 0.
5118
5119 This warning option also generates warnings if
5120 one or both tests is optimized away in a membership test for integer
5121 values if the result can be determined at compile time. Range tests on
5122 enumeration types are not included, since it is common for such tests
5123 to include an end point.
5124
5125 This warning can also be turned on using @option{-gnatwa}.
5126
5127 @item -gnatwC
5128 @emph{Suppress warnings on conditionals.}
5129 @cindex @option{-gnatwC} (@command{gcc})
5130 This switch suppresses warnings for conditional expressions used in
5131 tests that are known to be True or False at compile time.
5132
5133 @item -gnatw.c
5134 @emph{Activate warnings on missing component clauses.}
5135 @cindex @option{-gnatw.c} (@command{gcc})
5136 @cindex Component clause, missing
5137 This switch activates warnings for record components where a record
5138 representation clause is present and has component clauses for the
5139 majority, but not all, of the components. A warning is given for each
5140 component for which no component clause is present.
5141
5142 This warning can also be turned on using @option{-gnatwa}.
5143
5144 @item -gnatw.C
5145 @emph{Suppress warnings on missing component clauses.}
5146 @cindex @option{-gnatwC} (@command{gcc})
5147 This switch suppresses warnings for record components that are
5148 missing a component clause in the situation described above.
5149
5150 @item -gnatwd
5151 @emph{Activate warnings on implicit dereferencing.}
5152 @cindex @option{-gnatwd} (@command{gcc})
5153 If this switch is set, then the use of a prefix of an access type
5154 in an indexed component, slice, or selected component without an
5155 explicit @code{.all} will generate a warning. With this warning
5156 enabled, access checks occur only at points where an explicit
5157 @code{.all} appears in the source code (assuming no warnings are
5158 generated as a result of this switch). The default is that such
5159 warnings are not generated.
5160 Note that @option{-gnatwa} does not affect the setting of
5161 this warning option.
5162
5163 @item -gnatwD
5164 @emph{Suppress warnings on implicit dereferencing.}
5165 @cindex @option{-gnatwD} (@command{gcc})
5166 @cindex Implicit dereferencing
5167 @cindex Dereferencing, implicit
5168 This switch suppresses warnings for implicit dereferences in
5169 indexed components, slices, and selected components.
5170
5171 @item -gnatwe
5172 @emph{Treat warnings as errors.}
5173 @cindex @option{-gnatwe} (@command{gcc})
5174 @cindex Warnings, treat as error
5175 This switch causes warning messages to be treated as errors.
5176 The warning string still appears, but the warning messages are counted
5177 as errors, and prevent the generation of an object file.
5178
5179 @item -gnatw.e
5180 @emph{Activate every optional warning}
5181 @cindex @option{-gnatw.e} (@command{gcc})
5182 @cindex Warnings, activate every optional warning
5183 This switch activates all optional warnings, including those which
5184 are not activated by @code{-gnatwa}.
5185
5186 @item -gnatwf
5187 @emph{Activate warnings on unreferenced formals.}
5188 @cindex @option{-gnatwf} (@command{gcc})
5189 @cindex Formals, unreferenced
5190 This switch causes a warning to be generated if a formal parameter
5191 is not referenced in the body of the subprogram. This warning can
5192 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5193 default is that these warnings are not generated.
5194
5195 @item -gnatwF
5196 @emph{Suppress warnings on unreferenced formals.}
5197 @cindex @option{-gnatwF} (@command{gcc})
5198 This switch suppresses warnings for unreferenced formal
5199 parameters. Note that the
5200 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5201 effect of warning on unreferenced entities other than subprogram
5202 formals.
5203
5204 @item -gnatwg
5205 @emph{Activate warnings on unrecognized pragmas.}
5206 @cindex @option{-gnatwg} (@command{gcc})
5207 @cindex Pragmas, unrecognized
5208 This switch causes a warning to be generated if an unrecognized
5209 pragma is encountered. Apart from issuing this warning, the
5210 pragma is ignored and has no effect. This warning can
5211 also be turned on using @option{-gnatwa}. The default
5212 is that such warnings are issued (satisfying the Ada Reference
5213 Manual requirement that such warnings appear).
5214
5215 @item -gnatwG
5216 @emph{Suppress warnings on unrecognized pragmas.}
5217 @cindex @option{-gnatwG} (@command{gcc})
5218 This switch suppresses warnings for unrecognized pragmas.
5219
5220 @item -gnatwh
5221 @emph{Activate warnings on hiding.}
5222 @cindex @option{-gnatwh} (@command{gcc})
5223 @cindex Hiding of Declarations
5224 This switch activates warnings on hiding declarations.
5225 A declaration is considered hiding
5226 if it is for a non-overloadable entity, and it declares an entity with the
5227 same name as some other entity that is directly or use-visible. The default
5228 is that such warnings are not generated.
5229 Note that @option{-gnatwa} does not affect the setting of this warning option.
5230
5231 @item -gnatwH
5232 @emph{Suppress warnings on hiding.}
5233 @cindex @option{-gnatwH} (@command{gcc})
5234 This switch suppresses warnings on hiding declarations.
5235
5236 @item -gnatwi
5237 @emph{Activate warnings on implementation units.}
5238 @cindex @option{-gnatwi} (@command{gcc})
5239 This switch activates warnings for a @code{with} of an internal GNAT
5240 implementation unit, defined as any unit from the @code{Ada},
5241 @code{Interfaces}, @code{GNAT},
5242 ^^@code{DEC},^ or @code{System}
5243 hierarchies that is not
5244 documented in either the Ada Reference Manual or the GNAT
5245 Programmer's Reference Manual. Such units are intended only
5246 for internal implementation purposes and should not be @code{with}'ed
5247 by user programs. The default is that such warnings are generated
5248 This warning can also be turned on using @option{-gnatwa}.
5249
5250 @item -gnatwI
5251 @emph{Disable warnings on implementation units.}
5252 @cindex @option{-gnatwI} (@command{gcc})
5253 This switch disables warnings for a @code{with} of an internal GNAT
5254 implementation unit.
5255
5256 @item -gnatwj
5257 @emph{Activate warnings on obsolescent features (Annex J).}
5258 @cindex @option{-gnatwj} (@command{gcc})
5259 @cindex Features, obsolescent
5260 @cindex Obsolescent features
5261 If this warning option is activated, then warnings are generated for
5262 calls to subprograms marked with @code{pragma Obsolescent} and
5263 for use of features in Annex J of the Ada Reference Manual. In the
5264 case of Annex J, not all features are flagged. In particular use
5265 of the renamed packages (like @code{Text_IO}) and use of package
5266 @code{ASCII} are not flagged, since these are very common and
5267 would generate many annoying positive warnings. The default is that
5268 such warnings are not generated. This warning is also turned on by
5269 the use of @option{-gnatwa}.
5270
5271 In addition to the above cases, warnings are also generated for
5272 GNAT features that have been provided in past versions but which
5273 have been superseded (typically by features in the new Ada standard).
5274 For example, @code{pragma Ravenscar} will be flagged since its
5275 function is replaced by @code{pragma Profile(Ravenscar)}.
5276
5277 Note that this warning option functions differently from the
5278 restriction @code{No_Obsolescent_Features} in two respects.
5279 First, the restriction applies only to annex J features.
5280 Second, the restriction does flag uses of package @code{ASCII}.
5281
5282 @item -gnatwJ
5283 @emph{Suppress warnings on obsolescent features (Annex J).}
5284 @cindex @option{-gnatwJ} (@command{gcc})
5285 This switch disables warnings on use of obsolescent features.
5286
5287 @item -gnatwk
5288 @emph{Activate warnings on variables that could be constants.}
5289 @cindex @option{-gnatwk} (@command{gcc})
5290 This switch activates warnings for variables that are initialized but
5291 never modified, and then could be declared constants. The default is that
5292 such warnings are not given.
5293 This warning can also be turned on using @option{-gnatwa}.
5294
5295 @item -gnatwK
5296 @emph{Suppress warnings on variables that could be constants.}
5297 @cindex @option{-gnatwK} (@command{gcc})
5298 This switch disables warnings on variables that could be declared constants.
5299
5300 @item -gnatwl
5301 @emph{Activate warnings for elaboration pragmas.}
5302 @cindex @option{-gnatwl} (@command{gcc})
5303 @cindex Elaboration, warnings
5304 This switch activates warnings on missing
5305 @code{Elaborate_All} and @code{Elaborate} pragmas.
5306 See the section in this guide on elaboration checking for details on
5307 when such pragmas should be used. In dynamic elaboration mode, this switch
5308 generations warnings about the need to add elaboration pragmas. Note however,
5309 that if you blindly follow these warnings, and add @code{Elaborate_All}
5310 warnings wherever they are recommended, you basically end up with the
5311 equivalent of the static elaboration model, which may not be what you want for
5312 legacy code for which the static model does not work.
5313
5314 For the static model, the messages generated are labeled "info:" (for
5315 information messages). They are not warnings to add elaboration pragmas,
5316 merely informational messages showing what implicit elaboration pragmas
5317 have been added, for use in analyzing elaboration circularity problems.
5318
5319 Warnings are also generated if you
5320 are using the static mode of elaboration, and a @code{pragma Elaborate}
5321 is encountered. The default is that such warnings
5322 are not generated.
5323 This warning is not automatically turned on by the use of @option{-gnatwa}.
5324
5325 @item -gnatwL
5326 @emph{Suppress warnings for elaboration pragmas.}
5327 @cindex @option{-gnatwL} (@command{gcc})
5328 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5329 See the section in this guide on elaboration checking for details on
5330 when such pragmas should be used.
5331
5332 @item -gnatwm
5333 @emph{Activate warnings on modified but unreferenced variables.}
5334 @cindex @option{-gnatwm} (@command{gcc})
5335 This switch activates warnings for variables that are assigned (using
5336 an initialization value or with one or more assignment statements) but
5337 whose value is never read. The warning is suppressed for volatile
5338 variables and also for variables that are renamings of other variables
5339 or for which an address clause is given.
5340 This warning can also be turned on using @option{-gnatwa}.
5341 The default is that these warnings are not given.
5342
5343 @item -gnatwM
5344 @emph{Disable warnings on modified but unreferenced variables.}
5345 @cindex @option{-gnatwM} (@command{gcc})
5346 This switch disables warnings for variables that are assigned or
5347 initialized, but never read.
5348
5349 @item -gnatwn
5350 @emph{Set normal warnings mode.}
5351 @cindex @option{-gnatwn} (@command{gcc})
5352 This switch sets normal warning mode, in which enabled warnings are
5353 issued and treated as warnings rather than errors. This is the default
5354 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5355 an explicit @option{-gnatws} or
5356 @option{-gnatwe}. It also cancels the effect of the
5357 implicit @option{-gnatwe} that is activated by the
5358 use of @option{-gnatg}.
5359
5360 @item -gnatwo
5361 @emph{Activate warnings on address clause overlays.}
5362 @cindex @option{-gnatwo} (@command{gcc})
5363 @cindex Address Clauses, warnings
5364 This switch activates warnings for possibly unintended initialization
5365 effects of defining address clauses that cause one variable to overlap
5366 another. The default is that such warnings are generated.
5367 This warning can also be turned on using @option{-gnatwa}.
5368
5369 @item -gnatwO
5370 @emph{Suppress warnings on address clause overlays.}
5371 @cindex @option{-gnatwO} (@command{gcc})
5372 This switch suppresses warnings on possibly unintended initialization
5373 effects of defining address clauses that cause one variable to overlap
5374 another.
5375
5376 @item -gnatw.o
5377 @emph{Activate warnings on modified but unreferenced out parameters.}
5378 @cindex @option{-gnatw.o} (@command{gcc})
5379 This switch activates warnings for variables that are modified by using
5380 them as actuals for a call to a procedure with an out mode formal, where
5381 the resulting assigned value is never read. It is applicable in the case
5382 where there is more than one out mode formal. If there is only one out
5383 mode formal, the warning is issued by default (controlled by -gnatwu).
5384 The warning is suppressed for volatile
5385 variables and also for variables that are renamings of other variables
5386 or for which an address clause is given.
5387 The default is that these warnings are not given. Note that this warning
5388 is not included in -gnatwa, it must be activated explicitly.
5389
5390 @item -gnatw.O
5391 @emph{Disable warnings on modified but unreferenced out parameters.}
5392 @cindex @option{-gnatw.O} (@command{gcc})
5393 This switch suppresses warnings for variables that are modified by using
5394 them as actuals for a call to a procedure with an out mode formal, where
5395 the resulting assigned value is never read.
5396
5397 @item -gnatwp
5398 @emph{Activate warnings on ineffective pragma Inlines.}
5399 @cindex @option{-gnatwp} (@command{gcc})
5400 @cindex Inlining, warnings
5401 This switch activates warnings for failure of front end inlining
5402 (activated by @option{-gnatN}) to inline a particular call. There are
5403 many reasons for not being able to inline a call, including most
5404 commonly that the call is too complex to inline. The default is
5405 that such warnings are not given.
5406 This warning can also be turned on using @option{-gnatwa}.
5407 Warnings on ineffective inlining by the gcc back-end can be activated
5408 separately, using the gcc switch -Winline.
5409
5410 @item -gnatwP
5411 @emph{Suppress warnings on ineffective pragma Inlines.}
5412 @cindex @option{-gnatwP} (@command{gcc})
5413 This switch suppresses warnings on ineffective pragma Inlines. If the
5414 inlining mechanism cannot inline a call, it will simply ignore the
5415 request silently.
5416
5417 @item -gnatw.p
5418 @emph{Activate warnings on parameter ordering.}
5419 @cindex @option{-gnatw.p} (@command{gcc})
5420 @cindex Parameter order, warnings
5421 This switch activates warnings for cases of suspicious parameter
5422 ordering when the list of arguments are all simple identifiers that
5423 match the names of the formals, but are in a different order. The
5424 warning is suppressed if any use of named parameter notation is used,
5425 so this is the appropriate way to suppress a false positive (and
5426 serves to emphasize that the "misordering" is deliberate). The
5427 default is
5428 that such warnings are not given.
5429 This warning can also be turned on using @option{-gnatwa}.
5430
5431 @item -gnatw.P
5432 @emph{Suppress warnings on parameter ordering.}
5433 @cindex @option{-gnatw.P} (@command{gcc})
5434 This switch suppresses warnings on cases of suspicious parameter
5435 ordering.
5436
5437 @item -gnatwq
5438 @emph{Activate warnings on questionable missing parentheses.}
5439 @cindex @option{-gnatwq} (@command{gcc})
5440 @cindex Parentheses, warnings
5441 This switch activates warnings for cases where parentheses are not used and
5442 the result is potential ambiguity from a readers point of view. For example
5443 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5444 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5445 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5446 follow the rule of always parenthesizing to make the association clear, and
5447 this warning switch warns if such parentheses are not present. The default
5448 is that these warnings are given.
5449 This warning can also be turned on using @option{-gnatwa}.
5450
5451 @item -gnatwQ
5452 @emph{Suppress warnings on questionable missing parentheses.}
5453 @cindex @option{-gnatwQ} (@command{gcc})
5454 This switch suppresses warnings for cases where the association is not
5455 clear and the use of parentheses is preferred.
5456
5457 @item -gnatwr
5458 @emph{Activate warnings on redundant constructs.}
5459 @cindex @option{-gnatwr} (@command{gcc})
5460 This switch activates warnings for redundant constructs. The following
5461 is the current list of constructs regarded as redundant:
5462
5463 @itemize @bullet
5464 @item
5465 Assignment of an item to itself.
5466 @item
5467 Type conversion that converts an expression to its own type.
5468 @item
5469 Use of the attribute @code{Base} where @code{typ'Base} is the same
5470 as @code{typ}.
5471 @item
5472 Use of pragma @code{Pack} when all components are placed by a record
5473 representation clause.
5474 @item
5475 Exception handler containing only a reraise statement (raise with no
5476 operand) which has no effect.
5477 @item
5478 Use of the operator abs on an operand that is known at compile time
5479 to be non-negative
5480 @item
5481 Comparison of boolean expressions to an explicit True value.
5482 @end itemize
5483
5484 This warning can also be turned on using @option{-gnatwa}.
5485 The default is that warnings for redundant constructs are not given.
5486
5487 @item -gnatwR
5488 @emph{Suppress warnings on redundant constructs.}
5489 @cindex @option{-gnatwR} (@command{gcc})
5490 This switch suppresses warnings for redundant constructs.
5491
5492 @item -gnatws
5493 @emph{Suppress all warnings.}
5494 @cindex @option{-gnatws} (@command{gcc})
5495 This switch completely suppresses the
5496 output of all warning messages from the GNAT front end.
5497 Note that it does not suppress warnings from the @command{gcc} back end.
5498 To suppress these back end warnings as well, use the switch @option{-w}
5499 in addition to @option{-gnatws}.
5500
5501 @item -gnatwt
5502 @emph{Activate warnings for tracking of deleted conditional code.}
5503 @cindex @option{-gnatwt} (@command{gcc})
5504 @cindex Deactivated code, warnings
5505 @cindex Deleted code, warnings
5506 This switch activates warnings for tracking of code in conditionals (IF and
5507 CASE statements) that is detected to be dead code which cannot be executed, and
5508 which is removed by the front end. This warning is off by default, and is not
5509 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5510 useful for detecting deactivated code in certified applications.
5511
5512 @item -gnatwT
5513 @emph{Suppress warnings for tracking of deleted conditional code.}
5514 @cindex @option{-gnatwT} (@command{gcc})
5515 This switch suppresses warnings for tracking of deleted conditional code.
5516
5517 @item -gnatwu
5518 @emph{Activate warnings on unused entities.}
5519 @cindex @option{-gnatwu} (@command{gcc})
5520 This switch activates warnings to be generated for entities that
5521 are declared but not referenced, and for units that are @code{with}'ed
5522 and not
5523 referenced. In the case of packages, a warning is also generated if
5524 no entities in the package are referenced. This means that if the package
5525 is referenced but the only references are in @code{use}
5526 clauses or @code{renames}
5527 declarations, a warning is still generated. A warning is also generated
5528 for a generic package that is @code{with}'ed but never instantiated.
5529 In the case where a package or subprogram body is compiled, and there
5530 is a @code{with} on the corresponding spec
5531 that is only referenced in the body,
5532 a warning is also generated, noting that the
5533 @code{with} can be moved to the body. The default is that
5534 such warnings are not generated.
5535 This switch also activates warnings on unreferenced formals
5536 (it includes the effect of @option{-gnatwf}).
5537 This warning can also be turned on using @option{-gnatwa}.
5538
5539 @item -gnatwU
5540 @emph{Suppress warnings on unused entities.}
5541 @cindex @option{-gnatwU} (@command{gcc})
5542 This switch suppresses warnings for unused entities and packages.
5543 It also turns off warnings on unreferenced formals (and thus includes
5544 the effect of @option{-gnatwF}).
5545
5546 @item -gnatwv
5547 @emph{Activate warnings on unassigned variables.}
5548 @cindex @option{-gnatwv} (@command{gcc})
5549 @cindex Unassigned variable warnings
5550 This switch activates warnings for access to variables which
5551 may not be properly initialized. The default is that
5552 such warnings are generated.
5553 This warning can also be turned on using @option{-gnatwa}.
5554
5555 @item -gnatwV
5556 @emph{Suppress warnings on unassigned variables.}
5557 @cindex @option{-gnatwV} (@command{gcc})
5558 This switch suppresses warnings for access to variables which
5559 may not be properly initialized.
5560 For variables of a composite type, the warning can also be suppressed in
5561 Ada 2005 by using a default initialization with a box. For example, if
5562 Table is an array of records whose components are only partially uninitialized,
5563 then the following code:
5564
5565 @smallexample @c ada
5566    Tab : Table := (others => <>);
5567 @end smallexample
5568
5569 will suppress warnings on subsequent statements that access components
5570 of variable Tab.
5571
5572 @item -gnatww
5573 @emph{Activate warnings on wrong low bound assumption.}
5574 @cindex @option{-gnatww} (@command{gcc})
5575 @cindex String indexing warnings
5576 This switch activates warnings for indexing an unconstrained string parameter
5577 with a literal or S'Length. This is a case where the code is assuming that the
5578 low bound is one, which is in general not true (for example when a slice is
5579 passed). The default is that such warnings are generated.
5580 This warning can also be turned on using @option{-gnatwa}.
5581
5582 @item -gnatwW
5583 @emph{Suppress warnings on wrong low bound assumption.}
5584 @cindex @option{-gnatwW} (@command{gcc})
5585 This switch suppresses warnings for indexing an unconstrained string parameter
5586 with a literal or S'Length. Note that this warning can also be suppressed
5587 in a particular case by adding an
5588 assertion that the lower bound is 1,
5589 as shown in the following example.
5590
5591 @smallexample @c ada
5592    procedure K (S : String) is
5593       pragma Assert (S'First = 1);
5594       @dots{}
5595 @end smallexample
5596
5597 @item -gnatw.w
5598 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5599 @cindex @option{-gnatw.w} (@command{gcc})
5600 @cindex Warnings Off control
5601 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5602 where either the pragma is entirely useless (because it suppresses no
5603 warnings), or it could be replaced by @code{pragma Unreferenced} or
5604 @code{pragma Unmodified}.The default is that these warnings are not given.
5605 Note that this warning is not included in -gnatwa, it must be
5606 activated explicitly.
5607
5608 @item -gnatw.W
5609 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5610 @cindex @option{-gnatw.W} (@command{gcc})
5611 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5612
5613 @item -gnatwx
5614 @emph{Activate warnings on Export/Import pragmas.}
5615 @cindex @option{-gnatwx} (@command{gcc})
5616 @cindex Export/Import pragma warnings
5617 This switch activates warnings on Export/Import pragmas when
5618 the compiler detects a possible conflict between the Ada and
5619 foreign language calling sequences. For example, the use of
5620 default parameters in a convention C procedure is dubious
5621 because the C compiler cannot supply the proper default, so
5622 a warning is issued. The default is that such warnings are
5623 generated.
5624 This warning can also be turned on using @option{-gnatwa}.
5625
5626 @item -gnatwX
5627 @emph{Suppress warnings on Export/Import pragmas.}
5628 @cindex @option{-gnatwX} (@command{gcc})
5629 This switch suppresses warnings on Export/Import pragmas.
5630 The sense of this is that you are telling the compiler that
5631 you know what you are doing in writing the pragma, and it
5632 should not complain at you.
5633
5634 @item -gnatw.x
5635 @emph{Activate warnings for No_Exception_Propagation mode.}
5636 @cindex @option{-gnatwm} (@command{gcc})
5637 This switch activates warnings for exception usage when pragma Restrictions
5638 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5639 explicit exception raises which are not covered by a local handler, and for
5640 exception handlers which do not cover a local raise. The default is that these
5641 warnings are not given.
5642
5643 @item -gnatw.X
5644 @emph{Disable warnings for No_Exception_Propagation mode.}
5645 This switch disables warnings for exception usage when pragma Restrictions
5646 (No_Exception_Propagation) is in effect.
5647
5648 @item -gnatwy
5649 @emph{Activate warnings for Ada 2005 compatibility issues.}
5650 @cindex @option{-gnatwy} (@command{gcc})
5651 @cindex Ada 2005 compatibility issues warnings
5652 For the most part Ada 2005 is upwards compatible with Ada 95,
5653 but there are some exceptions (for example the fact that
5654 @code{interface} is now a reserved word in Ada 2005). This
5655 switch activates several warnings to help in identifying
5656 and correcting such incompatibilities. The default is that
5657 these warnings are generated. Note that at one point Ada 2005
5658 was called Ada 0Y, hence the choice of character.
5659 This warning can also be turned on using @option{-gnatwa}.
5660
5661 @item -gnatwY
5662 @emph{Disable warnings for Ada 2005 compatibility issues.}
5663 @cindex @option{-gnatwY} (@command{gcc})
5664 @cindex Ada 2005 compatibility issues warnings
5665 This switch suppresses several warnings intended to help in identifying
5666 incompatibilities between Ada 95 and Ada 2005.
5667
5668 @item -gnatwz
5669 @emph{Activate warnings on unchecked conversions.}
5670 @cindex @option{-gnatwz} (@command{gcc})
5671 @cindex Unchecked_Conversion warnings
5672 This switch activates warnings for unchecked conversions
5673 where the types are known at compile time to have different
5674 sizes. The default
5675 is that such warnings are generated. Warnings are also
5676 generated for subprogram pointers with different conventions,
5677 and, on VMS only, for data pointers with different conventions.
5678 This warning can also be turned on using @option{-gnatwa}.
5679
5680 @item -gnatwZ
5681 @emph{Suppress warnings on unchecked conversions.}
5682 @cindex @option{-gnatwZ} (@command{gcc})
5683 This switch suppresses warnings for unchecked conversions
5684 where the types are known at compile time to have different
5685 sizes or conventions.
5686
5687 @item ^-Wunused^WARNINGS=UNUSED^
5688 @cindex @option{-Wunused}
5689 The warnings controlled by the @option{-gnatw} switch are generated by
5690 the front end of the compiler. The @option{GCC} back end can provide
5691 additional warnings and they are controlled by the @option{-W} switch.
5692 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5693 warnings for entities that are declared but not referenced.
5694
5695 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5696 @cindex @option{-Wuninitialized}
5697 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5698 the back end warning for uninitialized variables. This switch must be
5699 used in conjunction with an optimization level greater than zero.
5700
5701 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5702 @cindex @option{-Wall}
5703 This switch enables all the above warnings from the @option{GCC} back end.
5704 The code generator detects a number of warning situations that are missed
5705 by the @option{GNAT} front end, and this switch can be used to activate them.
5706 The use of this switch also sets the default front end warning mode to
5707 @option{-gnatwa}, that is, most front end warnings activated as well.
5708
5709 @item ^-w^/NO_BACK_END_WARNINGS^
5710 @cindex @option{-w}
5711 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5712 The use of this switch also sets the default front end warning mode to
5713 @option{-gnatws}, that is, front end warnings suppressed as well.
5714
5715 @end table
5716
5717 @noindent
5718 @ifclear vms
5719 A string of warning parameters can be used in the same parameter. For example:
5720
5721 @smallexample
5722 -gnatwaLe
5723 @end smallexample
5724
5725 @noindent
5726 will turn on all optional warnings except for elaboration pragma warnings,
5727 and also specify that warnings should be treated as errors.
5728 @end ifclear
5729 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5730
5731 @table @option
5732 @c !sort!
5733 @item -gnatwC
5734 @item -gnatwD
5735 @item -gnatwF
5736 @item -gnatwg
5737 @item -gnatwH
5738 @item -gnatwi
5739 @item -gnatwJ
5740 @item -gnatwK
5741 @item -gnatwL
5742 @item -gnatwM
5743 @item -gnatwn
5744 @item -gnatwo
5745 @item -gnatwP
5746 @item -gnatwR
5747 @item -gnatwU
5748 @item -gnatwv
5749 @item -gnatwz
5750 @item -gnatwx
5751
5752 @end table
5753
5754 @node Debugging and Assertion Control
5755 @subsection Debugging and Assertion Control
5756
5757 @table @option
5758 @item -gnata
5759 @cindex @option{-gnata} (@command{gcc})
5760 @findex Assert
5761 @findex Debug
5762 @cindex Assertions
5763
5764 @noindent
5765 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5766 are ignored. This switch, where @samp{a} stands for assert, causes
5767 @code{Assert} and @code{Debug} pragmas to be activated.
5768
5769 The pragmas have the form:
5770
5771 @smallexample
5772 @cartouche
5773    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5774                       @var{static-string-expression}@r{]})
5775    @b{pragma} Debug (@var{procedure call})
5776 @end cartouche
5777 @end smallexample
5778
5779 @noindent
5780 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5781 If the result is @code{True}, the pragma has no effect (other than
5782 possible side effects from evaluating the expression). If the result is
5783 @code{False}, the exception @code{Assert_Failure} declared in the package
5784 @code{System.Assertions} is
5785 raised (passing @var{static-string-expression}, if present, as the
5786 message associated with the exception). If no string expression is
5787 given the default is a string giving the file name and line number
5788 of the pragma.
5789
5790 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5791 @code{pragma Debug} may appear within a declaration sequence, allowing
5792 debugging procedures to be called between declarations.
5793
5794 @ifset vms
5795 @item /DEBUG@r{[}=debug-level@r{]}
5796 @itemx  /NODEBUG
5797 Specifies how much debugging information is to be included in
5798 the resulting object file where 'debug-level' is one of the following:
5799 @table @code
5800 @item   TRACEBACK
5801 Include both debugger symbol records and traceback
5802 the object file.
5803 This is the default setting.
5804 @item   ALL
5805 Include both debugger symbol records and traceback in
5806 object file.
5807 @item   NONE
5808 Excludes both debugger symbol records and traceback
5809 the object file. Same as /NODEBUG.
5810 @item   SYMBOLS
5811 Includes only debugger symbol records in the object
5812 file. Note that this doesn't include traceback information.
5813 @end table
5814 @end ifset
5815 @end table
5816
5817 @node Validity Checking
5818 @subsection Validity Checking
5819 @findex Validity Checking
5820
5821 @noindent
5822 The Ada Reference Manual has specific requirements for checking
5823 for invalid values. In particular, RM 13.9.1 requires that the
5824 evaluation of invalid values (for example from unchecked conversions),
5825 not result in erroneous execution. In GNAT, the result of such an
5826 evaluation in normal default mode is to either use the value
5827 unmodified, or to raise Constraint_Error in those cases where use
5828 of the unmodified value would cause erroneous execution. The cases
5829 where unmodified values might lead to erroneous execution are case
5830 statements (where a wild jump might result from an invalid value),
5831 and subscripts on the left hand side (where memory corruption could
5832 occur as a result of an invalid value).
5833
5834 The @option{-gnatB} switch tells the compiler to assume that all
5835 values are valid (that is, within their declared subtype range)
5836 except in the context of a use of the Valid attribute. This means
5837 the compiler can generate more efficient code, since the range
5838 of values is better known at compile time.
5839
5840 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5841 checking mode.
5842 @ifclear vms
5843 The @code{x} argument is a string of letters that
5844 indicate validity checks that are performed or not performed in addition
5845 to the default checks described above.
5846 @end ifclear
5847 @ifset vms
5848 The options allowed for this qualifier
5849 indicate validity checks that are performed or not performed in addition
5850 to the default checks described above.
5851 @end ifset
5852
5853 @table @option
5854 @c !sort!
5855 @item -gnatVa
5856 @emph{All validity checks.}
5857 @cindex @option{-gnatVa} (@command{gcc})
5858 All validity checks are turned on.
5859 @ifclear vms
5860 That is, @option{-gnatVa} is
5861 equivalent to @option{gnatVcdfimorst}.
5862 @end ifclear
5863
5864 @item -gnatVc
5865 @emph{Validity checks for copies.}
5866 @cindex @option{-gnatVc} (@command{gcc})
5867 The right hand side of assignments, and the initializing values of
5868 object declarations are validity checked.
5869
5870 @item -gnatVd
5871 @emph{Default (RM) validity checks.}
5872 @cindex @option{-gnatVd} (@command{gcc})
5873 Some validity checks are done by default following normal Ada semantics
5874 (RM 13.9.1 (9-11)).
5875 A check is done in case statements that the expression is within the range
5876 of the subtype. If it is not, Constraint_Error is raised.
5877 For assignments to array components, a check is done that the expression used
5878 as index is within the range. If it is not, Constraint_Error is raised.
5879 Both these validity checks may be turned off using switch @option{-gnatVD}.
5880 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5881 switch @option{-gnatVd} will leave the checks turned on.
5882 Switch @option{-gnatVD} should be used only if you are sure that all such
5883 expressions have valid values. If you use this switch and invalid values
5884 are present, then the program is erroneous, and wild jumps or memory
5885 overwriting may occur.
5886
5887 @item -gnatVe
5888 @emph{Validity checks for elementary components.}
5889 @cindex @option{-gnatVe} (@command{gcc})
5890 In the absence of this switch, assignments to record or array components are
5891 not validity checked, even if validity checks for assignments generally
5892 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5893 require valid data, but assignment of individual components does. So for
5894 example, there is a difference between copying the elements of an array with a
5895 slice assignment, compared to assigning element by element in a loop. This
5896 switch allows you to turn off validity checking for components, even when they
5897 are assigned component by component.
5898
5899 @item -gnatVf
5900 @emph{Validity checks for floating-point values.}
5901 @cindex @option{-gnatVf} (@command{gcc})
5902 In the absence of this switch, validity checking occurs only for discrete
5903 values. If @option{-gnatVf} is specified, then validity checking also applies
5904 for floating-point values, and NaNs and infinities are considered invalid,
5905 as well as out of range values for constrained types. Note that this means
5906 that standard IEEE infinity mode is not allowed. The exact contexts
5907 in which floating-point values are checked depends on the setting of other
5908 options. For example,
5909 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5910 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5911 (the order does not matter) specifies that floating-point parameters of mode
5912 @code{in} should be validity checked.
5913
5914 @item -gnatVi
5915 @emph{Validity checks for @code{in} mode parameters}
5916 @cindex @option{-gnatVi} (@command{gcc})
5917 Arguments for parameters of mode @code{in} are validity checked in function
5918 and procedure calls at the point of call.
5919
5920 @item -gnatVm
5921 @emph{Validity checks for @code{in out} mode parameters.}
5922 @cindex @option{-gnatVm} (@command{gcc})
5923 Arguments for parameters of mode @code{in out} are validity checked in
5924 procedure calls at the point of call. The @code{'m'} here stands for
5925 modify, since this concerns parameters that can be modified by the call.
5926 Note that there is no specific option to test @code{out} parameters,
5927 but any reference within the subprogram will be tested in the usual
5928 manner, and if an invalid value is copied back, any reference to it
5929 will be subject to validity checking.
5930
5931 @item -gnatVn
5932 @emph{No validity checks.}
5933 @cindex @option{-gnatVn} (@command{gcc})
5934 This switch turns off all validity checking, including the default checking
5935 for case statements and left hand side subscripts. Note that the use of
5936 the switch @option{-gnatp} suppresses all run-time checks, including
5937 validity checks, and thus implies @option{-gnatVn}. When this switch
5938 is used, it cancels any other @option{-gnatV} previously issued.
5939
5940 @item -gnatVo
5941 @emph{Validity checks for operator and attribute operands.}
5942 @cindex @option{-gnatVo} (@command{gcc})
5943 Arguments for predefined operators and attributes are validity checked.
5944 This includes all operators in package @code{Standard},
5945 the shift operators defined as intrinsic in package @code{Interfaces}
5946 and operands for attributes such as @code{Pos}. Checks are also made
5947 on individual component values for composite comparisons, and on the
5948 expressions in type conversions and qualified expressions. Checks are
5949 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5950
5951 @item -gnatVp
5952 @emph{Validity checks for parameters.}
5953 @cindex @option{-gnatVp} (@command{gcc})
5954 This controls the treatment of parameters within a subprogram (as opposed
5955 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5956 of parameters on a call. If either of these call options is used, then
5957 normally an assumption is made within a subprogram that the input arguments
5958 have been validity checking at the point of call, and do not need checking
5959 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5960 is not made, and parameters are not assumed to be valid, so their validity
5961 will be checked (or rechecked) within the subprogram.
5962
5963 @item -gnatVr
5964 @emph{Validity checks for function returns.}
5965 @cindex @option{-gnatVr} (@command{gcc})
5966 The expression in @code{return} statements in functions is validity
5967 checked.
5968
5969 @item -gnatVs
5970 @emph{Validity checks for subscripts.}
5971 @cindex @option{-gnatVs} (@command{gcc})
5972 All subscripts expressions are checked for validity, whether they appear
5973 on the right side or left side (in default mode only left side subscripts
5974 are validity checked).
5975
5976 @item -gnatVt
5977 @emph{Validity checks for tests.}
5978 @cindex @option{-gnatVt} (@command{gcc})
5979 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5980 statements are checked, as well as guard expressions in entry calls.
5981
5982 @end table
5983
5984 @noindent
5985 The @option{-gnatV} switch may be followed by
5986 ^a string of letters^a list of options^
5987 to turn on a series of validity checking options.
5988 For example,
5989 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5990 specifies that in addition to the default validity checking, copies and
5991 function return expressions are to be validity checked.
5992 In order to make it easier
5993 to specify the desired combination of effects,
5994 @ifclear vms
5995 the upper case letters @code{CDFIMORST} may
5996 be used to turn off the corresponding lower case option.
5997 @end ifclear
5998 @ifset vms
5999 the prefix @code{NO} on an option turns off the corresponding validity
6000 checking:
6001 @itemize @bullet
6002 @item @code{NOCOPIES}
6003 @item @code{NODEFAULT}
6004 @item @code{NOFLOATS}
6005 @item @code{NOIN_PARAMS}
6006 @item @code{NOMOD_PARAMS}
6007 @item @code{NOOPERANDS}
6008 @item @code{NORETURNS}
6009 @item @code{NOSUBSCRIPTS}
6010 @item @code{NOTESTS}
6011 @end itemize
6012 @end ifset
6013 Thus
6014 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6015 turns on all validity checking options except for
6016 checking of @code{@b{in out}} procedure arguments.
6017
6018 The specification of additional validity checking generates extra code (and
6019 in the case of @option{-gnatVa} the code expansion can be substantial).
6020 However, these additional checks can be very useful in detecting
6021 uninitialized variables, incorrect use of unchecked conversion, and other
6022 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6023 is useful in conjunction with the extra validity checking, since this
6024 ensures that wherever possible uninitialized variables have invalid values.
6025
6026 See also the pragma @code{Validity_Checks} which allows modification of
6027 the validity checking mode at the program source level, and also allows for
6028 temporary disabling of validity checks.
6029
6030 @node Style Checking
6031 @subsection Style Checking
6032 @findex Style checking
6033
6034 @noindent
6035 The @option{-gnaty^x^(option,option,@dots{})^} switch
6036 @cindex @option{-gnaty} (@command{gcc})
6037 causes the compiler to
6038 enforce specified style rules. A limited set of style rules has been used
6039 in writing the GNAT sources themselves. This switch allows user programs
6040 to activate all or some of these checks. If the source program fails a
6041 specified style check, an appropriate warning message is given, preceded by
6042 the character sequence ``(style)''.
6043 @ifset vms
6044 @code{(option,option,@dots{})} is a sequence of keywords
6045 @end ifset
6046 @ifclear vms
6047 The string @var{x} is a sequence of letters or digits
6048 @end ifclear
6049 indicating the particular style
6050 checks to be performed. The following checks are defined:
6051
6052 @table @option
6053 @c !sort!
6054 @item 0-9
6055 @emph{Specify indentation level.}
6056 If a digit from 1-9 appears
6057 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6058 then proper indentation is checked, with the digit indicating the
6059 indentation level required. A value of zero turns off this style check.
6060 The general style of required indentation is as specified by
6061 the examples in the Ada Reference Manual. Full line comments must be
6062 aligned with the @code{--} starting on a column that is a multiple of
6063 the alignment level, or they may be aligned the same way as the following
6064 non-blank line (this is useful when full line comments appear in the middle
6065 of a statement.
6066
6067 @item ^a^ATTRIBUTE^
6068 @emph{Check attribute casing.}
6069 Attribute names, including the case of keywords such as @code{digits}
6070 used as attributes names, must be written in mixed case, that is, the
6071 initial letter and any letter following an underscore must be uppercase.
6072 All other letters must be lowercase.
6073
6074 @item ^A^ARRAY_INDEXES^
6075 @emph{Use of array index numbers in array attributes.}
6076 When using the array attributes First, Last, Range,
6077 or Length, the index number must be omitted for one-dimensional arrays
6078 and is required for multi-dimensional arrays.
6079
6080 @item ^b^BLANKS^
6081 @emph{Blanks not allowed at statement end.}
6082 Trailing blanks are not allowed at the end of statements. The purpose of this
6083 rule, together with h (no horizontal tabs), is to enforce a canonical format
6084 for the use of blanks to separate source tokens.
6085
6086 @item ^c^COMMENTS^
6087 @emph{Check comments.}
6088 Comments must meet the following set of rules:
6089
6090 @itemize @bullet
6091
6092 @item
6093 The ``@code{--}'' that starts the column must either start in column one,
6094 or else at least one blank must precede this sequence.
6095
6096 @item
6097 Comments that follow other tokens on a line must have at least one blank
6098 following the ``@code{--}'' at the start of the comment.
6099
6100 @item
6101 Full line comments must have two blanks following the ``@code{--}'' that
6102 starts the comment, with the following exceptions.
6103
6104 @item
6105 A line consisting only of the ``@code{--}'' characters, possibly preceded
6106 by blanks is permitted.
6107
6108 @item
6109 A comment starting with ``@code{--x}'' where @code{x} is a special character
6110 is permitted.
6111 This allows proper processing of the output generated by specialized tools
6112 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6113 annotation
6114 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6115 special character is defined as being in one of the ASCII ranges
6116 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6117 Note that this usage is not permitted
6118 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6119
6120 @item
6121 A line consisting entirely of minus signs, possibly preceded by blanks, is
6122 permitted. This allows the construction of box comments where lines of minus
6123 signs are used to form the top and bottom of the box.
6124
6125 @item
6126 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6127 least one blank follows the initial ``@code{--}''. Together with the preceding
6128 rule, this allows the construction of box comments, as shown in the following
6129 example:
6130 @smallexample
6131 ---------------------------
6132 -- This is a box comment --
6133 -- with two text lines.  --
6134 ---------------------------
6135 @end smallexample
6136 @end itemize
6137
6138 @item ^d^DOS_LINE_ENDINGS^
6139 @emph{Check no DOS line terminators present.}
6140 All lines must be terminated by a single ASCII.LF
6141 character (in particular the DOS line terminator sequence CR/LF is not
6142 allowed).
6143
6144 @item ^e^END^
6145 @emph{Check end/exit labels.}
6146 Optional labels on @code{end} statements ending subprograms and on
6147 @code{exit} statements exiting named loops, are required to be present.
6148
6149 @item ^f^VTABS^
6150 @emph{No form feeds or vertical tabs.}
6151 Neither form feeds nor vertical tab characters are permitted
6152 in the source text.
6153
6154 @item ^g^GNAT^
6155 @emph{GNAT style mode}
6156 The set of style check switches is set to match that used by the GNAT sources.
6157 This may be useful when developing code that is eventually intended to be
6158 incorporated into GNAT. For further details, see GNAT sources.
6159
6160 @item ^h^HTABS^
6161 @emph{No horizontal tabs.}
6162 Horizontal tab characters are not permitted in the source text.
6163 Together with the b (no blanks at end of line) check, this
6164 enforces a canonical form for the use of blanks to separate
6165 source tokens.
6166
6167 @item ^i^IF_THEN^
6168 @emph{Check if-then layout.}
6169 The keyword @code{then} must appear either on the same
6170 line as corresponding @code{if}, or on a line on its own, lined
6171 up under the @code{if} with at least one non-blank line in between
6172 containing all or part of the condition to be tested.
6173
6174 @item ^I^IN_MODE^
6175 @emph{check mode IN keywords}
6176 Mode @code{in} (the default mode) is not
6177 allowed to be given explicitly. @code{in out} is fine,
6178 but not @code{in} on its own.
6179
6180 @item ^k^KEYWORD^
6181 @emph{Check keyword casing.}
6182 All keywords must be in lower case (with the exception of keywords
6183 such as @code{digits} used as attribute names to which this check
6184 does not apply).
6185
6186 @item ^l^LAYOUT^
6187 @emph{Check layout.}
6188 Layout of statement and declaration constructs must follow the
6189 recommendations in the Ada Reference Manual, as indicated by the
6190 form of the syntax rules. For example an @code{else} keyword must
6191 be lined up with the corresponding @code{if} keyword.
6192
6193 There are two respects in which the style rule enforced by this check
6194 option are more liberal than those in the Ada Reference Manual. First
6195 in the case of record declarations, it is permissible to put the
6196 @code{record} keyword on the same line as the @code{type} keyword, and
6197 then the @code{end} in @code{end record} must line up under @code{type}.
6198 This is also permitted when the type declaration is split on two lines.
6199 For example, any of the following three layouts is acceptable:
6200
6201 @smallexample @c ada
6202 @cartouche
6203 type q is record
6204    a : integer;
6205    b : integer;
6206 end record;
6207
6208 type q is
6209    record
6210       a : integer;
6211       b : integer;
6212    end record;
6213
6214 type q is
6215    record
6216       a : integer;
6217       b : integer;
6218 end record;
6219
6220 @end cartouche
6221 @end smallexample
6222
6223 @noindent
6224 Second, in the case of a block statement, a permitted alternative
6225 is to put the block label on the same line as the @code{declare} or
6226 @code{begin} keyword, and then line the @code{end} keyword up under
6227 the block label. For example both the following are permitted:
6228
6229 @smallexample @c ada
6230 @cartouche
6231 Block : declare
6232    A : Integer := 3;
6233 begin
6234    Proc (A, A);
6235 end Block;
6236
6237 Block :
6238    declare
6239       A : Integer := 3;
6240    begin
6241       Proc (A, A);
6242    end Block;
6243 @end cartouche
6244 @end smallexample
6245
6246 @noindent
6247 The same alternative format is allowed for loops. For example, both of
6248 the following are permitted:
6249
6250 @smallexample @c ada
6251 @cartouche
6252 Clear : while J < 10 loop
6253    A (J) := 0;
6254 end loop Clear;
6255
6256 Clear :
6257    while J < 10 loop
6258       A (J) := 0;
6259    end loop Clear;
6260 @end cartouche
6261 @end smallexample
6262
6263 @item ^Lnnn^MAX_NESTING=nnn^
6264 @emph{Set maximum nesting level}
6265 The maximum level of nesting of constructs (including subprograms, loops,
6266 blocks, packages, and conditionals) may not exceed the given value
6267 @option{nnn}. A value of zero disconnects this style check.
6268
6269 @item ^m^LINE_LENGTH^
6270 @emph{Check maximum line length.}
6271 The length of source lines must not exceed 79 characters, including
6272 any trailing blanks. The value of 79 allows convenient display on an
6273 80 character wide device or window, allowing for possible special
6274 treatment of 80 character lines. Note that this count is of
6275 characters in the source text. This means that a tab character counts
6276 as one character in this count but a wide character sequence counts as
6277 a single character (however many bytes are needed in the encoding).
6278
6279 @item ^Mnnn^MAX_LENGTH=nnn^
6280 @emph{Set maximum line length.}
6281 The length of lines must not exceed the
6282 given value @option{nnn}. The maximum value that can be specified is 32767.
6283
6284 @item ^n^STANDARD_CASING^
6285 @emph{Check casing of entities in Standard.}
6286 Any identifier from Standard must be cased
6287 to match the presentation in the Ada Reference Manual (for example,
6288 @code{Integer} and @code{ASCII.NUL}).
6289
6290 @item ^N^NONE^
6291 @emph{Turn off all style checks}
6292 All style check options are turned off.
6293
6294 @item ^o^ORDERED_SUBPROGRAMS^
6295 @emph{Check order of subprogram bodies.}
6296 All subprogram bodies in a given scope
6297 (e.g.@: a package body) must be in alphabetical order. The ordering
6298 rule uses normal Ada rules for comparing strings, ignoring casing
6299 of letters, except that if there is a trailing numeric suffix, then
6300 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6301 before Junk10).
6302
6303 @item ^O^OVERRIDING_INDICATORS^
6304 @emph{Check that overriding subprograms are explicitly marked as such.}
6305 The declaration of a primitive operation of a type extension that overrides
6306 an inherited operation must carry an overriding indicator.
6307
6308 @item ^p^PRAGMA^
6309 @emph{Check pragma casing.}
6310 Pragma names must be written in mixed case, that is, the
6311 initial letter and any letter following an underscore must be uppercase.
6312 All other letters must be lowercase.
6313
6314 @item ^r^REFERENCES^
6315 @emph{Check references.}
6316 All identifier references must be cased in the same way as the
6317 corresponding declaration. No specific casing style is imposed on
6318 identifiers. The only requirement is for consistency of references
6319 with declarations.
6320
6321 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6322 @emph{Check no statements after THEN/ELSE.}
6323 No statements are allowed
6324 on the same line as a THEN or ELSE keyword following the
6325 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6326 and a special exception allows a pragma to appear after ELSE.
6327
6328 @item ^s^SPECS^
6329 @emph{Check separate specs.}
6330 Separate declarations (``specs'') are required for subprograms (a
6331 body is not allowed to serve as its own declaration). The only
6332 exception is that parameterless library level procedures are
6333 not required to have a separate declaration. This exception covers
6334 the most frequent form of main program procedures.
6335
6336 @item ^t^TOKEN^
6337 @emph{Check token spacing.}
6338 The following token spacing rules are enforced:
6339
6340 @itemize @bullet
6341
6342 @item
6343 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6344
6345 @item
6346 The token @code{=>} must be surrounded by spaces.
6347
6348 @item
6349 The token @code{<>} must be preceded by a space or a left parenthesis.
6350
6351 @item
6352 Binary operators other than @code{**} must be surrounded by spaces.
6353 There is no restriction on the layout of the @code{**} binary operator.
6354
6355 @item
6356 Colon must be surrounded by spaces.
6357
6358 @item
6359 Colon-equal (assignment, initialization) must be surrounded by spaces.
6360
6361 @item
6362 Comma must be the first non-blank character on the line, or be
6363 immediately preceded by a non-blank character, and must be followed
6364 by a space.
6365
6366 @item
6367 If the token preceding a left parenthesis ends with a letter or digit, then
6368 a space must separate the two tokens.
6369
6370 @item
6371 A right parenthesis must either be the first non-blank character on
6372 a line, or it must be preceded by a non-blank character.
6373
6374 @item
6375 A semicolon must not be preceded by a space, and must not be followed by
6376 a non-blank character.
6377
6378 @item
6379 A unary plus or minus may not be followed by a space.
6380
6381 @item
6382 A vertical bar must be surrounded by spaces.
6383 @end itemize
6384
6385 @item ^u^UNNECESSARY_BLANK_LINES^
6386 @emph{Check unnecessary blank lines.}
6387 Unnecessary blank lines are not allowed. A blank line is considered
6388 unnecessary if it appears at the end of the file, or if more than
6389 one blank line occurs in sequence.
6390
6391 @item ^x^XTRA_PARENS^
6392 @emph{Check extra parentheses.}
6393 Unnecessary extra level of parentheses (C-style) are not allowed
6394 around conditions in @code{if} statements, @code{while} statements and
6395 @code{exit} statements.
6396
6397 @item ^y^ALL_BUILTIN^
6398 @emph{Set all standard style check options}
6399 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6400 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6401 @option{-gnatyS}, @option{-gnatyLnnn},
6402 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6403
6404 @ifclear vms
6405 @item -
6406 @emph{Remove style check options}
6407 This causes any subsequent options in the string to act as canceling the
6408 corresponding style check option. To cancel maximum nesting level control,
6409 use @option{L} parameter witout any integer value after that, because any
6410 digit following @option{-} in the parameter string of the @option{-gnaty}
6411 option will be threated as canceling indentation check. The same is true
6412 for @option{M} parameter. @option{y} and @option{N} parameters are not
6413 allowed after @option{-}.
6414
6415 @item +
6416 This causes any subsequent options in the string to enable the corresponding
6417 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6418 if any.
6419 @end ifclear
6420
6421 @ifset vms
6422 @item NOxxx
6423 @emph{Removing style check options}
6424 If the name of a style check is preceded by @option{NO} then the corresponding
6425 style check is turned off. For example @option{NOCOMMENTS} turns off style
6426 checking for comments.
6427 @end ifset
6428 @end table
6429
6430 @noindent
6431 In the above rules, appearing in column one is always permitted, that is,
6432 counts as meeting either a requirement for a required preceding space,
6433 or as meeting a requirement for no preceding space.
6434
6435 Appearing at the end of a line is also always permitted, that is, counts
6436 as meeting either a requirement for a following space, or as meeting
6437 a requirement for no following space.
6438
6439 @noindent
6440 If any of these style rules is violated, a message is generated giving
6441 details on the violation. The initial characters of such messages are
6442 always ``@code{(style)}''. Note that these messages are treated as warning
6443 messages, so they normally do not prevent the generation of an object
6444 file. The @option{-gnatwe} switch can be used to treat warning messages,
6445 including style messages, as fatal errors.
6446
6447 The switch
6448 @ifclear vms
6449 @option{-gnaty} on its own (that is not
6450 followed by any letters or digits), then the effect is equivalent
6451 to the use of @option{-gnatyy}, as described above, that is all
6452 built-in standard style check options are enabled.
6453
6454 @end ifclear
6455 @ifset vms
6456 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6457 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6458 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6459 @end ifset
6460
6461
6462
6463 The switch
6464 @ifclear vms
6465 @option{-gnatyN}
6466 @end ifclear
6467 @ifset vms
6468 /STYLE_CHECKS=NONE
6469 @end ifset
6470 clears any previously set style checks.
6471
6472 @node Run-Time Checks
6473 @subsection Run-Time Checks
6474 @cindex Division by zero
6475 @cindex Access before elaboration
6476 @cindex Checks, division by zero
6477 @cindex Checks, access before elaboration
6478 @cindex Checks, stack overflow checking
6479
6480 @noindent
6481 By default, the following checks are suppressed: integer overflow
6482 checks, stack overflow checks, and checks for access before
6483 elaboration on subprogram calls. All other checks, including range
6484 checks and array bounds checks, are turned on by default. The
6485 following @command{gcc} switches refine this default behavior.
6486
6487 @table @option
6488 @c !sort!
6489 @item -gnatp
6490 @cindex @option{-gnatp} (@command{gcc})
6491 @cindex Suppressing checks
6492 @cindex Checks, suppressing
6493 @findex Suppress
6494 Suppress all run-time checks as though @code{pragma Suppress (All_checks)}
6495 had been present in the source. Validity checks are also suppressed (in
6496 other words @option{-gnatp} also implies @option{-gnatVn}.
6497 Use this switch to improve the performance
6498 of the code at the expense of safety in the presence of invalid data or
6499 program bugs.
6500
6501 Note that when checks are suppressed, the compiler is allowed, but not
6502 required, to omit the checking code. If the run-time cost of the
6503 checking code is zero or near-zero, the compiler will generate it even
6504 if checks are suppressed. In particular, if the compiler can prove
6505 that a certain check will necessarily fail, it will generate code to
6506 do an unconditional ``raise'', even if checks are suppressed. The
6507 compiler warns in this case.
6508
6509 Of course, run-time checks are omitted whenever the compiler can prove
6510 that they will not fail, whether or not checks are suppressed.
6511
6512 Note that if you suppress a check that would have failed, program
6513 execution is erroneous, which means the behavior is totally
6514 unpredictable. The program might crash, or print wrong answers, or
6515 do anything else. It might even do exactly what you wanted it to do
6516 (and then it might start failing mysteriously next week or next
6517 year). The compiler will generate code based on the assumption that
6518 the condition being checked is true, which can result in disaster if
6519 that assumption is wrong.
6520
6521 @item -gnato
6522 @cindex @option{-gnato} (@command{gcc})
6523 @cindex Overflow checks
6524 @cindex Check, overflow
6525 Enables overflow checking for integer operations.
6526 This causes GNAT to generate slower and larger executable
6527 programs by adding code to check for overflow (resulting in raising
6528 @code{Constraint_Error} as required by standard Ada
6529 semantics). These overflow checks correspond to situations in which
6530 the true value of the result of an operation may be outside the base
6531 range of the result type. The following example shows the distinction:
6532
6533 @smallexample @c ada
6534 X1 : Integer := "Integer'Last";
6535 X2 : Integer range 1 .. 5 := "5";
6536 X3 : Integer := "Integer'Last";
6537 X4 : Integer range 1 .. 5 := "5";
6538 F  : Float := "2.0E+20";
6539 @dots{}
6540 X1 := X1 + 1;
6541 X2 := X2 + 1;
6542 X3 := Integer (F);
6543 X4 := Integer (F);
6544 @end smallexample
6545
6546 @noindent
6547 Note that if explicit values are assigned at compile time, the
6548 compiler may be able to detect overflow at compile time, in which case
6549 no actual run-time checking code is required, and Constraint_Error
6550 will be raised unconditionally, with or without
6551 @option{-gnato}. That's why the assigned values in the above fragment
6552 are in quotes, the meaning is "assign a value not known to the
6553 compiler that happens to be equal to ...". The remaining discussion
6554 assumes that the compiler cannot detect the values at compile time.
6555
6556 Here the first addition results in a value that is outside the base range
6557 of Integer, and hence requires an overflow check for detection of the
6558 constraint error. Thus the first assignment to @code{X1} raises a
6559 @code{Constraint_Error} exception only if @option{-gnato} is set.
6560
6561 The second increment operation results in a violation of the explicit
6562 range constraint; such range checks are performed by default, and are
6563 unaffected by @option{-gnato}.
6564
6565 The two conversions of @code{F} both result in values that are outside
6566 the base range of type @code{Integer} and thus will raise
6567 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6568 The fact that the result of the second conversion is assigned to
6569 variable @code{X4} with a restricted range is irrelevant, since the problem
6570 is in the conversion, not the assignment.
6571
6572 Basically the rule is that in the default mode (@option{-gnato} not
6573 used), the generated code assures that all integer variables stay
6574 within their declared ranges, or within the base range if there is
6575 no declared range. This prevents any serious problems like indexes
6576 out of range for array operations.
6577
6578 What is not checked in default mode is an overflow that results in
6579 an in-range, but incorrect value. In the above example, the assignments
6580 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6581 range of the target variable, but the result is wrong in the sense that
6582 it is too large to be represented correctly. Typically the assignment
6583 to @code{X1} will result in wrap around to the largest negative number.
6584 The conversions of @code{F} will result in some @code{Integer} value
6585 and if that integer value is out of the @code{X4} range then the
6586 subsequent assignment would generate an exception.
6587
6588 @findex Machine_Overflows
6589 Note that the @option{-gnato} switch does not affect the code generated
6590 for any floating-point operations; it applies only to integer
6591 semantics).
6592 For floating-point, GNAT has the @code{Machine_Overflows}
6593 attribute set to @code{False} and the normal mode of operation is to
6594 generate IEEE NaN and infinite values on overflow or invalid operations
6595 (such as dividing 0.0 by 0.0).
6596
6597 The reason that we distinguish overflow checking from other kinds of
6598 range constraint checking is that a failure of an overflow check, unlike
6599 for example the failure of a range check, can result in an incorrect
6600 value, but cannot cause random memory destruction (like an out of range
6601 subscript), or a wild jump (from an out of range case value). Overflow
6602 checking is also quite expensive in time and space, since in general it
6603 requires the use of double length arithmetic.
6604
6605 Note again that @option{-gnato} is off by default, so overflow checking is
6606 not performed in default mode. This means that out of the box, with the
6607 default settings, GNAT does not do all the checks expected from the
6608 language description in the Ada Reference Manual. If you want all constraint
6609 checks to be performed, as described in this Manual, then you must
6610 explicitly use the -gnato switch either on the @command{gnatmake} or
6611 @command{gcc} command.
6612
6613 @item -gnatE
6614 @cindex @option{-gnatE} (@command{gcc})
6615 @cindex Elaboration checks
6616 @cindex Check, elaboration
6617 Enables dynamic checks for access-before-elaboration
6618 on subprogram calls and generic instantiations.
6619 Note that @option{-gnatE} is not necessary for safety, because in the
6620 default mode, GNAT ensures statically that the checks would not fail.
6621 For full details of the effect and use of this switch,
6622 @xref{Compiling Using gcc}.
6623
6624 @item -fstack-check
6625 @cindex @option{-fstack-check} (@command{gcc})
6626 @cindex Stack Overflow Checking
6627 @cindex Checks, stack overflow checking
6628 Activates stack overflow checking. For full details of the effect and use of
6629 this switch see @ref{Stack Overflow Checking}.
6630 @end table
6631
6632 @findex Unsuppress
6633 @noindent
6634 The setting of these switches only controls the default setting of the
6635 checks. You may modify them using either @code{Suppress} (to remove
6636 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6637 the program source.
6638
6639 @node Using gcc for Syntax Checking
6640 @subsection Using @command{gcc} for Syntax Checking
6641 @table @option
6642 @item -gnats
6643 @cindex @option{-gnats} (@command{gcc})
6644 @ifclear vms
6645
6646 @noindent
6647 The @code{s} stands for ``syntax''.
6648 @end ifclear
6649
6650 Run GNAT in syntax checking only mode. For
6651 example, the command
6652
6653 @smallexample
6654 $ gcc -c -gnats x.adb
6655 @end smallexample
6656
6657 @noindent
6658 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6659 series of files in a single command
6660 @ifclear vms
6661 , and can use wild cards to specify such a group of files.
6662 Note that you must specify the @option{-c} (compile
6663 only) flag in addition to the @option{-gnats} flag.
6664 @end ifclear
6665 .
6666 You may use other switches in conjunction with @option{-gnats}. In
6667 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6668 format of any generated error messages.
6669
6670 When the source file is empty or contains only empty lines and/or comments,
6671 the output is a warning:
6672
6673 @smallexample
6674 $ gcc -c -gnats -x ada toto.txt
6675 toto.txt:1:01: warning: empty file, contains no compilation units
6676 $
6677 @end smallexample
6678
6679 Otherwise, the output is simply the error messages, if any. No object file or
6680 ALI file is generated by a syntax-only compilation. Also, no units other
6681 than the one specified are accessed. For example, if a unit @code{X}
6682 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6683 check only mode does not access the source file containing unit
6684 @code{Y}.
6685
6686 @cindex Multiple units, syntax checking
6687 Normally, GNAT allows only a single unit in a source file. However, this
6688 restriction does not apply in syntax-check-only mode, and it is possible
6689 to check a file containing multiple compilation units concatenated
6690 together. This is primarily used by the @code{gnatchop} utility
6691 (@pxref{Renaming Files Using gnatchop}).
6692 @end table
6693
6694 @node Using gcc for Semantic Checking
6695 @subsection Using @command{gcc} for Semantic Checking
6696 @table @option
6697 @item -gnatc
6698 @cindex @option{-gnatc} (@command{gcc})
6699
6700 @ifclear vms
6701 @noindent
6702 The @code{c} stands for ``check''.
6703 @end ifclear
6704 Causes the compiler to operate in semantic check mode,
6705 with full checking for all illegalities specified in the
6706 Ada Reference Manual, but without generation of any object code
6707 (no object file is generated).
6708
6709 Because dependent files must be accessed, you must follow the GNAT
6710 semantic restrictions on file structuring to operate in this mode:
6711
6712 @itemize @bullet
6713 @item
6714 The needed source files must be accessible
6715 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6716
6717 @item
6718 Each file must contain only one compilation unit.
6719
6720 @item
6721 The file name and unit name must match (@pxref{File Naming Rules}).
6722 @end itemize
6723
6724 The output consists of error messages as appropriate. No object file is
6725 generated. An @file{ALI} file is generated for use in the context of
6726 cross-reference tools, but this file is marked as not being suitable
6727 for binding (since no object file is generated).
6728 The checking corresponds exactly to the notion of
6729 legality in the Ada Reference Manual.
6730
6731 Any unit can be compiled in semantics-checking-only mode, including
6732 units that would not normally be compiled (subunits,
6733 and specifications where a separate body is present).
6734 @end table
6735
6736 @node Compiling Different Versions of Ada
6737 @subsection Compiling Different Versions of Ada
6738
6739 @noindent
6740 The switches described in this section allow you to explicitly specify
6741 the version of the Ada language that your programs are written in.
6742 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6743 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6744 indicate Ada 83 compatibility mode.
6745
6746 @table @option
6747 @cindex Compatibility with Ada 83
6748
6749 @item -gnat83 (Ada 83 Compatibility Mode)
6750 @cindex @option{-gnat83} (@command{gcc})
6751 @cindex ACVC, Ada 83 tests
6752 @cindex Ada 83 mode
6753
6754 @noindent
6755 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6756 specifies that the program is to be compiled in Ada 83 mode. With
6757 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6758 semantics where this can be done easily.
6759 It is not possible to guarantee this switch does a perfect
6760 job; some subtle tests, such as are
6761 found in earlier ACVC tests (and that have been removed from the ACATS suite
6762 for Ada 95), might not compile correctly.
6763 Nevertheless, this switch may be useful in some circumstances, for example
6764 where, due to contractual reasons, existing code needs to be maintained
6765 using only Ada 83 features.
6766
6767 With few exceptions (most notably the need to use @code{<>} on
6768 @cindex Generic formal parameters
6769 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6770 reserved words, and the use of packages
6771 with optional bodies), it is not necessary to specify the
6772 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6773 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6774 a correct Ada 83 program is usually also a correct program
6775 in these later versions of the language standard.
6776 For further information, please refer to @ref{Compatibility and Porting Guide}.
6777
6778 @item -gnat95 (Ada 95 mode)
6779 @cindex @option{-gnat95} (@command{gcc})
6780 @cindex Ada 95 mode
6781
6782 @noindent
6783 This switch directs the compiler to implement the Ada 95 version of the
6784 language.
6785 Since Ada 95 is almost completely upwards
6786 compatible with Ada 83, Ada 83 programs may generally be compiled using
6787 this switch (see the description of the @option{-gnat83} switch for further
6788 information about Ada 83 mode).
6789 If an Ada 2005 program is compiled in Ada 95 mode,
6790 uses of the new Ada 2005 features will cause error
6791 messages or warnings.
6792
6793 This switch also can be used to cancel the effect of a previous
6794 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6795
6796 @item -gnat05 (Ada 2005 mode)
6797 @cindex @option{-gnat05} (@command{gcc})
6798 @cindex Ada 2005 mode
6799
6800 @noindent
6801 This switch directs the compiler to implement the Ada 2005 version of the
6802 language.
6803 Since Ada 2005 is almost completely upwards
6804 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6805 may generally be compiled using this switch (see the description of the
6806 @option{-gnat83} and @option{-gnat95} switches for further
6807 information).
6808
6809 For information about the approved ``Ada Issues'' that have been incorporated
6810 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6811 Included with GNAT releases is a file @file{features-ada0y} that describes
6812 the set of implemented Ada 2005 features.
6813 @end table
6814
6815
6816 @node Character Set Control
6817 @subsection Character Set Control
6818 @table @option
6819 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6820 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6821
6822 @noindent
6823 Normally GNAT recognizes the Latin-1 character set in source program
6824 identifiers, as described in the Ada Reference Manual.
6825 This switch causes
6826 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6827 single character ^^or word^ indicating the character set, as follows:
6828
6829 @table @code
6830 @item 1
6831 ISO 8859-1 (Latin-1) identifiers
6832
6833 @item 2
6834 ISO 8859-2 (Latin-2) letters allowed in identifiers
6835
6836 @item 3
6837 ISO 8859-3 (Latin-3) letters allowed in identifiers
6838
6839 @item 4
6840 ISO 8859-4 (Latin-4) letters allowed in identifiers
6841
6842 @item 5
6843 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6844
6845 @item 9
6846 ISO 8859-15 (Latin-9) letters allowed in identifiers
6847
6848 @item ^p^PC^
6849 IBM PC letters (code page 437) allowed in identifiers
6850
6851 @item ^8^PC850^
6852 IBM PC letters (code page 850) allowed in identifiers
6853
6854 @item ^f^FULL_UPPER^
6855 Full upper-half codes allowed in identifiers
6856
6857 @item ^n^NO_UPPER^
6858 No upper-half codes allowed in identifiers
6859
6860 @item ^w^WIDE^
6861 Wide-character codes (that is, codes greater than 255)
6862 allowed in identifiers
6863 @end table
6864
6865 @xref{Foreign Language Representation}, for full details on the
6866 implementation of these character sets.
6867
6868 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6869 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6870 Specify the method of encoding for wide characters.
6871 @var{e} is one of the following:
6872
6873 @table @code
6874
6875 @item ^h^HEX^
6876 Hex encoding (brackets coding also recognized)
6877
6878 @item ^u^UPPER^
6879 Upper half encoding (brackets encoding also recognized)
6880
6881 @item ^s^SHIFT_JIS^
6882 Shift/JIS encoding (brackets encoding also recognized)
6883
6884 @item ^e^EUC^
6885 EUC encoding (brackets encoding also recognized)
6886
6887 @item ^8^UTF8^
6888 UTF-8 encoding (brackets encoding also recognized)
6889
6890 @item ^b^BRACKETS^
6891 Brackets encoding only (default value)
6892 @end table
6893 For full details on these encoding
6894 methods see @ref{Wide Character Encodings}.
6895 Note that brackets coding is always accepted, even if one of the other
6896 options is specified, so for example @option{-gnatW8} specifies that both
6897 brackets and UTF-8 encodings will be recognized. The units that are
6898 with'ed directly or indirectly will be scanned using the specified
6899 representation scheme, and so if one of the non-brackets scheme is
6900 used, it must be used consistently throughout the program. However,
6901 since brackets encoding is always recognized, it may be conveniently
6902 used in standard libraries, allowing these libraries to be used with
6903 any of the available coding schemes.
6904 scheme.
6905
6906 If no @option{-gnatW?} parameter is present, then the default
6907 representation is normally Brackets encoding only. However, if the
6908 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6909 byte order mark or BOM for UTF-8), then these three characters are
6910 skipped and the default representation for the file is set to UTF-8.
6911
6912 Note that the wide character representation that is specified (explicitly
6913 or by default) for the main program also acts as the default encoding used
6914 for Wide_Text_IO files if not specifically overridden by a WCEM form
6915 parameter.
6916
6917 @end table
6918 @node File Naming Control
6919 @subsection File Naming Control
6920
6921 @table @option
6922 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6923 @cindex @option{-gnatk} (@command{gcc})
6924 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6925 1-999, indicates the maximum allowable length of a file name (not
6926 including the @file{.ads} or @file{.adb} extension). The default is not
6927 to enable file name krunching.
6928
6929 For the source file naming rules, @xref{File Naming Rules}.
6930 @end table
6931
6932 @node Subprogram Inlining Control
6933 @subsection Subprogram Inlining Control
6934
6935 @table @option
6936 @c !sort!
6937 @item -gnatn
6938 @cindex @option{-gnatn} (@command{gcc})
6939 @ifclear vms
6940 The @code{n} here is intended to suggest the first syllable of the
6941 word ``inline''.
6942 @end ifclear
6943 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6944 inlining to actually occur, optimization must be enabled. To enable
6945 inlining of subprograms specified by pragma @code{Inline},
6946 you must also specify this switch.
6947 In the absence of this switch, GNAT does not attempt
6948 inlining and does not need to access the bodies of
6949 subprograms for which @code{pragma Inline} is specified if they are not
6950 in the current unit.
6951
6952 If you specify this switch the compiler will access these bodies,
6953 creating an extra source dependency for the resulting object file, and
6954 where possible, the call will be inlined.
6955 For further details on when inlining is possible
6956 see @ref{Inlining of Subprograms}.
6957
6958 @item -gnatN
6959 @cindex @option{-gnatN} (@command{gcc})
6960 This switch activates front-end inlining which also
6961 generates additional dependencies.
6962
6963 When using a gcc-based back end (in practice this means using any version
6964 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6965 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6966 Historically front end inlining was more extensive than the gcc back end
6967 inlining, but that is no longer the case.
6968 @end table
6969
6970 @node Auxiliary Output Control
6971 @subsection Auxiliary Output Control
6972
6973 @table @option
6974 @item -gnatt
6975 @cindex @option{-gnatt} (@command{gcc})
6976 @cindex Writing internal trees
6977 @cindex Internal trees, writing to file
6978 Causes GNAT to write the internal tree for a unit to a file (with the
6979 extension @file{.adt}.
6980 This not normally required, but is used by separate analysis tools.
6981 Typically
6982 these tools do the necessary compilations automatically, so you should
6983 not have to specify this switch in normal operation.
6984
6985 @item -gnatu
6986 @cindex @option{-gnatu} (@command{gcc})
6987 Print a list of units required by this compilation on @file{stdout}.
6988 The listing includes all units on which the unit being compiled depends
6989 either directly or indirectly.
6990
6991 @ifclear vms
6992 @item -pass-exit-codes
6993 @cindex @option{-pass-exit-codes} (@command{gcc})
6994 If this switch is not used, the exit code returned by @command{gcc} when
6995 compiling multiple files indicates whether all source files have
6996 been successfully used to generate object files or not.
6997
6998 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6999 exit status and allows an integrated development environment to better
7000 react to a compilation failure. Those exit status are:
7001
7002 @table @asis
7003 @item 5
7004 There was an error in at least one source file.
7005 @item 3
7006 At least one source file did not generate an object file.
7007 @item 2
7008 The compiler died unexpectedly (internal error for example).
7009 @item 0
7010 An object file has been generated for every source file.
7011 @end table
7012 @end ifclear
7013 @end table
7014
7015 @node Debugging Control
7016 @subsection Debugging Control
7017
7018 @table @option
7019 @c !sort!
7020 @cindex Debugging options
7021 @ifclear vms
7022 @item -gnatd@var{x}
7023 @cindex @option{-gnatd} (@command{gcc})
7024 Activate internal debugging switches. @var{x} is a letter or digit, or
7025 string of letters or digits, which specifies the type of debugging
7026 outputs desired. Normally these are used only for internal development
7027 or system debugging purposes. You can find full documentation for these
7028 switches in the body of the @code{Debug} unit in the compiler source
7029 file @file{debug.adb}.
7030 @end ifclear
7031
7032 @item -gnatG[=nn]
7033 @cindex @option{-gnatG} (@command{gcc})
7034 This switch causes the compiler to generate auxiliary output containing
7035 a pseudo-source listing of the generated expanded code. Like most Ada
7036 compilers, GNAT works by first transforming the high level Ada code into
7037 lower level constructs. For example, tasking operations are transformed
7038 into calls to the tasking run-time routines. A unique capability of GNAT
7039 is to list this expanded code in a form very close to normal Ada source.
7040 This is very useful in understanding the implications of various Ada
7041 usage on the efficiency of the generated code. There are many cases in
7042 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7043 generate a lot of run-time code. By using @option{-gnatG} you can identify
7044 these cases, and consider whether it may be desirable to modify the coding
7045 approach to improve efficiency.
7046
7047 The optional parameter @code{nn} if present after -gnatG specifies an
7048 alternative maximum line length that overrides the normal default of 72.
7049 This value is in the range 40-999999, values less than 40 being silently
7050 reset to 40. The equal sign is optional.
7051
7052 The format of the output is very similar to standard Ada source, and is
7053 easily understood by an Ada programmer. The following special syntactic
7054 additions correspond to low level features used in the generated code that
7055 do not have any exact analogies in pure Ada source form. The following
7056 is a partial list of these special constructions. See the spec
7057 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7058
7059 If the switch @option{-gnatL} is used in conjunction with
7060 @cindex @option{-gnatL} (@command{gcc})
7061 @option{-gnatG}, then the original source lines are interspersed
7062 in the expanded source (as comment lines with the original line number).
7063
7064 @table @code
7065 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7066 Shows the storage pool being used for an allocator.
7067
7068 @item at end @var{procedure-name};
7069 Shows the finalization (cleanup) procedure for a scope.
7070
7071 @item (if @var{expr} then @var{expr} else @var{expr})
7072 Conditional expression equivalent to the @code{x?y:z} construction in C.
7073
7074 @item @var{target}^^^(@var{source})
7075 A conversion with floating-point truncation instead of rounding.
7076
7077 @item @var{target}?(@var{source})
7078 A conversion that bypasses normal Ada semantic checking. In particular
7079 enumeration types and fixed-point types are treated simply as integers.
7080
7081 @item @var{target}?^^^(@var{source})
7082 Combines the above two cases.
7083
7084 @item @var{x} #/ @var{y}
7085 @itemx @var{x} #mod @var{y}
7086 @itemx @var{x} #* @var{y}
7087 @itemx @var{x} #rem @var{y}
7088 A division or multiplication of fixed-point values which are treated as
7089 integers without any kind of scaling.
7090
7091 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7092 Shows the storage pool associated with a @code{free} statement.
7093
7094 @item [subtype or type declaration]
7095 Used to list an equivalent declaration for an internally generated
7096 type that is referenced elsewhere in the listing.
7097
7098 @item freeze @var{type-name} @ovar{actions}
7099 Shows the point at which @var{type-name} is frozen, with possible
7100 associated actions to be performed at the freeze point.
7101
7102 @item reference @var{itype}
7103 Reference (and hence definition) to internal type @var{itype}.
7104
7105 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7106 Intrinsic function call.
7107
7108 @item @var{label-name} : label
7109 Declaration of label @var{labelname}.
7110
7111 @item #$ @var{subprogram-name}
7112 An implicit call to a run-time support routine
7113 (to meet the requirement of H.3.1(9) in a
7114 convenient manner).
7115
7116 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7117 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7118 @var{expr}, but handled more efficiently).
7119
7120 @item [constraint_error]
7121 Raise the @code{Constraint_Error} exception.
7122
7123 @item @var{expression}'reference
7124 A pointer to the result of evaluating @var{expression}.
7125
7126 @item @var{target-type}!(@var{source-expression})
7127 An unchecked conversion of @var{source-expression} to @var{target-type}.
7128
7129 @item [@var{numerator}/@var{denominator}]
7130 Used to represent internal real literals (that) have no exact
7131 representation in base 2-16 (for example, the result of compile time
7132 evaluation of the expression 1.0/27.0).
7133 @end table
7134
7135 @item -gnatD[=nn]
7136 @cindex @option{-gnatD} (@command{gcc})
7137 When used in conjunction with @option{-gnatG}, this switch causes
7138 the expanded source, as described above for
7139 @option{-gnatG} to be written to files with names
7140 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7141 instead of to the standard output file. For
7142 example, if the source file name is @file{hello.adb}, then a file
7143 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7144 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7145 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7146 you to do source level debugging using the generated code which is
7147 sometimes useful for complex code, for example to find out exactly
7148 which part of a complex construction raised an exception. This switch
7149 also suppress generation of cross-reference information (see
7150 @option{-gnatx}) since otherwise the cross-reference information
7151 would refer to the @file{^.dg^.DG^} file, which would cause
7152 confusion since this is not the original source file.
7153
7154 Note that @option{-gnatD} actually implies @option{-gnatG}
7155 automatically, so it is not necessary to give both options.
7156 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7157
7158 If the switch @option{-gnatL} is used in conjunction with
7159 @cindex @option{-gnatL} (@command{gcc})
7160 @option{-gnatDG}, then the original source lines are interspersed
7161 in the expanded source (as comment lines with the original line number).
7162
7163 The optional parameter @code{nn} if present after -gnatD specifies an
7164 alternative maximum line length that overrides the normal default of 72.
7165 This value is in the range 40-999999, values less than 40 being silently
7166 reset to 40. The equal sign is optional.
7167
7168 @item -gnatr
7169 @cindex @option{-gnatr} (@command{gcc})
7170 @cindex pragma Restrictions
7171 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7172 so that violation of restrictions causes warnings rather than illegalities.
7173 This is useful during the development process when new restrictions are added
7174 or investigated. The switch also causes pragma Profile to be treated as
7175 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7176 restriction warnings rather than restrictions.
7177
7178 @ifclear vms
7179 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7180 @cindex @option{-gnatR} (@command{gcc})
7181 This switch controls output from the compiler of a listing showing
7182 representation information for declared types and objects. For
7183 @option{-gnatR0}, no information is output (equivalent to omitting
7184 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7185 so @option{-gnatR} with no parameter has the same effect), size and alignment
7186 information is listed for declared array and record types. For
7187 @option{-gnatR2}, size and alignment information is listed for all
7188 declared types and objects. Finally @option{-gnatR3} includes symbolic
7189 expressions for values that are computed at run time for
7190 variant records. These symbolic expressions have a mostly obvious
7191 format with #n being used to represent the value of the n'th
7192 discriminant. See source files @file{repinfo.ads/adb} in the
7193 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7194 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7195 the output is to a file with the name @file{^file.rep^file_REP^} where
7196 file is the name of the corresponding source file.
7197 @end ifclear
7198 @ifset vms
7199 @item /REPRESENTATION_INFO
7200 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7201 This qualifier controls output from the compiler of a listing showing
7202 representation information for declared types and objects. For
7203 @option{/REPRESENTATION_INFO=NONE}, no information is output
7204 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7205 @option{/REPRESENTATION_INFO} without option is equivalent to
7206 @option{/REPRESENTATION_INFO=ARRAYS}.
7207 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7208 information is listed for declared array and record types. For
7209 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7210 is listed for all expression information for values that are computed
7211 at run time for variant records. These symbolic expressions have a mostly
7212 obvious format with #n being used to represent the value of the n'th
7213 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7214 @code{GNAT} sources for full details on the format of
7215 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7216 If _FILE is added at the end of an option
7217 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7218 then the output is to a file with the name @file{file_REP} where
7219 file is the name of the corresponding source file.
7220 @end ifset
7221 Note that it is possible for record components to have zero size. In
7222 this case, the component clause uses an obvious extension of permitted
7223 Ada syntax, for example @code{at 0 range 0 .. -1}.
7224
7225 Representation information requires that code be generated (since it is the
7226 code generator that lays out complex data structures). If an attempt is made
7227 to output representation information when no code is generated, for example
7228 when a subunit is compiled on its own, then no information can be generated
7229 and the compiler outputs a message to this effect.
7230
7231 @item -gnatS
7232 @cindex @option{-gnatS} (@command{gcc})
7233 The use of the switch @option{-gnatS} for an
7234 Ada compilation will cause the compiler to output a
7235 representation of package Standard in a form very
7236 close to standard Ada. It is not quite possible to
7237 do this entirely in standard Ada (since new
7238 numeric base types cannot be created in standard
7239 Ada), but the output is easily
7240 readable to any Ada programmer, and is useful to
7241 determine the characteristics of target dependent
7242 types in package Standard.
7243
7244 @item -gnatx
7245 @cindex @option{-gnatx} (@command{gcc})
7246 Normally the compiler generates full cross-referencing information in
7247 the @file{ALI} file. This information is used by a number of tools,
7248 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7249 suppresses this information. This saves some space and may slightly
7250 speed up compilation, but means that these tools cannot be used.
7251 @end table
7252
7253 @node Exception Handling Control
7254 @subsection Exception Handling Control
7255
7256 @noindent
7257 GNAT uses two methods for handling exceptions at run-time. The
7258 @code{setjmp/longjmp} method saves the context when entering
7259 a frame with an exception handler. Then when an exception is
7260 raised, the context can be restored immediately, without the
7261 need for tracing stack frames. This method provides very fast
7262 exception propagation, but introduces significant overhead for
7263 the use of exception handlers, even if no exception is raised.
7264
7265 The other approach is called ``zero cost'' exception handling.
7266 With this method, the compiler builds static tables to describe
7267 the exception ranges. No dynamic code is required when entering
7268 a frame containing an exception handler. When an exception is
7269 raised, the tables are used to control a back trace of the
7270 subprogram invocation stack to locate the required exception
7271 handler. This method has considerably poorer performance for
7272 the propagation of exceptions, but there is no overhead for
7273 exception handlers if no exception is raised. Note that in this
7274 mode and in the context of mixed Ada and C/C++ programming,
7275 to propagate an exception through a C/C++ code, the C/C++ code
7276 must be compiled with the @option{-funwind-tables} GCC's
7277 option.
7278
7279 The following switches may be used to control which of the
7280 two exception handling methods is used.
7281
7282 @table @option
7283 @c !sort!
7284
7285 @item --RTS=sjlj
7286 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7287 This switch causes the setjmp/longjmp run-time (when available) to be used
7288 for exception handling. If the default
7289 mechanism for the target is zero cost exceptions, then
7290 this switch can be used to modify this default, and must be
7291 used for all units in the partition.
7292 This option is rarely used. One case in which it may be
7293 advantageous is if you have an application where exception
7294 raising is common and the overall performance of the
7295 application is improved by favoring exception propagation.
7296
7297 @item --RTS=zcx
7298 @cindex @option{--RTS=zcx} (@command{gnatmake})
7299 @cindex Zero Cost Exceptions
7300 This switch causes the zero cost approach to be used
7301 for exception handling. If this is the default mechanism for the
7302 target (see below), then this switch is unneeded. If the default
7303 mechanism for the target is setjmp/longjmp exceptions, then
7304 this switch can be used to modify this default, and must be
7305 used for all units in the partition.
7306 This option can only be used if the zero cost approach
7307 is available for the target in use, otherwise it will generate an error.
7308 @end table
7309
7310 @noindent
7311 The same option @option{--RTS} must be used both for @command{gcc}
7312 and @command{gnatbind}. Passing this option to @command{gnatmake}
7313 (@pxref{Switches for gnatmake}) will ensure the required consistency
7314 through the compilation and binding steps.
7315
7316 @node Units to Sources Mapping Files
7317 @subsection Units to Sources Mapping Files
7318
7319 @table @option
7320
7321 @item -gnatem^^=^@var{path}
7322 @cindex @option{-gnatem} (@command{gcc})
7323 A mapping file is a way to communicate to the compiler two mappings:
7324 from unit names to file names (without any directory information) and from
7325 file names to path names (with full directory information). These mappings
7326 are used by the compiler to short-circuit the path search.
7327
7328 The use of mapping files is not required for correct operation of the
7329 compiler, but mapping files can improve efficiency, particularly when
7330 sources are read over a slow network connection. In normal operation,
7331 you need not be concerned with the format or use of mapping files,
7332 and the @option{-gnatem} switch is not a switch that you would use
7333 explicitly. it is intended only for use by automatic tools such as
7334 @command{gnatmake} running under the project file facility. The
7335 description here of the format of mapping files is provided
7336 for completeness and for possible use by other tools.
7337
7338 A mapping file is a sequence of sets of three lines. In each set,
7339 the first line is the unit name, in lower case, with ``@code{%s}''
7340 appended for
7341 specs and ``@code{%b}'' appended for bodies; the second line is the
7342 file name; and the third line is the path name.
7343
7344 Example:
7345 @smallexample
7346    main%b
7347    main.2.ada
7348    /gnat/project1/sources/main.2.ada
7349 @end smallexample
7350
7351 When the switch @option{-gnatem} is specified, the compiler will create
7352 in memory the two mappings from the specified file. If there is any problem
7353 (nonexistent file, truncated file or duplicate entries), no mapping will
7354 be created.
7355
7356 Several @option{-gnatem} switches may be specified; however, only the last
7357 one on the command line will be taken into account.
7358
7359 When using a project file, @command{gnatmake} create a temporary mapping file
7360 and communicates it to the compiler using this switch.
7361
7362 @end table
7363
7364 @node Integrated Preprocessing
7365 @subsection Integrated Preprocessing
7366
7367 @noindent
7368 GNAT sources may be preprocessed immediately before compilation.
7369 In this case, the actual
7370 text of the source is not the text of the source file, but is derived from it
7371 through a process called preprocessing. Integrated preprocessing is specified
7372 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7373 indicates, through a text file, the preprocessing data to be used.
7374 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7375
7376 @noindent
7377 Note that when integrated preprocessing is used, the output from the
7378 preprocessor is not written to any external file. Instead it is passed
7379 internally to the compiler. If you need to preserve the result of
7380 preprocessing in a file, then you should use @command{gnatprep}
7381 to perform the desired preprocessing in stand-alone mode.
7382
7383 @noindent
7384 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7385 used when Integrated Preprocessing is used. The reason is that preprocessing
7386 with another Preprocessing Data file without changing the sources will
7387 not trigger recompilation without this switch.
7388
7389 @noindent
7390 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7391 always trigger recompilation for sources that are preprocessed,
7392 because @command{gnatmake} cannot compute the checksum of the source after
7393 preprocessing.
7394
7395 @noindent
7396 The actual preprocessing function is described in details in section
7397 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7398 preprocessing is triggered and parameterized.
7399
7400 @table @code
7401
7402 @item -gnatep=@var{file}
7403 @cindex @option{-gnatep} (@command{gcc})
7404 This switch indicates to the compiler the file name (without directory
7405 information) of the preprocessor data file to use. The preprocessor data file
7406 should be found in the source directories.
7407
7408 @noindent
7409 A preprocessing data file is a text file with significant lines indicating
7410 how should be preprocessed either a specific source or all sources not
7411 mentioned in other lines. A significant line is a nonempty, non-comment line.
7412 Comments are similar to Ada comments.
7413
7414 @noindent
7415 Each significant line starts with either a literal string or the character '*'.
7416 A literal string is the file name (without directory information) of the source
7417 to preprocess. A character '*' indicates the preprocessing for all the sources
7418 that are not specified explicitly on other lines (order of the lines is not
7419 significant). It is an error to have two lines with the same file name or two
7420 lines starting with the character '*'.
7421
7422 @noindent
7423 After the file name or the character '*', another optional literal string
7424 indicating the file name of the definition file to be used for preprocessing
7425 (@pxref{Form of Definitions File}). The definition files are found by the
7426 compiler in one of the source directories. In some cases, when compiling
7427 a source in a directory other than the current directory, if the definition
7428 file is in the current directory, it may be necessary to add the current
7429 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7430 the compiler would not find the definition file.
7431
7432 @noindent
7433 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7434 be found. Those ^switches^switches^ are:
7435
7436 @table @code
7437
7438 @item -b
7439 Causes both preprocessor lines and the lines deleted by
7440 preprocessing to be replaced by blank lines, preserving the line number.
7441 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7442 it cancels the effect of @option{-c}.
7443
7444 @item -c
7445 Causes both preprocessor lines and the lines deleted
7446 by preprocessing to be retained as comments marked
7447 with the special string ``@code{--! }''.
7448
7449 @item -Dsymbol=value
7450 Define or redefine a symbol, associated with value. A symbol is an Ada
7451 identifier, or an Ada reserved word, with the exception of @code{if},
7452 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7453 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7454 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7455 same name defined in a definition file.
7456
7457 @item -s
7458 Causes a sorted list of symbol names and values to be
7459 listed on the standard output file.
7460
7461 @item -u
7462 Causes undefined symbols to be treated as having the value @code{FALSE}
7463 in the context
7464 of a preprocessor test. In the absence of this option, an undefined symbol in
7465 a @code{#if} or @code{#elsif} test will be treated as an error.
7466
7467 @end table
7468
7469 @noindent
7470 Examples of valid lines in a preprocessor data file:
7471
7472 @smallexample
7473   "toto.adb"  "prep.def" -u
7474   --  preprocess "toto.adb", using definition file "prep.def",
7475   --  undefined symbol are False.
7476
7477   * -c -DVERSION=V101
7478   --  preprocess all other sources without a definition file;
7479   --  suppressed lined are commented; symbol VERSION has the value V101.
7480
7481   "titi.adb" "prep2.def" -s
7482   --  preprocess "titi.adb", using definition file "prep2.def";
7483   --  list all symbols with their values.
7484 @end smallexample
7485
7486 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7487 @cindex @option{-gnateD} (@command{gcc})
7488 Define or redefine a preprocessing symbol, associated with value. If no value
7489 is given on the command line, then the value of the symbol is @code{True}.
7490 A symbol is an identifier, following normal Ada (case-insensitive)
7491 rules for its syntax, and value is any sequence (including an empty sequence)
7492 of characters from the set (letters, digits, period, underline).
7493 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7494 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7495
7496 @noindent
7497 A symbol declared with this ^switch^switch^ on the command line replaces a
7498 symbol with the same name either in a definition file or specified with a
7499 ^switch^switch^ -D in the preprocessor data file.
7500
7501 @noindent
7502 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7503
7504 @item -gnateG
7505 When integrated preprocessing is performed and the preprocessor modifies
7506 the source text, write the result of this preprocessing into a file
7507 <source>^.prep^_prep^.
7508
7509 @end table
7510
7511 @node Code Generation Control
7512 @subsection Code Generation Control
7513
7514 @noindent
7515
7516 The GCC technology provides a wide range of target dependent
7517 @option{-m} switches for controlling
7518 details of code generation with respect to different versions of
7519 architectures. This includes variations in instruction sets (e.g.@:
7520 different members of the power pc family), and different requirements
7521 for optimal arrangement of instructions (e.g.@: different members of
7522 the x86 family). The list of available @option{-m} switches may be
7523 found in the GCC documentation.
7524
7525 Use of these @option{-m} switches may in some cases result in improved
7526 code performance.
7527
7528 The GNAT Pro technology is tested and qualified without any
7529 @option{-m} switches,
7530 so generally the most reliable approach is to avoid the use of these
7531 switches. However, we generally expect most of these switches to work
7532 successfully with GNAT Pro, and many customers have reported successful
7533 use of these options.
7534
7535 Our general advice is to avoid the use of @option{-m} switches unless
7536 special needs lead to requirements in this area. In particular,
7537 there is no point in using @option{-m} switches to improve performance
7538 unless you actually see a performance improvement.
7539
7540 @ifset vms
7541 @node Return Codes
7542 @subsection Return Codes
7543 @cindex Return Codes
7544 @cindex @option{/RETURN_CODES=VMS}
7545
7546 @noindent
7547 On VMS, GNAT compiled programs return POSIX-style codes by default,
7548 e.g.@: @option{/RETURN_CODES=POSIX}.
7549
7550 To enable VMS style return codes, use GNAT BIND and LINK with the option
7551 @option{/RETURN_CODES=VMS}. For example:
7552
7553 @smallexample
7554 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7555 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7556 @end smallexample
7557
7558 @noindent
7559 Programs built with /RETURN_CODES=VMS are suitable to be called in
7560 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7561 are suitable for spawning with appropriate GNAT RTL routines.
7562
7563 @end ifset
7564
7565 @node Search Paths and the Run-Time Library (RTL)
7566 @section Search Paths and the Run-Time Library (RTL)
7567
7568 @noindent
7569 With the GNAT source-based library system, the compiler must be able to
7570 find source files for units that are needed by the unit being compiled.
7571 Search paths are used to guide this process.
7572
7573 The compiler compiles one source file whose name must be given
7574 explicitly on the command line. In other words, no searching is done
7575 for this file. To find all other source files that are needed (the most
7576 common being the specs of units), the compiler examines the following
7577 directories, in the following order:
7578
7579 @enumerate
7580 @item
7581 The directory containing the source file of the main unit being compiled
7582 (the file name on the command line).
7583
7584 @item
7585 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7586 @command{gcc} command line, in the order given.
7587
7588 @item
7589 @findex ADA_PRJ_INCLUDE_FILE
7590 Each of the directories listed in the text file whose name is given
7591 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7592
7593 @noindent
7594 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7595 driver when project files are used. It should not normally be set
7596 by other means.
7597
7598 @item
7599 @findex ADA_INCLUDE_PATH
7600 Each of the directories listed in the value of the
7601 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7602 @ifclear vms
7603 Construct this value
7604 exactly as the @env{PATH} environment variable: a list of directory
7605 names separated by colons (semicolons when working with the NT version).
7606 @end ifclear
7607 @ifset vms
7608 Normally, define this value as a logical name containing a comma separated
7609 list of directory names.
7610
7611 This variable can also be defined by means of an environment string
7612 (an argument to the HP C exec* set of functions).
7613
7614 Logical Name:
7615 @smallexample
7616 DEFINE ANOTHER_PATH FOO:[BAG]
7617 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7618 @end smallexample
7619
7620 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7621 first, followed by the standard Ada
7622 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7623 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7624 (Text_IO, Sequential_IO, etc)
7625 instead of the standard Ada packages. Thus, in order to get the standard Ada
7626 packages by default, ADA_INCLUDE_PATH must be redefined.
7627 @end ifset
7628
7629 @item
7630 The content of the @file{ada_source_path} file which is part of the GNAT
7631 installation tree and is used to store standard libraries such as the
7632 GNAT Run Time Library (RTL) source files.
7633 @ifclear vms
7634 @ref{Installing a library}
7635 @end ifclear
7636 @end enumerate
7637
7638 @noindent
7639 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7640 inhibits the use of the directory
7641 containing the source file named in the command line. You can still
7642 have this directory on your search path, but in this case it must be
7643 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7644
7645 Specifying the switch @option{-nostdinc}
7646 inhibits the search of the default location for the GNAT Run Time
7647 Library (RTL) source files.
7648
7649 The compiler outputs its object files and ALI files in the current
7650 working directory.
7651 @ifclear vms
7652 Caution: The object file can be redirected with the @option{-o} switch;
7653 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7654 so the @file{ALI} file will not go to the right place. Therefore, you should
7655 avoid using the @option{-o} switch.
7656 @end ifclear
7657
7658 @findex System.IO
7659 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7660 children make up the GNAT RTL, together with the simple @code{System.IO}
7661 package used in the @code{"Hello World"} example. The sources for these units
7662 are needed by the compiler and are kept together in one directory. Not
7663 all of the bodies are needed, but all of the sources are kept together
7664 anyway. In a normal installation, you need not specify these directory
7665 names when compiling or binding. Either the environment variables or
7666 the built-in defaults cause these files to be found.
7667
7668 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7669 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7670 consisting of child units of @code{GNAT}. This is a collection of generally
7671 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7672 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7673
7674 Besides simplifying access to the RTL, a major use of search paths is
7675 in compiling sources from multiple directories. This can make
7676 development environments much more flexible.
7677
7678 @node Order of Compilation Issues
7679 @section Order of Compilation Issues
7680
7681 @noindent
7682 If, in our earlier example, there was a spec for the @code{hello}
7683 procedure, it would be contained in the file @file{hello.ads}; yet this
7684 file would not have to be explicitly compiled. This is the result of the
7685 model we chose to implement library management. Some of the consequences
7686 of this model are as follows:
7687
7688 @itemize @bullet
7689 @item
7690 There is no point in compiling specs (except for package
7691 specs with no bodies) because these are compiled as needed by clients. If
7692 you attempt a useless compilation, you will receive an error message.
7693 It is also useless to compile subunits because they are compiled as needed
7694 by the parent.
7695
7696 @item
7697 There are no order of compilation requirements: performing a
7698 compilation never obsoletes anything. The only way you can obsolete
7699 something and require recompilations is to modify one of the
7700 source files on which it depends.
7701
7702 @item
7703 There is no library as such, apart from the ALI files
7704 (@pxref{The Ada Library Information Files}, for information on the format
7705 of these files). For now we find it convenient to create separate ALI files,
7706 but eventually the information therein may be incorporated into the object
7707 file directly.
7708
7709 @item
7710 When you compile a unit, the source files for the specs of all units
7711 that it @code{with}'s, all its subunits, and the bodies of any generics it
7712 instantiates must be available (reachable by the search-paths mechanism
7713 described above), or you will receive a fatal error message.
7714 @end itemize
7715
7716 @node Examples
7717 @section Examples
7718
7719 @noindent
7720 The following are some typical Ada compilation command line examples:
7721
7722 @table @code
7723 @item $ gcc -c xyz.adb
7724 Compile body in file @file{xyz.adb} with all default options.
7725
7726 @ifclear vms
7727 @item $ gcc -c -O2 -gnata xyz-def.adb
7728 @end ifclear
7729 @ifset vms
7730 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7731 @end ifset
7732
7733 Compile the child unit package in file @file{xyz-def.adb} with extensive
7734 optimizations, and pragma @code{Assert}/@code{Debug} statements
7735 enabled.
7736
7737 @item $ gcc -c -gnatc abc-def.adb
7738 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7739 mode.
7740 @end table
7741
7742 @node Binding Using gnatbind
7743 @chapter Binding Using @code{gnatbind}
7744 @findex gnatbind
7745
7746 @menu
7747 * Running gnatbind::
7748 * Switches for gnatbind::
7749 * Command-Line Access::
7750 * Search Paths for gnatbind::
7751 * Examples of gnatbind Usage::
7752 @end menu
7753
7754 @noindent
7755 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7756 to bind compiled GNAT objects.
7757
7758 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7759 driver (see @ref{The GNAT Driver and Project Files}).
7760
7761 The @code{gnatbind} program performs four separate functions:
7762
7763 @enumerate
7764 @item
7765 Checks that a program is consistent, in accordance with the rules in
7766 Chapter 10 of the Ada Reference Manual. In particular, error
7767 messages are generated if a program uses inconsistent versions of a
7768 given unit.
7769
7770 @item
7771 Checks that an acceptable order of elaboration exists for the program
7772 and issues an error message if it cannot find an order of elaboration
7773 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7774
7775 @item
7776 Generates a main program incorporating the given elaboration order.
7777 This program is a small Ada package (body and spec) that
7778 must be subsequently compiled
7779 using the GNAT compiler. The necessary compilation step is usually
7780 performed automatically by @command{gnatlink}. The two most important
7781 functions of this program
7782 are to call the elaboration routines of units in an appropriate order
7783 and to call the main program.
7784
7785 @item
7786 Determines the set of object files required by the given main program.
7787 This information is output in the forms of comments in the generated program,
7788 to be read by the @command{gnatlink} utility used to link the Ada application.
7789 @end enumerate
7790
7791 @node Running gnatbind
7792 @section Running @code{gnatbind}
7793
7794 @noindent
7795 The form of the @code{gnatbind} command is
7796
7797 @smallexample
7798 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7799 @end smallexample
7800
7801 @noindent
7802 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7803 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7804 package in two files whose names are
7805 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7806 For example, if given the
7807 parameter @file{hello.ali}, for a main program contained in file
7808 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7809 and @file{b~hello.adb}.
7810
7811 When doing consistency checking, the binder takes into consideration
7812 any source files it can locate. For example, if the binder determines
7813 that the given main program requires the package @code{Pack}, whose
7814 @file{.ALI}
7815 file is @file{pack.ali} and whose corresponding source spec file is
7816 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7817 (using the same search path conventions as previously described for the
7818 @command{gcc} command). If it can locate this source file, it checks that
7819 the time stamps
7820 or source checksums of the source and its references to in @file{ALI} files
7821 match. In other words, any @file{ALI} files that mentions this spec must have
7822 resulted from compiling this version of the source file (or in the case
7823 where the source checksums match, a version close enough that the
7824 difference does not matter).
7825
7826 @cindex Source files, use by binder
7827 The effect of this consistency checking, which includes source files, is
7828 that the binder ensures that the program is consistent with the latest
7829 version of the source files that can be located at bind time. Editing a
7830 source file without compiling files that depend on the source file cause
7831 error messages to be generated by the binder.
7832
7833 For example, suppose you have a main program @file{hello.adb} and a
7834 package @code{P}, from file @file{p.ads} and you perform the following
7835 steps:
7836
7837 @enumerate
7838 @item
7839 Enter @code{gcc -c hello.adb} to compile the main program.
7840
7841 @item
7842 Enter @code{gcc -c p.ads} to compile package @code{P}.
7843
7844 @item
7845 Edit file @file{p.ads}.
7846
7847 @item
7848 Enter @code{gnatbind hello}.
7849 @end enumerate
7850
7851 @noindent
7852 At this point, the file @file{p.ali} contains an out-of-date time stamp
7853 because the file @file{p.ads} has been edited. The attempt at binding
7854 fails, and the binder generates the following error messages:
7855
7856 @smallexample
7857 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7858 error: "p.ads" has been modified and must be recompiled
7859 @end smallexample
7860
7861 @noindent
7862 Now both files must be recompiled as indicated, and then the bind can
7863 succeed, generating a main program. You need not normally be concerned
7864 with the contents of this file, but for reference purposes a sample
7865 binder output file is given in @ref{Example of Binder Output File}.
7866
7867 In most normal usage, the default mode of @command{gnatbind} which is to
7868 generate the main package in Ada, as described in the previous section.
7869 In particular, this means that any Ada programmer can read and understand
7870 the generated main program. It can also be debugged just like any other
7871 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7872 @command{gnatbind} and @command{gnatlink}.
7873
7874 However for some purposes it may be convenient to generate the main
7875 program in C rather than Ada. This may for example be helpful when you
7876 are generating a mixed language program with the main program in C. The
7877 GNAT compiler itself is an example.
7878 The use of the @option{^-C^/BIND_FILE=C^} switch
7879 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7880 be generated in C (and compiled using the gnu C compiler).
7881
7882 @node Switches for gnatbind
7883 @section Switches for @command{gnatbind}
7884
7885 @noindent
7886 The following switches are available with @code{gnatbind}; details will
7887 be presented in subsequent sections.
7888
7889 @menu
7890 * Consistency-Checking Modes::
7891 * Binder Error Message Control::
7892 * Elaboration Control::
7893 * Output Control::
7894 * Binding with Non-Ada Main Programs::
7895 * Binding Programs with No Main Subprogram::
7896 @end menu
7897
7898 @table @option
7899 @c !sort!
7900
7901 @item --version
7902 @cindex @option{--version} @command{gnatbind}
7903 Display Copyright and version, then exit disregarding all other options.
7904
7905 @item --help
7906 @cindex @option{--help} @command{gnatbind}
7907 If @option{--version} was not used, display usage, then exit disregarding
7908 all other options.
7909
7910 @item -a
7911 @cindex @option{-a} @command{gnatbind}
7912 Indicates that, if supported by the platform, the adainit procedure should
7913 be treated as an initialisation routine by the linker (a constructor). This
7914 is intended to be used by the Project Manager to automatically initialize
7915 shared Stand-Alone Libraries.
7916
7917 @item ^-aO^/OBJECT_SEARCH^
7918 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7919 Specify directory to be searched for ALI files.
7920
7921 @item ^-aI^/SOURCE_SEARCH^
7922 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7923 Specify directory to be searched for source file.
7924
7925 @item ^-A^/BIND_FILE=ADA^
7926 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7927 Generate binder program in Ada (default)
7928
7929 @item ^-b^/REPORT_ERRORS=BRIEF^
7930 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7931 Generate brief messages to @file{stderr} even if verbose mode set.
7932
7933 @item ^-c^/NOOUTPUT^
7934 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7935 Check only, no generation of binder output file.
7936
7937 @item ^-C^/BIND_FILE=C^
7938 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7939 Generate binder program in C
7940
7941 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7942 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7943 This switch can be used to change the default task stack size value
7944 to a specified size @var{nn}, which is expressed in bytes by default, or
7945 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7946 with @var{m}.
7947 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7948 in effect, to completing all task specs with
7949 @smallexample @c ada
7950    pragma Storage_Size (nn);
7951 @end smallexample
7952 When they do not already have such a pragma.
7953
7954 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7955 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7956 This switch can be used to change the default secondary stack size value
7957 to a specified size @var{nn}, which is expressed in bytes by default, or
7958 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7959 with @var{m}.
7960
7961 The secondary stack is used to deal with functions that return a variable
7962 sized result, for example a function returning an unconstrained
7963 String. There are two ways in which this secondary stack is allocated.
7964
7965 For most targets, the secondary stack is growing on demand and is allocated
7966 as a chain of blocks in the heap. The -D option is not very
7967 relevant. It only give some control over the size of the allocated
7968 blocks (whose size is the minimum of the default secondary stack size value,
7969 and the actual size needed for the current allocation request).
7970
7971 For certain targets, notably VxWorks 653,
7972 the secondary stack is allocated by carving off a fixed ratio chunk of the
7973 primary task stack. The -D option is used to define the
7974 size of the environment task's secondary stack.
7975
7976 @item ^-e^/ELABORATION_DEPENDENCIES^
7977 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7978 Output complete list of elaboration-order dependencies.
7979
7980 @item ^-E^/STORE_TRACEBACKS^
7981 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7982 Store tracebacks in exception occurrences when the target supports it.
7983 This is the default with the zero cost exception mechanism.
7984 @ignore
7985 @c The following may get moved to an appendix
7986 This option is currently supported on the following targets:
7987 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7988 @end ignore
7989 See also the packages @code{GNAT.Traceback} and
7990 @code{GNAT.Traceback.Symbolic} for more information.
7991 @ifclear vms
7992 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7993 @command{gcc} option.
7994 @end ifclear
7995
7996 @item ^-F^/FORCE_ELABS_FLAGS^
7997 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7998 Force the checks of elaboration flags. @command{gnatbind} does not normally
7999 generate checks of elaboration flags for the main executable, except when
8000 a Stand-Alone Library is used. However, there are cases when this cannot be
8001 detected by gnatbind. An example is importing an interface of a Stand-Alone
8002 Library through a pragma Import and only specifying through a linker switch
8003 this Stand-Alone Library. This switch is used to guarantee that elaboration
8004 flag checks are generated.
8005
8006 @item ^-h^/HELP^
8007 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8008 Output usage (help) information
8009
8010 @item ^-I^/SEARCH^
8011 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8012 Specify directory to be searched for source and ALI files.
8013
8014 @item ^-I-^/NOCURRENT_DIRECTORY^
8015 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8016 Do not look for sources in the current directory where @code{gnatbind} was
8017 invoked, and do not look for ALI files in the directory containing the
8018 ALI file named in the @code{gnatbind} command line.
8019
8020 @item ^-l^/ORDER_OF_ELABORATION^
8021 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8022 Output chosen elaboration order.
8023
8024 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8025 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8026 Bind the units for library building. In this case the adainit and
8027 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8028 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8029 ^@var{xxx}final^@var{XXX}FINAL^.
8030 Implies ^-n^/NOCOMPILE^.
8031 @ifclear vms
8032 (@xref{GNAT and Libraries}, for more details.)
8033 @end ifclear
8034 @ifset vms
8035 On OpenVMS, these init and final procedures are exported in uppercase
8036 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8037 the init procedure will be "TOTOINIT" and the exported name of the final
8038 procedure will be "TOTOFINAL".
8039 @end ifset
8040
8041 @item ^-Mxyz^/RENAME_MAIN=xyz^
8042 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8043 Rename generated main program from main to xyz. This option is
8044 supported on cross environments only.
8045
8046 @item ^-m^/ERROR_LIMIT=^@var{n}
8047 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8048 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8049 in the range 1..999999. The default value if no switch is
8050 given is 9999. If the number of warnings reaches this limit, then a
8051 message is output and further warnings are suppressed, the bind
8052 continues in this case. If the number of errors reaches this
8053 limit, then a message is output and the bind is abandoned.
8054 A value of zero means that no limit is enforced. The equal
8055 sign is optional.
8056
8057 @ifset unw
8058 Furthermore, under Windows, the sources pointed to by the libraries path
8059 set in the registry are not searched for.
8060 @end ifset
8061
8062 @item ^-n^/NOMAIN^
8063 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8064 No main program.
8065
8066 @item -nostdinc
8067 @cindex @option{-nostdinc} (@command{gnatbind})
8068 Do not look for sources in the system default directory.
8069
8070 @item -nostdlib
8071 @cindex @option{-nostdlib} (@command{gnatbind})
8072 Do not look for library files in the system default directory.
8073
8074 @item --RTS=@var{rts-path}
8075 @cindex @option{--RTS} (@code{gnatbind})
8076 Specifies the default location of the runtime library. Same meaning as the
8077 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8078
8079 @item ^-o ^/OUTPUT=^@var{file}
8080 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8081 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8082 Note that if this option is used, then linking must be done manually,
8083 gnatlink cannot be used.
8084
8085 @item ^-O^/OBJECT_LIST^
8086 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8087 Output object list.
8088
8089 @item ^-p^/PESSIMISTIC_ELABORATION^
8090 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8091 Pessimistic (worst-case) elaboration order
8092
8093 @item ^-R^-R^
8094 @cindex @option{^-R^-R^} (@command{gnatbind})
8095 Output closure source list.
8096
8097 @item ^-s^/READ_SOURCES=ALL^
8098 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8099 Require all source files to be present.
8100
8101 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8102 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8103 Specifies the value to be used when detecting uninitialized scalar
8104 objects with pragma Initialize_Scalars.
8105 The @var{xxx} ^string specified with the switch^option^ may be either
8106 @itemize @bullet
8107 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8108 @item ``@option{^lo^LOW^}'' for the lowest possible value
8109 @item ``@option{^hi^HIGH^}'' for the highest possible value
8110 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8111 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8112 @end itemize
8113
8114 In addition, you can specify @option{-Sev} to indicate that the value is
8115 to be set at run time. In this case, the program will look for an environment
8116 @cindex GNAT_INIT_SCALARS
8117 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8118 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8119 If no environment variable is found, or if it does not have a valid value,
8120 then the default is @option{in} (invalid values).
8121
8122 @ifclear vms
8123 @item -static
8124 @cindex @option{-static} (@code{gnatbind})
8125 Link against a static GNAT run time.
8126
8127 @item -shared
8128 @cindex @option{-shared} (@code{gnatbind})
8129 Link against a shared GNAT run time when available.
8130 @end ifclear
8131
8132 @item ^-t^/NOTIME_STAMP_CHECK^
8133 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8134 Tolerate time stamp and other consistency errors
8135
8136 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8137 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8138 Set the time slice value to @var{n} milliseconds. If the system supports
8139 the specification of a specific time slice value, then the indicated value
8140 is used. If the system does not support specific time slice values, but
8141 does support some general notion of round-robin scheduling, then any
8142 nonzero value will activate round-robin scheduling.
8143
8144 A value of zero is treated specially. It turns off time
8145 slicing, and in addition, indicates to the tasking run time that the
8146 semantics should match as closely as possible the Annex D
8147 requirements of the Ada RM, and in particular sets the default
8148 scheduling policy to @code{FIFO_Within_Priorities}.
8149
8150 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8151 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8152 Enable dynamic stack usage, with @var{n} results stored and displayed
8153 at program termination. A result is generated when a task
8154 terminates. Results that can't be stored are displayed on the fly, at
8155 task termination. This option is currently not supported on Itanium
8156 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8157
8158 @item ^-v^/REPORT_ERRORS=VERBOSE^
8159 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8160 Verbose mode. Write error messages, header, summary output to
8161 @file{stdout}.
8162
8163 @ifclear vms
8164 @item -w@var{x}
8165 @cindex @option{-w} (@code{gnatbind})
8166 Warning mode (@var{x}=s/e for suppress/treat as error)
8167 @end ifclear
8168
8169 @ifset vms
8170 @item /WARNINGS=NORMAL
8171 @cindex @option{/WARNINGS} (@code{gnatbind})
8172 Normal warnings mode. Warnings are issued but ignored
8173
8174 @item /WARNINGS=SUPPRESS
8175 @cindex @option{/WARNINGS} (@code{gnatbind})
8176 All warning messages are suppressed
8177
8178 @item /WARNINGS=ERROR
8179 @cindex @option{/WARNINGS} (@code{gnatbind})
8180 Warning messages are treated as fatal errors
8181 @end ifset
8182
8183 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8184 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8185 Override default wide character encoding for standard Text_IO files.
8186
8187 @item ^-x^/READ_SOURCES=NONE^
8188 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8189 Exclude source files (check object consistency only).
8190
8191 @ifset vms
8192 @item /READ_SOURCES=AVAILABLE
8193 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8194 Default mode, in which sources are checked for consistency only if
8195 they are available.
8196 @end ifset
8197
8198 @item ^-y^/ENABLE_LEAP_SECONDS^
8199 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8200 Enable leap seconds support in @code{Ada.Calendar} and its children.
8201
8202 @item ^-z^/ZERO_MAIN^
8203 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8204 No main subprogram.
8205 @end table
8206
8207 @ifclear vms
8208 @noindent
8209 You may obtain this listing of switches by running @code{gnatbind} with
8210 no arguments.
8211 @end ifclear
8212
8213 @node Consistency-Checking Modes
8214 @subsection Consistency-Checking Modes
8215
8216 @noindent
8217 As described earlier, by default @code{gnatbind} checks
8218 that object files are consistent with one another and are consistent
8219 with any source files it can locate. The following switches control binder
8220 access to sources.
8221
8222 @table @option
8223 @c !sort!
8224 @item ^-s^/READ_SOURCES=ALL^
8225 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8226 Require source files to be present. In this mode, the binder must be
8227 able to locate all source files that are referenced, in order to check
8228 their consistency. In normal mode, if a source file cannot be located it
8229 is simply ignored. If you specify this switch, a missing source
8230 file is an error.
8231
8232 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8233 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8234 Override default wide character encoding for standard Text_IO files.
8235 Normally the default wide character encoding method used for standard
8236 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8237 the main source input (see description of switch
8238 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8239 use of this switch for the binder (which has the same set of
8240 possible arguments) overrides this default as specified.
8241
8242 @item ^-x^/READ_SOURCES=NONE^
8243 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8244 Exclude source files. In this mode, the binder only checks that ALI
8245 files are consistent with one another. Source files are not accessed.
8246 The binder runs faster in this mode, and there is still a guarantee that
8247 the resulting program is self-consistent.
8248 If a source file has been edited since it was last compiled, and you
8249 specify this switch, the binder will not detect that the object
8250 file is out of date with respect to the source file. Note that this is the
8251 mode that is automatically used by @command{gnatmake} because in this
8252 case the checking against sources has already been performed by
8253 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8254
8255 @ifset vms
8256 @item /READ_SOURCES=AVAILABLE
8257 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8258 This is the default mode in which source files are checked if they are
8259 available, and ignored if they are not available.
8260 @end ifset
8261 @end table
8262
8263 @node Binder Error Message Control
8264 @subsection Binder Error Message Control
8265
8266 @noindent
8267 The following switches provide control over the generation of error
8268 messages from the binder:
8269
8270 @table @option
8271 @c !sort!
8272 @item ^-v^/REPORT_ERRORS=VERBOSE^
8273 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8274 Verbose mode. In the normal mode, brief error messages are generated to
8275 @file{stderr}. If this switch is present, a header is written
8276 to @file{stdout} and any error messages are directed to @file{stdout}.
8277 All that is written to @file{stderr} is a brief summary message.
8278
8279 @item ^-b^/REPORT_ERRORS=BRIEF^
8280 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8281 Generate brief error messages to @file{stderr} even if verbose mode is
8282 specified. This is relevant only when used with the
8283 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8284
8285 @ifclear vms
8286 @item -m@var{n}
8287 @cindex @option{-m} (@code{gnatbind})
8288 Limits the number of error messages to @var{n}, a decimal integer in the
8289 range 1-999. The binder terminates immediately if this limit is reached.
8290
8291 @item -M@var{xxx}
8292 @cindex @option{-M} (@code{gnatbind})
8293 Renames the generated main program from @code{main} to @code{xxx}.
8294 This is useful in the case of some cross-building environments, where
8295 the actual main program is separate from the one generated
8296 by @code{gnatbind}.
8297 @end ifclear
8298
8299 @item ^-ws^/WARNINGS=SUPPRESS^
8300 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8301 @cindex Warnings
8302 Suppress all warning messages.
8303
8304 @item ^-we^/WARNINGS=ERROR^
8305 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8306 Treat any warning messages as fatal errors.
8307
8308 @ifset vms
8309 @item /WARNINGS=NORMAL
8310 Standard mode with warnings generated, but warnings do not get treated
8311 as errors.
8312 @end ifset
8313
8314 @item ^-t^/NOTIME_STAMP_CHECK^
8315 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8316 @cindex Time stamp checks, in binder
8317 @cindex Binder consistency checks
8318 @cindex Consistency checks, in binder
8319 The binder performs a number of consistency checks including:
8320
8321 @itemize @bullet
8322 @item
8323 Check that time stamps of a given source unit are consistent
8324 @item
8325 Check that checksums of a given source unit are consistent
8326 @item
8327 Check that consistent versions of @code{GNAT} were used for compilation
8328 @item
8329 Check consistency of configuration pragmas as required
8330 @end itemize
8331
8332 @noindent
8333 Normally failure of such checks, in accordance with the consistency
8334 requirements of the Ada Reference Manual, causes error messages to be
8335 generated which abort the binder and prevent the output of a binder
8336 file and subsequent link to obtain an executable.
8337
8338 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8339 into warnings, so that
8340 binding and linking can continue to completion even in the presence of such
8341 errors. The result may be a failed link (due to missing symbols), or a
8342 non-functional executable which has undefined semantics.
8343 @emph{This means that
8344 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8345 with extreme care.}
8346 @end table
8347
8348 @node Elaboration Control
8349 @subsection Elaboration Control
8350
8351 @noindent
8352 The following switches provide additional control over the elaboration
8353 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8354
8355 @table @option
8356 @item ^-p^/PESSIMISTIC_ELABORATION^
8357 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8358 Normally the binder attempts to choose an elaboration order that is
8359 likely to minimize the likelihood of an elaboration order error resulting
8360 in raising a @code{Program_Error} exception. This switch reverses the
8361 action of the binder, and requests that it deliberately choose an order
8362 that is likely to maximize the likelihood of an elaboration error.
8363 This is useful in ensuring portability and avoiding dependence on
8364 accidental fortuitous elaboration ordering.
8365
8366 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8367 switch if dynamic
8368 elaboration checking is used (@option{-gnatE} switch used for compilation).
8369 This is because in the default static elaboration mode, all necessary
8370 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8371 These implicit pragmas are still respected by the binder in
8372 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8373 safe elaboration order is assured.
8374 @end table
8375
8376 @node Output Control
8377 @subsection Output Control
8378
8379 @noindent
8380 The following switches allow additional control over the output
8381 generated by the binder.
8382
8383 @table @option
8384 @c !sort!
8385
8386 @item ^-A^/BIND_FILE=ADA^
8387 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8388 Generate binder program in Ada (default). The binder program is named
8389 @file{b~@var{mainprog}.adb} by default. This can be changed with
8390 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8391
8392 @item ^-c^/NOOUTPUT^
8393 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8394 Check only. Do not generate the binder output file. In this mode the
8395 binder performs all error checks but does not generate an output file.
8396
8397 @item ^-C^/BIND_FILE=C^
8398 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8399 Generate binder program in C. The binder program is named
8400 @file{b_@var{mainprog}.c}.
8401 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8402 option.
8403
8404 @item ^-e^/ELABORATION_DEPENDENCIES^
8405 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8406 Output complete list of elaboration-order dependencies, showing the
8407 reason for each dependency. This output can be rather extensive but may
8408 be useful in diagnosing problems with elaboration order. The output is
8409 written to @file{stdout}.
8410
8411 @item ^-h^/HELP^
8412 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8413 Output usage information. The output is written to @file{stdout}.
8414
8415 @item ^-K^/LINKER_OPTION_LIST^
8416 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8417 Output linker options to @file{stdout}. Includes library search paths,
8418 contents of pragmas Ident and Linker_Options, and libraries added
8419 by @code{gnatbind}.
8420
8421 @item ^-l^/ORDER_OF_ELABORATION^
8422 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8423 Output chosen elaboration order. The output is written to @file{stdout}.
8424
8425 @item ^-O^/OBJECT_LIST^
8426 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8427 Output full names of all the object files that must be linked to provide
8428 the Ada component of the program. The output is written to @file{stdout}.
8429 This list includes the files explicitly supplied and referenced by the user
8430 as well as implicitly referenced run-time unit files. The latter are
8431 omitted if the corresponding units reside in shared libraries. The
8432 directory names for the run-time units depend on the system configuration.
8433
8434 @item ^-o ^/OUTPUT=^@var{file}
8435 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8436 Set name of output file to @var{file} instead of the normal
8437 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8438 binder generated body filename. In C mode you would normally give
8439 @var{file} an extension of @file{.c} because it will be a C source program.
8440 Note that if this option is used, then linking must be done manually.
8441 It is not possible to use gnatlink in this case, since it cannot locate
8442 the binder file.
8443
8444 @item ^-r^/RESTRICTION_LIST^
8445 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8446 Generate list of @code{pragma Restrictions} that could be applied to
8447 the current unit. This is useful for code audit purposes, and also may
8448 be used to improve code generation in some cases.
8449
8450 @end table
8451
8452 @node Binding with Non-Ada Main Programs
8453 @subsection Binding with Non-Ada Main Programs
8454
8455 @noindent
8456 In our description so far we have assumed that the main
8457 program is in Ada, and that the task of the binder is to generate a
8458 corresponding function @code{main} that invokes this Ada main
8459 program. GNAT also supports the building of executable programs where
8460 the main program is not in Ada, but some of the called routines are
8461 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8462 The following switch is used in this situation:
8463
8464 @table @option
8465 @item ^-n^/NOMAIN^
8466 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8467 No main program. The main program is not in Ada.
8468 @end table
8469
8470 @noindent
8471 In this case, most of the functions of the binder are still required,
8472 but instead of generating a main program, the binder generates a file
8473 containing the following callable routines:
8474
8475 @table @code
8476 @item adainit
8477 @findex adainit
8478 You must call this routine to initialize the Ada part of the program by
8479 calling the necessary elaboration routines. A call to @code{adainit} is
8480 required before the first call to an Ada subprogram.
8481
8482 Note that it is assumed that the basic execution environment must be setup
8483 to be appropriate for Ada execution at the point where the first Ada
8484 subprogram is called. In particular, if the Ada code will do any
8485 floating-point operations, then the FPU must be setup in an appropriate
8486 manner. For the case of the x86, for example, full precision mode is
8487 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8488 that the FPU is in the right state.
8489
8490 @item adafinal
8491 @findex adafinal
8492 You must call this routine to perform any library-level finalization
8493 required by the Ada subprograms. A call to @code{adafinal} is required
8494 after the last call to an Ada subprogram, and before the program
8495 terminates.
8496 @end table
8497
8498 @noindent
8499 If the @option{^-n^/NOMAIN^} switch
8500 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8501 @cindex Binder, multiple input files
8502 is given, more than one ALI file may appear on
8503 the command line for @code{gnatbind}. The normal @dfn{closure}
8504 calculation is performed for each of the specified units. Calculating
8505 the closure means finding out the set of units involved by tracing
8506 @code{with} references. The reason it is necessary to be able to
8507 specify more than one ALI file is that a given program may invoke two or
8508 more quite separate groups of Ada units.
8509
8510 The binder takes the name of its output file from the last specified ALI
8511 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8512 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8513 The output is an Ada unit in source form that can
8514 be compiled with GNAT unless the -C switch is used in which case the
8515 output is a C source file, which must be compiled using the C compiler.
8516 This compilation occurs automatically as part of the @command{gnatlink}
8517 processing.
8518
8519 Currently the GNAT run time requires a FPU using 80 bits mode
8520 precision. Under targets where this is not the default it is required to
8521 call GNAT.Float_Control.Reset before using floating point numbers (this
8522 include float computation, float input and output) in the Ada code. A
8523 side effect is that this could be the wrong mode for the foreign code
8524 where floating point computation could be broken after this call.
8525
8526 @node Binding Programs with No Main Subprogram
8527 @subsection Binding Programs with No Main Subprogram
8528
8529 @noindent
8530 It is possible to have an Ada program which does not have a main
8531 subprogram. This program will call the elaboration routines of all the
8532 packages, then the finalization routines.
8533
8534 The following switch is used to bind programs organized in this manner:
8535
8536 @table @option
8537 @item ^-z^/ZERO_MAIN^
8538 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8539 Normally the binder checks that the unit name given on the command line
8540 corresponds to a suitable main subprogram. When this switch is used,
8541 a list of ALI files can be given, and the execution of the program
8542 consists of elaboration of these units in an appropriate order. Note
8543 that the default wide character encoding method for standard Text_IO
8544 files is always set to Brackets if this switch is set (you can use
8545 the binder switch
8546 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8547 @end table
8548
8549 @node Command-Line Access
8550 @section Command-Line Access
8551
8552 @noindent
8553 The package @code{Ada.Command_Line} provides access to the command-line
8554 arguments and program name. In order for this interface to operate
8555 correctly, the two variables
8556
8557 @smallexample
8558 @group
8559 int gnat_argc;
8560 char **gnat_argv;
8561 @end group
8562 @end smallexample
8563
8564 @noindent
8565 @findex gnat_argv
8566 @findex gnat_argc
8567 are declared in one of the GNAT library routines. These variables must
8568 be set from the actual @code{argc} and @code{argv} values passed to the
8569 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8570 generates the C main program to automatically set these variables.
8571 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8572 set these variables. If they are not set, the procedures in
8573 @code{Ada.Command_Line} will not be available, and any attempt to use
8574 them will raise @code{Constraint_Error}. If command line access is
8575 required, your main program must set @code{gnat_argc} and
8576 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8577 it.
8578
8579 @node Search Paths for gnatbind
8580 @section Search Paths for @code{gnatbind}
8581
8582 @noindent
8583 The binder takes the name of an ALI file as its argument and needs to
8584 locate source files as well as other ALI files to verify object consistency.
8585
8586 For source files, it follows exactly the same search rules as @command{gcc}
8587 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8588 directories searched are:
8589
8590 @enumerate
8591 @item
8592 The directory containing the ALI file named in the command line, unless
8593 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8594
8595 @item
8596 All directories specified by @option{^-I^/SEARCH^}
8597 switches on the @code{gnatbind}
8598 command line, in the order given.
8599
8600 @item
8601 @findex ADA_PRJ_OBJECTS_FILE
8602 Each of the directories listed in the text file whose name is given
8603 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8604
8605 @noindent
8606 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8607 driver when project files are used. It should not normally be set
8608 by other means.
8609
8610 @item
8611 @findex ADA_OBJECTS_PATH
8612 Each of the directories listed in the value of the
8613 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8614 @ifset unw
8615 Construct this value
8616 exactly as the @env{PATH} environment variable: a list of directory
8617 names separated by colons (semicolons when working with the NT version
8618 of GNAT).
8619 @end ifset
8620 @ifset vms
8621 Normally, define this value as a logical name containing a comma separated
8622 list of directory names.
8623
8624 This variable can also be defined by means of an environment string
8625 (an argument to the HP C exec* set of functions).
8626
8627 Logical Name:
8628 @smallexample
8629 DEFINE ANOTHER_PATH FOO:[BAG]
8630 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8631 @end smallexample
8632
8633 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8634 first, followed by the standard Ada
8635 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8636 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8637 (Text_IO, Sequential_IO, etc)
8638 instead of the standard Ada packages. Thus, in order to get the standard Ada
8639 packages by default, ADA_OBJECTS_PATH must be redefined.
8640 @end ifset
8641
8642 @item
8643 The content of the @file{ada_object_path} file which is part of the GNAT
8644 installation tree and is used to store standard libraries such as the
8645 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8646 specified.
8647 @ifclear vms
8648 @ref{Installing a library}
8649 @end ifclear
8650 @end enumerate
8651
8652 @noindent
8653 In the binder the switch @option{^-I^/SEARCH^}
8654 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8655 is used to specify both source and
8656 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8657 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8658 instead if you want to specify
8659 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8660 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8661 if you want to specify library paths
8662 only. This means that for the binder
8663 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8664 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8665 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8666 The binder generates the bind file (a C language source file) in the
8667 current working directory.
8668
8669 @findex Ada
8670 @findex System
8671 @findex Interfaces
8672 @findex GNAT
8673 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8674 children make up the GNAT Run-Time Library, together with the package
8675 GNAT and its children, which contain a set of useful additional
8676 library functions provided by GNAT. The sources for these units are
8677 needed by the compiler and are kept together in one directory. The ALI
8678 files and object files generated by compiling the RTL are needed by the
8679 binder and the linker and are kept together in one directory, typically
8680 different from the directory containing the sources. In a normal
8681 installation, you need not specify these directory names when compiling
8682 or binding. Either the environment variables or the built-in defaults
8683 cause these files to be found.
8684
8685 Besides simplifying access to the RTL, a major use of search paths is
8686 in compiling sources from multiple directories. This can make
8687 development environments much more flexible.
8688
8689 @node Examples of gnatbind Usage
8690 @section Examples of @code{gnatbind} Usage
8691
8692 @noindent
8693 This section contains a number of examples of using the GNAT binding
8694 utility @code{gnatbind}.
8695
8696 @table @code
8697 @item gnatbind hello
8698 The main program @code{Hello} (source program in @file{hello.adb}) is
8699 bound using the standard switch settings. The generated main program is
8700 @file{b~hello.adb}. This is the normal, default use of the binder.
8701
8702 @ifclear vms
8703 @item gnatbind hello -o mainprog.adb
8704 @end ifclear
8705 @ifset vms
8706 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8707 @end ifset
8708 The main program @code{Hello} (source program in @file{hello.adb}) is
8709 bound using the standard switch settings. The generated main program is
8710 @file{mainprog.adb} with the associated spec in
8711 @file{mainprog.ads}. Note that you must specify the body here not the
8712 spec, in the case where the output is in Ada. Note that if this option
8713 is used, then linking must be done manually, since gnatlink will not
8714 be able to find the generated file.
8715
8716 @ifclear vms
8717 @item gnatbind main -C -o mainprog.c -x
8718 @end ifclear
8719 @ifset vms
8720 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8721 @end ifset
8722 The main program @code{Main} (source program in
8723 @file{main.adb}) is bound, excluding source files from the
8724 consistency checking, generating
8725 the file @file{mainprog.c}.
8726
8727 @ifclear vms
8728 @item gnatbind -x main_program -C -o mainprog.c
8729 This command is exactly the same as the previous example. Switches may
8730 appear anywhere in the command line, and single letter switches may be
8731 combined into a single switch.
8732 @end ifclear
8733
8734 @ifclear vms
8735 @item gnatbind -n math dbase -C -o ada-control.c
8736 @end ifclear
8737 @ifset vms
8738 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8739 @end ifset
8740 The main program is in a language other than Ada, but calls to
8741 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8742 to @code{gnatbind} generates the file @file{ada-control.c} containing
8743 the @code{adainit} and @code{adafinal} routines to be called before and
8744 after accessing the Ada units.
8745 @end table
8746
8747 @c ------------------------------------
8748 @node Linking Using gnatlink
8749 @chapter Linking Using @command{gnatlink}
8750 @c ------------------------------------
8751 @findex gnatlink
8752
8753 @noindent
8754 This chapter discusses @command{gnatlink}, a tool that links
8755 an Ada program and builds an executable file. This utility
8756 invokes the system linker ^(via the @command{gcc} command)^^
8757 with a correct list of object files and library references.
8758 @command{gnatlink} automatically determines the list of files and
8759 references for the Ada part of a program. It uses the binder file
8760 generated by the @command{gnatbind} to determine this list.
8761
8762 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8763 driver (see @ref{The GNAT Driver and Project Files}).
8764
8765 @menu
8766 * Running gnatlink::
8767 * Switches for gnatlink::
8768 @end menu
8769
8770 @node Running gnatlink
8771 @section Running @command{gnatlink}
8772
8773 @noindent
8774 The form of the @command{gnatlink} command is
8775
8776 @smallexample
8777 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8778            @ovar{non-Ada objects} @ovar{linker options}
8779 @end smallexample
8780
8781 @noindent
8782 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8783 non-Ada objects
8784 or linker options) may be in any order, provided that no non-Ada object may
8785 be mistaken for a main @file{ALI} file.
8786 Any file name @file{F} without the @file{.ali}
8787 extension will be taken as the main @file{ALI} file if a file exists
8788 whose name is the concatenation of @file{F} and @file{.ali}.
8789
8790 @noindent
8791 @file{@var{mainprog}.ali} references the ALI file of the main program.
8792 The @file{.ali} extension of this file can be omitted. From this
8793 reference, @command{gnatlink} locates the corresponding binder file
8794 @file{b~@var{mainprog}.adb} and, using the information in this file along
8795 with the list of non-Ada objects and linker options, constructs a
8796 linker command file to create the executable.
8797
8798 The arguments other than the @command{gnatlink} switches and the main
8799 @file{ALI} file are passed to the linker uninterpreted.
8800 They typically include the names of
8801 object files for units written in other languages than Ada and any library
8802 references required to resolve references in any of these foreign language
8803 units, or in @code{Import} pragmas in any Ada units.
8804
8805 @var{linker options} is an optional list of linker specific
8806 switches.
8807 The default linker called by gnatlink is @command{gcc} which in
8808 turn calls the appropriate system linker.
8809 Standard options for the linker such as @option{-lmy_lib} or
8810 @option{-Ldir} can be added as is.
8811 For options that are not recognized by
8812 @command{gcc} as linker options, use the @command{gcc} switches
8813 @option{-Xlinker} or @option{-Wl,}.
8814 Refer to the GCC documentation for
8815 details. Here is an example showing how to generate a linker map:
8816
8817 @smallexample
8818 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8819 @end smallexample
8820
8821 Using @var{linker options} it is possible to set the program stack and
8822 heap size.
8823 @ifset unw
8824 See @ref{Setting Stack Size from gnatlink} and
8825 @ref{Setting Heap Size from gnatlink}.
8826 @end ifset
8827
8828 @command{gnatlink} determines the list of objects required by the Ada
8829 program and prepends them to the list of objects passed to the linker.
8830 @command{gnatlink} also gathers any arguments set by the use of
8831 @code{pragma Linker_Options} and adds them to the list of arguments
8832 presented to the linker.
8833
8834 @ifset vms
8835 @command{gnatlink} accepts the following types of extra files on the command
8836 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8837 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8838 handled according to their extension.
8839 @end ifset
8840
8841 @node Switches for gnatlink
8842 @section Switches for @command{gnatlink}
8843
8844 @noindent
8845 The following switches are available with the @command{gnatlink} utility:
8846
8847 @table @option
8848 @c !sort!
8849
8850 @item --version
8851 @cindex @option{--version} @command{gnatlink}
8852 Display Copyright and version, then exit disregarding all other options.
8853
8854 @item --help
8855 @cindex @option{--help} @command{gnatlink}
8856 If @option{--version} was not used, display usage, then exit disregarding
8857 all other options.
8858
8859 @item ^-A^/BIND_FILE=ADA^
8860 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8861 The binder has generated code in Ada. This is the default.
8862
8863 @item ^-C^/BIND_FILE=C^
8864 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8865 If instead of generating a file in Ada, the binder has generated one in
8866 C, then the linker needs to know about it. Use this switch to signal
8867 to @command{gnatlink} that the binder has generated C code rather than
8868 Ada code.
8869
8870 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8871 @cindex Command line length
8872 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8873 On some targets, the command line length is limited, and @command{gnatlink}
8874 will generate a separate file for the linker if the list of object files
8875 is too long.
8876 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8877 to be generated even if
8878 the limit is not exceeded. This is useful in some cases to deal with
8879 special situations where the command line length is exceeded.
8880
8881 @item ^-g^/DEBUG^
8882 @cindex Debugging information, including
8883 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8884 The option to include debugging information causes the Ada bind file (in
8885 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8886 @option{^-g^/DEBUG^}.
8887 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8888 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8889 Without @option{^-g^/DEBUG^}, the binder removes these files by
8890 default. The same procedure apply if a C bind file was generated using
8891 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8892 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8893
8894 @item ^-n^/NOCOMPILE^
8895 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8896 Do not compile the file generated by the binder. This may be used when
8897 a link is rerun with different options, but there is no need to recompile
8898 the binder file.
8899
8900 @item ^-v^/VERBOSE^
8901 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8902 Causes additional information to be output, including a full list of the
8903 included object files. This switch option is most useful when you want
8904 to see what set of object files are being used in the link step.
8905
8906 @item ^-v -v^/VERBOSE/VERBOSE^
8907 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8908 Very verbose mode. Requests that the compiler operate in verbose mode when
8909 it compiles the binder file, and that the system linker run in verbose mode.
8910
8911 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8912 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8913 @var{exec-name} specifies an alternate name for the generated
8914 executable program. If this switch is omitted, the executable has the same
8915 name as the main unit. For example, @code{gnatlink try.ali} creates
8916 an executable called @file{^try^TRY.EXE^}.
8917
8918 @ifclear vms
8919 @item -b @var{target}
8920 @cindex @option{-b} (@command{gnatlink})
8921 Compile your program to run on @var{target}, which is the name of a
8922 system configuration. You must have a GNAT cross-compiler built if
8923 @var{target} is not the same as your host system.
8924
8925 @item -B@var{dir}
8926 @cindex @option{-B} (@command{gnatlink})
8927 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8928 from @var{dir} instead of the default location. Only use this switch
8929 when multiple versions of the GNAT compiler are available.
8930 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8931 for further details. You would normally use the @option{-b} or
8932 @option{-V} switch instead.
8933
8934 @item --GCC=@var{compiler_name}
8935 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8936 Program used for compiling the binder file. The default is
8937 @command{gcc}. You need to use quotes around @var{compiler_name} if
8938 @code{compiler_name} contains spaces or other separator characters.
8939 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8940 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8941 inserted after your command name. Thus in the above example the compiler
8942 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8943 A limitation of this syntax is that the name and path name of the executable
8944 itself must not include any embedded spaces. If the compiler executable is
8945 different from the default one (gcc or <prefix>-gcc), then the back-end
8946 switches in the ALI file are not used to compile the binder generated source.
8947 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8948 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8949 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8950 is taken into account. However, all the additional switches are also taken
8951 into account. Thus,
8952 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8953 @option{--GCC="bar -x -y -z -t"}.
8954
8955 @item --LINK=@var{name}
8956 @cindex @option{--LINK=} (@command{gnatlink})
8957 @var{name} is the name of the linker to be invoked. This is especially
8958 useful in mixed language programs since languages such as C++ require
8959 their own linker to be used. When this switch is omitted, the default
8960 name for the linker is @command{gcc}. When this switch is used, the
8961 specified linker is called instead of @command{gcc} with exactly the same
8962 parameters that would have been passed to @command{gcc} so if the desired
8963 linker requires different parameters it is necessary to use a wrapper
8964 script that massages the parameters before invoking the real linker. It
8965 may be useful to control the exact invocation by using the verbose
8966 switch.
8967
8968 @end ifclear
8969
8970 @ifset vms
8971 @item /DEBUG=TRACEBACK
8972 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8973 This qualifier causes sufficient information to be included in the
8974 executable file to allow a traceback, but does not include the full
8975 symbol information needed by the debugger.
8976
8977 @item /IDENTIFICATION="<string>"
8978 @code{"<string>"} specifies the string to be stored in the image file
8979 identification field in the image header.
8980 It overrides any pragma @code{Ident} specified string.
8981
8982 @item /NOINHIBIT-EXEC
8983 Generate the executable file even if there are linker warnings.
8984
8985 @item /NOSTART_FILES
8986 Don't link in the object file containing the ``main'' transfer address.
8987 Used when linking with a foreign language main program compiled with an
8988 HP compiler.
8989
8990 @item /STATIC
8991 Prefer linking with object libraries over sharable images, even without
8992 /DEBUG.
8993 @end ifset
8994
8995 @end table
8996
8997 @node The GNAT Make Program gnatmake
8998 @chapter The GNAT Make Program @command{gnatmake}
8999 @findex gnatmake
9000
9001 @menu
9002 * Running gnatmake::
9003 * Switches for gnatmake::
9004 * Mode Switches for gnatmake::
9005 * Notes on the Command Line::
9006 * How gnatmake Works::
9007 * Examples of gnatmake Usage::
9008 @end menu
9009 @noindent
9010 A typical development cycle when working on an Ada program consists of
9011 the following steps:
9012
9013 @enumerate
9014 @item
9015 Edit some sources to fix bugs.
9016
9017 @item
9018 Add enhancements.
9019
9020 @item
9021 Compile all sources affected.
9022
9023 @item
9024 Rebind and relink.
9025
9026 @item
9027 Test.
9028 @end enumerate
9029
9030 @noindent
9031 The third step can be tricky, because not only do the modified files
9032 @cindex Dependency rules
9033 have to be compiled, but any files depending on these files must also be
9034 recompiled. The dependency rules in Ada can be quite complex, especially
9035 in the presence of overloading, @code{use} clauses, generics and inlined
9036 subprograms.
9037
9038 @command{gnatmake} automatically takes care of the third and fourth steps
9039 of this process. It determines which sources need to be compiled,
9040 compiles them, and binds and links the resulting object files.
9041
9042 Unlike some other Ada make programs, the dependencies are always
9043 accurately recomputed from the new sources. The source based approach of
9044 the GNAT compilation model makes this possible. This means that if
9045 changes to the source program cause corresponding changes in
9046 dependencies, they will always be tracked exactly correctly by
9047 @command{gnatmake}.
9048
9049 @node Running gnatmake
9050 @section Running @command{gnatmake}
9051
9052 @noindent
9053 The usual form of the @command{gnatmake} command is
9054
9055 @smallexample
9056 $ gnatmake @ovar{switches} @var{file_name}
9057       @ovar{file_names} @ovar{mode_switches}
9058 @end smallexample
9059
9060 @noindent
9061 The only required argument is one @var{file_name}, which specifies
9062 a compilation unit that is a main program. Several @var{file_names} can be
9063 specified: this will result in several executables being built.
9064 If @code{switches} are present, they can be placed before the first
9065 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9066 If @var{mode_switches} are present, they must always be placed after
9067 the last @var{file_name} and all @code{switches}.
9068
9069 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9070 extension may be omitted from the @var{file_name} arguments. However, if
9071 you are using non-standard extensions, then it is required that the
9072 extension be given. A relative or absolute directory path can be
9073 specified in a @var{file_name}, in which case, the input source file will
9074 be searched for in the specified directory only. Otherwise, the input
9075 source file will first be searched in the directory where
9076 @command{gnatmake} was invoked and if it is not found, it will be search on
9077 the source path of the compiler as described in
9078 @ref{Search Paths and the Run-Time Library (RTL)}.
9079
9080 All @command{gnatmake} output (except when you specify
9081 @option{^-M^/DEPENDENCIES_LIST^}) is to
9082 @file{stderr}. The output produced by the
9083 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9084 @file{stdout}.
9085
9086 @node Switches for gnatmake
9087 @section Switches for @command{gnatmake}
9088
9089 @noindent
9090 You may specify any of the following switches to @command{gnatmake}:
9091
9092 @table @option
9093 @c !sort!
9094
9095 @item --version
9096 @cindex @option{--version} @command{gnatmake}
9097 Display Copyright and version, then exit disregarding all other options.
9098
9099 @item --help
9100 @cindex @option{--help} @command{gnatmake}
9101 If @option{--version} was not used, display usage, then exit disregarding
9102 all other options.
9103
9104 @ifclear vms
9105 @item --GCC=@var{compiler_name}
9106 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9107 Program used for compiling. The default is `@command{gcc}'. You need to use
9108 quotes around @var{compiler_name} if @code{compiler_name} contains
9109 spaces or other separator characters. As an example @option{--GCC="foo -x
9110 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9111 compiler. A limitation of this syntax is that the name and path name of
9112 the executable itself must not include any embedded spaces. Note that
9113 switch @option{-c} is always inserted after your command name. Thus in the
9114 above example the compiler command that will be used by @command{gnatmake}
9115 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9116 used, only the last @var{compiler_name} is taken into account. However,
9117 all the additional switches are also taken into account. Thus,
9118 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9119 @option{--GCC="bar -x -y -z -t"}.
9120
9121 @item --GNATBIND=@var{binder_name}
9122 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9123 Program used for binding. The default is `@code{gnatbind}'. You need to
9124 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9125 or other separator characters. As an example @option{--GNATBIND="bar -x
9126 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9127 binder. Binder switches that are normally appended by @command{gnatmake}
9128 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9129 A limitation of this syntax is that the name and path name of the executable
9130 itself must not include any embedded spaces.
9131
9132 @item --GNATLINK=@var{linker_name}
9133 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9134 Program used for linking. The default is `@command{gnatlink}'. You need to
9135 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9136 or other separator characters. As an example @option{--GNATLINK="lan -x
9137 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9138 linker. Linker switches that are normally appended by @command{gnatmake} to
9139 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9140 A limitation of this syntax is that the name and path name of the executable
9141 itself must not include any embedded spaces.
9142
9143 @end ifclear
9144
9145 @item ^-a^/ALL_FILES^
9146 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9147 Consider all files in the make process, even the GNAT internal system
9148 files (for example, the predefined Ada library files), as well as any
9149 locked files. Locked files are files whose ALI file is write-protected.
9150 By default,
9151 @command{gnatmake} does not check these files,
9152 because the assumption is that the GNAT internal files are properly up
9153 to date, and also that any write protected ALI files have been properly
9154 installed. Note that if there is an installation problem, such that one
9155 of these files is not up to date, it will be properly caught by the
9156 binder.
9157 You may have to specify this switch if you are working on GNAT
9158 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9159 in conjunction with @option{^-f^/FORCE_COMPILE^}
9160 if you need to recompile an entire application,
9161 including run-time files, using special configuration pragmas,
9162 such as a @code{Normalize_Scalars} pragma.
9163
9164 By default
9165 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9166 internal files with
9167 @ifclear vms
9168 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9169 @end ifclear
9170 @ifset vms
9171 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9172 @end ifset
9173
9174 @item ^-b^/ACTIONS=BIND^
9175 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9176 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9177 compilation and binding, but no link.
9178 Can be combined with @option{^-l^/ACTIONS=LINK^}
9179 to do binding and linking. When not combined with
9180 @option{^-c^/ACTIONS=COMPILE^}
9181 all the units in the closure of the main program must have been previously
9182 compiled and must be up to date. The root unit specified by @var{file_name}
9183 may be given without extension, with the source extension or, if no GNAT
9184 Project File is specified, with the ALI file extension.
9185
9186 @item ^-c^/ACTIONS=COMPILE^
9187 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9188 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9189 is also specified. Do not perform linking, except if both
9190 @option{^-b^/ACTIONS=BIND^} and
9191 @option{^-l^/ACTIONS=LINK^} are also specified.
9192 If the root unit specified by @var{file_name} is not a main unit, this is the
9193 default. Otherwise @command{gnatmake} will attempt binding and linking
9194 unless all objects are up to date and the executable is more recent than
9195 the objects.
9196
9197 @item ^-C^/MAPPING^
9198 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9199 Use a temporary mapping file. A mapping file is a way to communicate to the
9200 compiler two mappings: from unit names to file names (without any directory
9201 information) and from file names to path names (with full directory
9202 information). These mappings are used by the compiler to short-circuit the path
9203 search. When @command{gnatmake} is invoked with this switch, it will create
9204 a temporary mapping file, initially populated by the project manager,
9205 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9206 Each invocation of the compiler will add the newly accessed sources to the
9207 mapping file. This will improve the source search during the next invocation
9208 of the compiler.
9209
9210 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9211 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9212 Use a specific mapping file. The file, specified as a path name (absolute or
9213 relative) by this switch, should already exist, otherwise the switch is
9214 ineffective. The specified mapping file will be communicated to the compiler.
9215 This switch is not compatible with a project file
9216 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9217 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9218
9219 @item ^-d^/DISPLAY_PROGRESS^
9220 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9221 Display progress for each source, up to date or not, as a single line
9222
9223 @smallexample
9224 completed x out of y (zz%)
9225 @end smallexample
9226
9227 If the file needs to be compiled this is displayed after the invocation of
9228 the compiler. These lines are displayed even in quiet output mode.
9229
9230 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9231 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9232 Put all object files and ALI file in directory @var{dir}.
9233 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9234 and ALI files go in the current working directory.
9235
9236 This switch cannot be used when using a project file.
9237
9238 @ifclear vms
9239 @item -eL
9240 @cindex @option{-eL} (@command{gnatmake})
9241 Follow all symbolic links when processing project files.
9242 @end ifclear
9243
9244 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9245 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9246 Output the commands for the compiler, the binder and the linker
9247 on ^standard output^SYS$OUTPUT^,
9248 instead of ^standard error^SYS$ERROR^.
9249
9250 @item ^-f^/FORCE_COMPILE^
9251 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9252 Force recompilations. Recompile all sources, even though some object
9253 files may be up to date, but don't recompile predefined or GNAT internal
9254 files or locked files (files with a write-protected ALI file),
9255 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9256
9257 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9258 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9259 When using project files, if some errors or warnings are detected during
9260 parsing and verbose mode is not in effect (no use of switch
9261 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9262 file, rather than its simple file name.
9263
9264 @item ^-g^/DEBUG^
9265 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9266 Enable debugging. This switch is simply passed to the compiler and to the
9267 linker.
9268
9269 @item ^-i^/IN_PLACE^
9270 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9271 In normal mode, @command{gnatmake} compiles all object files and ALI files
9272 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9273 then instead object files and ALI files that already exist are overwritten
9274 in place. This means that once a large project is organized into separate
9275 directories in the desired manner, then @command{gnatmake} will automatically
9276 maintain and update this organization. If no ALI files are found on the
9277 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9278 the new object and ALI files are created in the
9279 directory containing the source being compiled. If another organization
9280 is desired, where objects and sources are kept in different directories,
9281 a useful technique is to create dummy ALI files in the desired directories.
9282 When detecting such a dummy file, @command{gnatmake} will be forced to
9283 recompile the corresponding source file, and it will be put the resulting
9284 object and ALI files in the directory where it found the dummy file.
9285
9286 @item ^-j^/PROCESSES=^@var{n}
9287 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9288 @cindex Parallel make
9289 Use @var{n} processes to carry out the (re)compilations. On a
9290 multiprocessor machine compilations will occur in parallel. In the
9291 event of compilation errors, messages from various compilations might
9292 get interspersed (but @command{gnatmake} will give you the full ordered
9293 list of failing compiles at the end). If this is problematic, rerun
9294 the make process with n set to 1 to get a clean list of messages.
9295
9296 @item ^-k^/CONTINUE_ON_ERROR^
9297 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9298 Keep going. Continue as much as possible after a compilation error. To
9299 ease the programmer's task in case of compilation errors, the list of
9300 sources for which the compile fails is given when @command{gnatmake}
9301 terminates.
9302
9303 If @command{gnatmake} is invoked with several @file{file_names} and with this
9304 switch, if there are compilation errors when building an executable,
9305 @command{gnatmake} will not attempt to build the following executables.
9306
9307 @item ^-l^/ACTIONS=LINK^
9308 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9309 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9310 and linking. Linking will not be performed if combined with
9311 @option{^-c^/ACTIONS=COMPILE^}
9312 but not with @option{^-b^/ACTIONS=BIND^}.
9313 When not combined with @option{^-b^/ACTIONS=BIND^}
9314 all the units in the closure of the main program must have been previously
9315 compiled and must be up to date, and the main program needs to have been bound.
9316 The root unit specified by @var{file_name}
9317 may be given without extension, with the source extension or, if no GNAT
9318 Project File is specified, with the ALI file extension.
9319
9320 @item ^-m^/MINIMAL_RECOMPILATION^
9321 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9322 Specify that the minimum necessary amount of recompilations
9323 be performed. In this mode @command{gnatmake} ignores time
9324 stamp differences when the only
9325 modifications to a source file consist in adding/removing comments,
9326 empty lines, spaces or tabs. This means that if you have changed the
9327 comments in a source file or have simply reformatted it, using this
9328 switch will tell @command{gnatmake} not to recompile files that depend on it
9329 (provided other sources on which these files depend have undergone no
9330 semantic modifications). Note that the debugging information may be
9331 out of date with respect to the sources if the @option{-m} switch causes
9332 a compilation to be switched, so the use of this switch represents a
9333 trade-off between compilation time and accurate debugging information.
9334
9335 @item ^-M^/DEPENDENCIES_LIST^
9336 @cindex Dependencies, producing list
9337 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9338 Check if all objects are up to date. If they are, output the object
9339 dependences to @file{stdout} in a form that can be directly exploited in
9340 a @file{Makefile}. By default, each source file is prefixed with its
9341 (relative or absolute) directory name. This name is whatever you
9342 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9343 and @option{^-I^/SEARCH^} switches. If you use
9344 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9345 @option{^-q^/QUIET^}
9346 (see below), only the source file names,
9347 without relative paths, are output. If you just specify the
9348 @option{^-M^/DEPENDENCIES_LIST^}
9349 switch, dependencies of the GNAT internal system files are omitted. This
9350 is typically what you want. If you also specify
9351 the @option{^-a^/ALL_FILES^} switch,
9352 dependencies of the GNAT internal files are also listed. Note that
9353 dependencies of the objects in external Ada libraries (see switch
9354 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9355 are never reported.
9356
9357 @item ^-n^/DO_OBJECT_CHECK^
9358 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9359 Don't compile, bind, or link. Checks if all objects are up to date.
9360 If they are not, the full name of the first file that needs to be
9361 recompiled is printed.
9362 Repeated use of this option, followed by compiling the indicated source
9363 file, will eventually result in recompiling all required units.
9364
9365 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9366 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9367 Output executable name. The name of the final executable program will be
9368 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9369 name for the executable will be the name of the input file in appropriate form
9370 for an executable file on the host system.
9371
9372 This switch cannot be used when invoking @command{gnatmake} with several
9373 @file{file_names}.
9374
9375 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9376 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9377 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9378 automatically missing object directories, library directories and exec
9379 directories.
9380
9381 @item ^-P^/PROJECT_FILE=^@var{project}
9382 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9383 Use project file @var{project}. Only one such switch can be used.
9384 @xref{gnatmake and Project Files}.
9385
9386 @item ^-q^/QUIET^
9387 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9388 Quiet. When this flag is not set, the commands carried out by
9389 @command{gnatmake} are displayed.
9390
9391 @item ^-s^/SWITCH_CHECK/^
9392 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9393 Recompile if compiler switches have changed since last compilation.
9394 All compiler switches but -I and -o are taken into account in the
9395 following way:
9396 orders between different ``first letter'' switches are ignored, but
9397 orders between same switches are taken into account. For example,
9398 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9399 is equivalent to @option{-O -g}.
9400
9401 This switch is recommended when Integrated Preprocessing is used.
9402
9403 @item ^-u^/UNIQUE^
9404 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9405 Unique. Recompile at most the main files. It implies -c. Combined with
9406 -f, it is equivalent to calling the compiler directly. Note that using
9407 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9408 (@pxref{Project Files and Main Subprograms}).
9409
9410 @item ^-U^/ALL_PROJECTS^
9411 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9412 When used without a project file or with one or several mains on the command
9413 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9414 on the command line, all sources of all project files are checked and compiled
9415 if not up to date, and libraries are rebuilt, if necessary.
9416
9417 @item ^-v^/REASONS^
9418 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9419 Verbose. Display the reason for all recompilations @command{gnatmake}
9420 decides are necessary, with the highest verbosity level.
9421
9422 @item ^-vl^/LOW_VERBOSITY^
9423 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9424 Verbosity level Low. Display fewer lines than in verbosity Medium.
9425
9426 @item ^-vm^/MEDIUM_VERBOSITY^
9427 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9428 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9429
9430 @item ^-vh^/HIGH_VERBOSITY^
9431 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9432 Verbosity level High. Equivalent to ^-v^/REASONS^.
9433
9434 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9435 Indicate the verbosity of the parsing of GNAT project files.
9436 @xref{Switches Related to Project Files}.
9437
9438 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9439 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9440 Indicate that sources that are not part of any Project File may be compiled.
9441 Normally, when using Project Files, only sources that are part of a Project
9442 File may be compile. When this switch is used, a source outside of all Project
9443 Files may be compiled. The ALI file and the object file will be put in the
9444 object directory of the main Project. The compilation switches used will only
9445 be those specified on the command line. Even when
9446 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9447 command line need to be sources of a project file.
9448
9449 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9450 Indicate that external variable @var{name} has the value @var{value}.
9451 The Project Manager will use this value for occurrences of
9452 @code{external(name)} when parsing the project file.
9453 @xref{Switches Related to Project Files}.
9454
9455 @item ^-z^/NOMAIN^
9456 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9457 No main subprogram. Bind and link the program even if the unit name
9458 given on the command line is a package name. The resulting executable
9459 will execute the elaboration routines of the package and its closure,
9460 then the finalization routines.
9461
9462 @end table
9463
9464 @table @asis
9465 @item @command{gcc} @asis{switches}
9466 @ifclear vms
9467 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9468 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9469 @end ifclear
9470 @ifset vms
9471 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9472 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9473 automatically treated as a compiler switch, and passed on to all
9474 compilations that are carried out.
9475 @end ifset
9476 @end table
9477
9478 @noindent
9479 Source and library search path switches:
9480
9481 @table @option
9482 @c !sort!
9483 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9484 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9485 When looking for source files also look in directory @var{dir}.
9486 The order in which source files search is undertaken is
9487 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9488
9489 @item ^-aL^/SKIP_MISSING=^@var{dir}
9490 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9491 Consider @var{dir} as being an externally provided Ada library.
9492 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9493 files have been located in directory @var{dir}. This allows you to have
9494 missing bodies for the units in @var{dir} and to ignore out of date bodies
9495 for the same units. You still need to specify
9496 the location of the specs for these units by using the switches
9497 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9498 or @option{^-I^/SEARCH=^@var{dir}}.
9499 Note: this switch is provided for compatibility with previous versions
9500 of @command{gnatmake}. The easier method of causing standard libraries
9501 to be excluded from consideration is to write-protect the corresponding
9502 ALI files.
9503
9504 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9505 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9506 When searching for library and object files, look in directory
9507 @var{dir}. The order in which library files are searched is described in
9508 @ref{Search Paths for gnatbind}.
9509
9510 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9511 @cindex Search paths, for @command{gnatmake}
9512 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9513 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9514 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9515
9516 @item ^-I^/SEARCH=^@var{dir}
9517 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9518 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9519 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9520
9521 @item ^-I-^/NOCURRENT_DIRECTORY^
9522 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9523 @cindex Source files, suppressing search
9524 Do not look for source files in the directory containing the source
9525 file named in the command line.
9526 Do not look for ALI or object files in the directory
9527 where @command{gnatmake} was invoked.
9528
9529 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9530 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9531 @cindex Linker libraries
9532 Add directory @var{dir} to the list of directories in which the linker
9533 will search for libraries. This is equivalent to
9534 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9535 @ifclear vms
9536 Furthermore, under Windows, the sources pointed to by the libraries path
9537 set in the registry are not searched for.
9538 @end ifclear
9539
9540 @item -nostdinc
9541 @cindex @option{-nostdinc} (@command{gnatmake})
9542 Do not look for source files in the system default directory.
9543
9544 @item -nostdlib
9545 @cindex @option{-nostdlib} (@command{gnatmake})
9546 Do not look for library files in the system default directory.
9547
9548 @item --RTS=@var{rts-path}
9549 @cindex @option{--RTS} (@command{gnatmake})
9550 Specifies the default location of the runtime library. GNAT looks for the
9551 runtime
9552 in the following directories, and stops as soon as a valid runtime is found
9553 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9554 @file{ada_object_path} present):
9555
9556 @itemize @bullet
9557 @item <current directory>/$rts_path
9558
9559 @item <default-search-dir>/$rts_path
9560
9561 @item <default-search-dir>/rts-$rts_path
9562 @end itemize
9563
9564 @noindent
9565 The selected path is handled like a normal RTS path.
9566
9567 @end table
9568
9569 @node Mode Switches for gnatmake
9570 @section Mode Switches for @command{gnatmake}
9571
9572 @noindent
9573 The mode switches (referred to as @code{mode_switches}) allow the
9574 inclusion of switches that are to be passed to the compiler itself, the
9575 binder or the linker. The effect of a mode switch is to cause all
9576 subsequent switches up to the end of the switch list, or up to the next
9577 mode switch, to be interpreted as switches to be passed on to the
9578 designated component of GNAT.
9579
9580 @table @option
9581 @c !sort!
9582 @item -cargs @var{switches}
9583 @cindex @option{-cargs} (@command{gnatmake})
9584 Compiler switches. Here @var{switches} is a list of switches
9585 that are valid switches for @command{gcc}. They will be passed on to
9586 all compile steps performed by @command{gnatmake}.
9587
9588 @item -bargs @var{switches}
9589 @cindex @option{-bargs} (@command{gnatmake})
9590 Binder switches. Here @var{switches} is a list of switches
9591 that are valid switches for @code{gnatbind}. They will be passed on to
9592 all bind steps performed by @command{gnatmake}.
9593
9594 @item -largs @var{switches}
9595 @cindex @option{-largs} (@command{gnatmake})
9596 Linker switches. Here @var{switches} is a list of switches
9597 that are valid switches for @command{gnatlink}. They will be passed on to
9598 all link steps performed by @command{gnatmake}.
9599
9600 @item -margs @var{switches}
9601 @cindex @option{-margs} (@command{gnatmake})
9602 Make switches. The switches are directly interpreted by @command{gnatmake},
9603 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9604 or @option{-largs}.
9605 @end table
9606
9607 @node Notes on the Command Line
9608 @section Notes on the Command Line
9609
9610 @noindent
9611 This section contains some additional useful notes on the operation
9612 of the @command{gnatmake} command.
9613
9614 @itemize @bullet
9615 @item
9616 @cindex Recompilation, by @command{gnatmake}
9617 If @command{gnatmake} finds no ALI files, it recompiles the main program
9618 and all other units required by the main program.
9619 This means that @command{gnatmake}
9620 can be used for the initial compile, as well as during subsequent steps of
9621 the development cycle.
9622
9623 @item
9624 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9625 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9626 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9627 warning.
9628
9629 @item
9630 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9631 is used to specify both source and
9632 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9633 instead if you just want to specify
9634 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9635 if you want to specify library paths
9636 only.
9637
9638 @item
9639 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9640 This may conveniently be used to exclude standard libraries from
9641 consideration and in particular it means that the use of the
9642 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9643 unless @option{^-a^/ALL_FILES^} is also specified.
9644
9645 @item
9646 @command{gnatmake} has been designed to make the use of Ada libraries
9647 particularly convenient. Assume you have an Ada library organized
9648 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9649 of your Ada compilation units,
9650 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9651 specs of these units, but no bodies. Then to compile a unit
9652 stored in @code{main.adb}, which uses this Ada library you would just type
9653
9654 @smallexample
9655 @ifclear vms
9656 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9657 @end ifclear
9658 @ifset vms
9659 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9660            /SKIP_MISSING=@i{[OBJ_DIR]} main
9661 @end ifset
9662 @end smallexample
9663
9664 @item
9665 Using @command{gnatmake} along with the
9666 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9667 switch provides a mechanism for avoiding unnecessary recompilations. Using
9668 this switch,
9669 you can update the comments/format of your
9670 source files without having to recompile everything. Note, however, that
9671 adding or deleting lines in a source files may render its debugging
9672 info obsolete. If the file in question is a spec, the impact is rather
9673 limited, as that debugging info will only be useful during the
9674 elaboration phase of your program. For bodies the impact can be more
9675 significant. In all events, your debugger will warn you if a source file
9676 is more recent than the corresponding object, and alert you to the fact
9677 that the debugging information may be out of date.
9678 @end itemize
9679
9680 @node How gnatmake Works
9681 @section How @command{gnatmake} Works
9682
9683 @noindent
9684 Generally @command{gnatmake} automatically performs all necessary
9685 recompilations and you don't need to worry about how it works. However,
9686 it may be useful to have some basic understanding of the @command{gnatmake}
9687 approach and in particular to understand how it uses the results of
9688 previous compilations without incorrectly depending on them.
9689
9690 First a definition: an object file is considered @dfn{up to date} if the
9691 corresponding ALI file exists and if all the source files listed in the
9692 dependency section of this ALI file have time stamps matching those in
9693 the ALI file. This means that neither the source file itself nor any
9694 files that it depends on have been modified, and hence there is no need
9695 to recompile this file.
9696
9697 @command{gnatmake} works by first checking if the specified main unit is up
9698 to date. If so, no compilations are required for the main unit. If not,
9699 @command{gnatmake} compiles the main program to build a new ALI file that
9700 reflects the latest sources. Then the ALI file of the main unit is
9701 examined to find all the source files on which the main program depends,
9702 and @command{gnatmake} recursively applies the above procedure on all these
9703 files.
9704
9705 This process ensures that @command{gnatmake} only trusts the dependencies
9706 in an existing ALI file if they are known to be correct. Otherwise it
9707 always recompiles to determine a new, guaranteed accurate set of
9708 dependencies. As a result the program is compiled ``upside down'' from what may
9709 be more familiar as the required order of compilation in some other Ada
9710 systems. In particular, clients are compiled before the units on which
9711 they depend. The ability of GNAT to compile in any order is critical in
9712 allowing an order of compilation to be chosen that guarantees that
9713 @command{gnatmake} will recompute a correct set of new dependencies if
9714 necessary.
9715
9716 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9717 imported by several of the executables, it will be recompiled at most once.
9718
9719 Note: when using non-standard naming conventions
9720 (@pxref{Using Other File Names}), changing through a configuration pragmas
9721 file the version of a source and invoking @command{gnatmake} to recompile may
9722 have no effect, if the previous version of the source is still accessible
9723 by @command{gnatmake}. It may be necessary to use the switch
9724 ^-f^/FORCE_COMPILE^.
9725
9726 @node Examples of gnatmake Usage
9727 @section Examples of @command{gnatmake} Usage
9728
9729 @table @code
9730 @item gnatmake hello.adb
9731 Compile all files necessary to bind and link the main program
9732 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9733 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9734
9735 @item gnatmake main1 main2 main3
9736 Compile all files necessary to bind and link the main programs
9737 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9738 (containing unit @code{Main2}) and @file{main3.adb}
9739 (containing unit @code{Main3}) and bind and link the resulting object files
9740 to generate three executable files @file{^main1^MAIN1.EXE^},
9741 @file{^main2^MAIN2.EXE^}
9742 and @file{^main3^MAIN3.EXE^}.
9743
9744 @ifclear vms
9745 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9746 @end ifclear
9747
9748 @ifset vms
9749 @item gnatmake Main_Unit /QUIET
9750 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9751 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9752 @end ifset
9753 Compile all files necessary to bind and link the main program unit
9754 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9755 be done with optimization level 2 and the order of elaboration will be
9756 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9757 displaying commands it is executing.
9758 @end table
9759
9760 @c *************************
9761 @node Improving Performance
9762 @chapter Improving Performance
9763 @cindex Improving performance
9764
9765 @noindent
9766 This chapter presents several topics related to program performance.
9767 It first describes some of the tradeoffs that need to be considered
9768 and some of the techniques for making your program run faster.
9769 It then documents the @command{gnatelim} tool and unused subprogram/data
9770 elimination feature, which can reduce the size of program executables.
9771
9772 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9773 driver (see @ref{The GNAT Driver and Project Files}).
9774
9775 @ifnottex
9776 @menu
9777 * Performance Considerations::
9778 * Text_IO Suggestions::
9779 * Reducing Size of Ada Executables with gnatelim::
9780 * Reducing Size of Executables with unused subprogram/data elimination::
9781 @end menu
9782 @end ifnottex
9783
9784 @c *****************************
9785 @node Performance Considerations
9786 @section Performance Considerations
9787
9788 @noindent
9789 The GNAT system provides a number of options that allow a trade-off
9790 between
9791
9792 @itemize @bullet
9793 @item
9794 performance of the generated code
9795
9796 @item
9797 speed of compilation
9798
9799 @item
9800 minimization of dependences and recompilation
9801
9802 @item
9803 the degree of run-time checking.
9804 @end itemize
9805
9806 @noindent
9807 The defaults (if no options are selected) aim at improving the speed
9808 of compilation and minimizing dependences, at the expense of performance
9809 of the generated code:
9810
9811 @itemize @bullet
9812 @item
9813 no optimization
9814
9815 @item
9816 no inlining of subprogram calls
9817
9818 @item
9819 all run-time checks enabled except overflow and elaboration checks
9820 @end itemize
9821
9822 @noindent
9823 These options are suitable for most program development purposes. This
9824 chapter describes how you can modify these choices, and also provides
9825 some guidelines on debugging optimized code.
9826
9827 @menu
9828 * Controlling Run-Time Checks::
9829 * Use of Restrictions::
9830 * Optimization Levels::
9831 * Debugging Optimized Code::
9832 * Inlining of Subprograms::
9833 * Other Optimization Switches::
9834 * Optimization and Strict Aliasing::
9835
9836 @ifset vms
9837 * Coverage Analysis::
9838 @end ifset
9839 @end menu
9840
9841 @node Controlling Run-Time Checks
9842 @subsection Controlling Run-Time Checks
9843
9844 @noindent
9845 By default, GNAT generates all run-time checks, except integer overflow
9846 checks, stack overflow checks, and checks for access before elaboration on
9847 subprogram calls. The latter are not required in default mode, because all
9848 necessary checking is done at compile time.
9849 @cindex @option{-gnatp} (@command{gcc})
9850 @cindex @option{-gnato} (@command{gcc})
9851 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9852 be modified. @xref{Run-Time Checks}.
9853
9854 Our experience is that the default is suitable for most development
9855 purposes.
9856
9857 We treat integer overflow specially because these
9858 are quite expensive and in our experience are not as important as other
9859 run-time checks in the development process. Note that division by zero
9860 is not considered an overflow check, and divide by zero checks are
9861 generated where required by default.
9862
9863 Elaboration checks are off by default, and also not needed by default, since
9864 GNAT uses a static elaboration analysis approach that avoids the need for
9865 run-time checking. This manual contains a full chapter discussing the issue
9866 of elaboration checks, and if the default is not satisfactory for your use,
9867 you should read this chapter.
9868
9869 For validity checks, the minimal checks required by the Ada Reference
9870 Manual (for case statements and assignments to array elements) are on
9871 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9872 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9873 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9874 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9875 are also suppressed entirely if @option{-gnatp} is used.
9876
9877 @cindex Overflow checks
9878 @cindex Checks, overflow
9879 @findex Suppress
9880 @findex Unsuppress
9881 @cindex pragma Suppress
9882 @cindex pragma Unsuppress
9883 Note that the setting of the switches controls the default setting of
9884 the checks. They may be modified using either @code{pragma Suppress} (to
9885 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9886 checks) in the program source.
9887
9888 @node Use of Restrictions
9889 @subsection Use of Restrictions
9890
9891 @noindent
9892 The use of pragma Restrictions allows you to control which features are
9893 permitted in your program. Apart from the obvious point that if you avoid
9894 relatively expensive features like finalization (enforceable by the use
9895 of pragma Restrictions (No_Finalization), the use of this pragma does not
9896 affect the generated code in most cases.
9897
9898 One notable exception to this rule is that the possibility of task abort
9899 results in some distributed overhead, particularly if finalization or
9900 exception handlers are used. The reason is that certain sections of code
9901 have to be marked as non-abortable.
9902
9903 If you use neither the @code{abort} statement, nor asynchronous transfer
9904 of control (@code{select @dots{} then abort}), then this distributed overhead
9905 is removed, which may have a general positive effect in improving
9906 overall performance.  Especially code involving frequent use of tasking
9907 constructs and controlled types will show much improved performance.
9908 The relevant restrictions pragmas are
9909
9910 @smallexample @c ada
9911    pragma Restrictions (No_Abort_Statements);
9912    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9913 @end smallexample
9914
9915 @noindent
9916 It is recommended that these restriction pragmas be used if possible. Note
9917 that this also means that you can write code without worrying about the
9918 possibility of an immediate abort at any point.
9919
9920 @node Optimization Levels
9921 @subsection Optimization Levels
9922 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9923
9924 @noindent
9925 Without any optimization ^option,^qualifier,^
9926 the compiler's goal is to reduce the cost of
9927 compilation and to make debugging produce the expected results.
9928 Statements are independent: if you stop the program with a breakpoint between
9929 statements, you can then assign a new value to any variable or change
9930 the program counter to any other statement in the subprogram and get exactly
9931 the results you would expect from the source code.
9932
9933 Turning on optimization makes the compiler attempt to improve the
9934 performance and/or code size at the expense of compilation time and
9935 possibly the ability to debug the program.
9936
9937 If you use multiple
9938 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9939 the last such option is the one that is effective.
9940
9941 @noindent
9942 The default is optimization off. This results in the fastest compile
9943 times, but GNAT makes absolutely no attempt to optimize, and the
9944 generated programs are considerably larger and slower than when
9945 optimization is enabled. You can use the
9946 @ifclear vms
9947 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9948 @option{-O2}, @option{-O3}, and @option{-Os})
9949 @end ifclear
9950 @ifset vms
9951 @code{OPTIMIZE} qualifier
9952 @end ifset
9953 to @command{gcc} to control the optimization level:
9954
9955 @table @option
9956 @item ^-O0^/OPTIMIZE=NONE^
9957 No optimization (the default);
9958 generates unoptimized code but has
9959 the fastest compilation time.
9960
9961 Note that many other compilers do fairly extensive optimization
9962 even if ``no optimization'' is specified. With gcc, it is
9963 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9964 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9965 really does mean no optimization at all. This difference between
9966 gcc and other compilers should be kept in mind when doing
9967 performance comparisons.
9968
9969 @item ^-O1^/OPTIMIZE=SOME^
9970 Moderate optimization;
9971 optimizes reasonably well but does not
9972 degrade compilation time significantly.
9973
9974 @item ^-O2^/OPTIMIZE=ALL^
9975 @ifset vms
9976 @itemx /OPTIMIZE=DEVELOPMENT
9977 @end ifset
9978 Full optimization;
9979 generates highly optimized code and has
9980 the slowest compilation time.
9981
9982 @item ^-O3^/OPTIMIZE=INLINING^
9983 Full optimization as in @option{-O2},
9984 and also attempts automatic inlining of small
9985 subprograms within a unit (@pxref{Inlining of Subprograms}).
9986
9987 @item ^-Os^/OPTIMIZE=SPACE^
9988 Optimize space usage of resulting program.
9989 @end table
9990
9991 @noindent
9992 Higher optimization levels perform more global transformations on the
9993 program and apply more expensive analysis algorithms in order to generate
9994 faster and more compact code. The price in compilation time, and the
9995 resulting improvement in execution time,
9996 both depend on the particular application and the hardware environment.
9997 You should experiment to find the best level for your application.
9998
9999 Since the precise set of optimizations done at each level will vary from
10000 release to release (and sometime from target to target), it is best to think
10001 of the optimization settings in general terms.
10002 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10003 the GNU Compiler Collection (GCC)}, for details about
10004 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10005 individually enable or disable specific optimizations.
10006
10007 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10008 been tested extensively at all optimization levels. There are some bugs
10009 which appear only with optimization turned on, but there have also been
10010 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10011 level of optimization does not improve the reliability of the code
10012 generator, which in practice is highly reliable at all optimization
10013 levels.
10014
10015 Note regarding the use of @option{-O3}: The use of this optimization level
10016 is generally discouraged with GNAT, since it often results in larger
10017 executables which run more slowly. See further discussion of this point
10018 in @ref{Inlining of Subprograms}.
10019
10020 @node Debugging Optimized Code
10021 @subsection Debugging Optimized Code
10022 @cindex Debugging optimized code
10023 @cindex Optimization and debugging
10024
10025 @noindent
10026 Although it is possible to do a reasonable amount of debugging at
10027 @ifclear vms
10028 nonzero optimization levels,
10029 the higher the level the more likely that
10030 @end ifclear
10031 @ifset vms
10032 @option{/OPTIMIZE} settings other than @code{NONE},
10033 such settings will make it more likely that
10034 @end ifset
10035 source-level constructs will have been eliminated by optimization.
10036 For example, if a loop is strength-reduced, the loop
10037 control variable may be completely eliminated and thus cannot be
10038 displayed in the debugger.
10039 This can only happen at @option{-O2} or @option{-O3}.
10040 Explicit temporary variables that you code might be eliminated at
10041 ^level^setting^ @option{-O1} or higher.
10042
10043 The use of the @option{^-g^/DEBUG^} switch,
10044 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10045 which is needed for source-level debugging,
10046 affects the size of the program executable on disk,
10047 and indeed the debugging information can be quite large.
10048 However, it has no effect on the generated code (and thus does not
10049 degrade performance)
10050
10051 Since the compiler generates debugging tables for a compilation unit before
10052 it performs optimizations, the optimizing transformations may invalidate some
10053 of the debugging data.  You therefore need to anticipate certain
10054 anomalous situations that may arise while debugging optimized code.
10055 These are the most common cases:
10056
10057 @enumerate
10058 @item
10059 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10060 commands show
10061 the PC bouncing back and forth in the code.  This may result from any of
10062 the following optimizations:
10063
10064 @itemize @bullet
10065 @item
10066 @i{Common subexpression elimination:} using a single instance of code for a
10067 quantity that the source computes several times.  As a result you
10068 may not be able to stop on what looks like a statement.
10069
10070 @item
10071 @i{Invariant code motion:} moving an expression that does not change within a
10072 loop, to the beginning of the loop.
10073
10074 @item
10075 @i{Instruction scheduling:} moving instructions so as to
10076 overlap loads and stores (typically) with other code, or in
10077 general to move computations of values closer to their uses. Often
10078 this causes you to pass an assignment statement without the assignment
10079 happening and then later bounce back to the statement when the
10080 value is actually needed.  Placing a breakpoint on a line of code
10081 and then stepping over it may, therefore, not always cause all the
10082 expected side-effects.
10083 @end itemize
10084
10085 @item
10086 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10087 two identical pieces of code are merged and the program counter suddenly
10088 jumps to a statement that is not supposed to be executed, simply because
10089 it (and the code following) translates to the same thing as the code
10090 that @emph{was} supposed to be executed.  This effect is typically seen in
10091 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10092 a @code{break} in a C @code{^switch^switch^} statement.
10093
10094 @item
10095 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10096 There are various reasons for this effect:
10097
10098 @itemize @bullet
10099 @item
10100 In a subprogram prologue, a parameter may not yet have been moved to its
10101 ``home''.
10102
10103 @item
10104 A variable may be dead, and its register re-used.  This is
10105 probably the most common cause.
10106
10107 @item
10108 As mentioned above, the assignment of a value to a variable may
10109 have been moved.
10110
10111 @item
10112 A variable may be eliminated entirely by value propagation or
10113 other means.  In this case, GCC may incorrectly generate debugging
10114 information for the variable
10115 @end itemize
10116
10117 @noindent
10118 In general, when an unexpected value appears for a local variable or parameter
10119 you should first ascertain if that value was actually computed by
10120 your program, as opposed to being incorrectly reported by the debugger.
10121 Record fields or
10122 array elements in an object designated by an access value
10123 are generally less of a problem, once you have ascertained that the access
10124 value is sensible.
10125 Typically, this means checking variables in the preceding code and in the
10126 calling subprogram to verify that the value observed is explainable from other
10127 values (one must apply the procedure recursively to those
10128 other values); or re-running the code and stopping a little earlier
10129 (perhaps before the call) and stepping to better see how the variable obtained
10130 the value in question; or continuing to step @emph{from} the point of the
10131 strange value to see if code motion had simply moved the variable's
10132 assignments later.
10133 @end enumerate
10134
10135 @noindent
10136 In light of such anomalies, a recommended technique is to use @option{-O0}
10137 early in the software development cycle, when extensive debugging capabilities
10138 are most needed, and then move to @option{-O1} and later @option{-O2} as
10139 the debugger becomes less critical.
10140 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10141 a release management issue.
10142 @ifclear vms
10143 Note that if you use @option{-g} you can then use the @command{strip} program
10144 on the resulting executable,
10145 which removes both debugging information and global symbols.
10146 @end ifclear
10147
10148 @node Inlining of Subprograms
10149 @subsection Inlining of Subprograms
10150
10151 @noindent
10152 A call to a subprogram in the current unit is inlined if all the
10153 following conditions are met:
10154
10155 @itemize @bullet
10156 @item
10157 The optimization level is at least @option{-O1}.
10158
10159 @item
10160 The called subprogram is suitable for inlining: It must be small enough
10161 and not contain something that @command{gcc} cannot support in inlined
10162 subprograms.
10163
10164 @item
10165 @cindex pragma Inline
10166 @findex Inline
10167 Either @code{pragma Inline} applies to the subprogram, or it is local
10168 to the unit and called once from within it, or it is small and automatic
10169 inlining (optimization level @option{-O3}) is specified.
10170 @end itemize
10171
10172 @noindent
10173 Calls to subprograms in @code{with}'ed units are normally not inlined.
10174 To achieve actual inlining (that is, replacement of the call by the code
10175 in the body of the subprogram), the following conditions must all be true.
10176
10177 @itemize @bullet
10178 @item
10179 The optimization level is at least @option{-O1}.
10180
10181 @item
10182 The called subprogram is suitable for inlining: It must be small enough
10183 and not contain something that @command{gcc} cannot support in inlined
10184 subprograms.
10185
10186 @item
10187 The call appears in a body (not in a package spec).
10188
10189 @item
10190 There is a @code{pragma Inline} for the subprogram.
10191
10192 @item
10193 @cindex @option{-gnatn} (@command{gcc})
10194 The @option{^-gnatn^/INLINE^} switch
10195 is used in the @command{gcc} command line
10196 @end itemize
10197
10198 Even if all these conditions are met, it may not be possible for
10199 the compiler to inline the call, due to the length of the body,
10200 or features in the body that make it impossible for the compiler
10201 to do the inlining.
10202
10203 Note that specifying the @option{-gnatn} switch causes additional
10204 compilation dependencies. Consider the following:
10205
10206 @smallexample @c ada
10207 @cartouche
10208 package R is
10209    procedure Q;
10210    pragma Inline (Q);
10211 end R;
10212 package body R is
10213    @dots{}
10214 end R;
10215
10216 with R;
10217 procedure Main is
10218 begin
10219    @dots{}
10220    R.Q;
10221 end Main;
10222 @end cartouche
10223 @end smallexample
10224
10225 @noindent
10226 With the default behavior (no @option{-gnatn} switch specified), the
10227 compilation of the @code{Main} procedure depends only on its own source,
10228 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10229 means that editing the body of @code{R} does not require recompiling
10230 @code{Main}.
10231
10232 On the other hand, the call @code{R.Q} is not inlined under these
10233 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10234 is compiled, the call will be inlined if the body of @code{Q} is small
10235 enough, but now @code{Main} depends on the body of @code{R} in
10236 @file{r.adb} as well as on the spec. This means that if this body is edited,
10237 the main program must be recompiled. Note that this extra dependency
10238 occurs whether or not the call is in fact inlined by @command{gcc}.
10239
10240 The use of front end inlining with @option{-gnatN} generates similar
10241 additional dependencies.
10242
10243 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10244 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10245 can be used to prevent
10246 all inlining. This switch overrides all other conditions and ensures
10247 that no inlining occurs. The extra dependences resulting from
10248 @option{-gnatn} will still be active, even if
10249 this switch is used to suppress the resulting inlining actions.
10250
10251 @cindex @option{-fno-inline-functions} (@command{gcc})
10252 Note: The @option{-fno-inline-functions} switch can be used to prevent
10253 automatic inlining of small subprograms if @option{-O3} is used.
10254
10255 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10256 Note: The @option{-fno-inline-functions-called-once} switch
10257 can be used to prevent inlining of subprograms local to the unit
10258 and called once from within it if @option{-O1} is used.
10259
10260 Note regarding the use of @option{-O3}: There is no difference in inlining
10261 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10262 pragma @code{Inline} assuming the use of @option{-gnatn}
10263 or @option{-gnatN} (the switches that activate inlining). If you have used
10264 pragma @code{Inline} in appropriate cases, then it is usually much better
10265 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10266 in this case only has the effect of inlining subprograms you did not
10267 think should be inlined. We often find that the use of @option{-O3} slows
10268 down code by performing excessive inlining, leading to increased instruction
10269 cache pressure from the increased code size. So the bottom line here is
10270 that you should not automatically assume that @option{-O3} is better than
10271 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10272 it actually improves performance.
10273
10274 @node Other Optimization Switches
10275 @subsection Other Optimization Switches
10276 @cindex Optimization Switches
10277
10278 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10279 @command{gcc} optimization switches are potentially usable. These switches
10280 have not been extensively tested with GNAT but can generally be expected
10281 to work. Examples of switches in this category are
10282 @option{-funroll-loops} and
10283 the various target-specific @option{-m} options (in particular, it has been
10284 observed that @option{-march=pentium4} can significantly improve performance
10285 on appropriate machines). For full details of these switches, see
10286 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10287 the GNU Compiler Collection (GCC)}.
10288
10289 @node Optimization and Strict Aliasing
10290 @subsection Optimization and Strict Aliasing
10291 @cindex Aliasing
10292 @cindex Strict Aliasing
10293 @cindex No_Strict_Aliasing
10294
10295 @noindent
10296 The strong typing capabilities of Ada allow an optimizer to generate
10297 efficient code in situations where other languages would be forced to
10298 make worst case assumptions preventing such optimizations. Consider
10299 the following example:
10300
10301 @smallexample @c ada
10302 @cartouche
10303 procedure R is
10304    type Int1 is new Integer;
10305    type Int2 is new Integer;
10306    type Int1A is access Int1;
10307    type Int2A is access Int2;
10308    Int1V : Int1A;
10309    Int2V : Int2A;
10310    @dots{}
10311
10312 begin
10313    @dots{}
10314    for J in Data'Range loop
10315       if Data (J) = Int1V.all then
10316          Int2V.all := Int2V.all + 1;
10317       end if;
10318    end loop;
10319    @dots{}
10320 end R;
10321 @end cartouche
10322 @end smallexample
10323
10324 @noindent
10325 In this example, since the variable @code{Int1V} can only access objects
10326 of type @code{Int1}, and @code{Int2V} can only access objects of type
10327 @code{Int2}, there is no possibility that the assignment to
10328 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10329 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10330 for all iterations of the loop and avoid the extra memory reference
10331 required to dereference it each time through the loop.
10332
10333 This kind of optimization, called strict aliasing analysis, is
10334 triggered by specifying an optimization level of @option{-O2} or
10335 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10336 when access values are involved.
10337
10338 However, although this optimization is always correct in terms of
10339 the formal semantics of the Ada Reference Manual, difficulties can
10340 arise if features like @code{Unchecked_Conversion} are used to break
10341 the typing system. Consider the following complete program example:
10342
10343 @smallexample @c ada
10344 @cartouche
10345 package p1 is
10346    type int1 is new integer;
10347    type int2 is new integer;
10348    type a1 is access int1;
10349    type a2 is access int2;
10350 end p1;
10351
10352 with p1; use p1;
10353 package p2 is
10354    function to_a2 (Input : a1) return a2;
10355 end p2;
10356
10357 with Unchecked_Conversion;
10358 package body p2 is
10359    function to_a2 (Input : a1) return a2 is
10360       function to_a2u is
10361         new Unchecked_Conversion (a1, a2);
10362    begin
10363       return to_a2u (Input);
10364    end to_a2;
10365 end p2;
10366
10367 with p2; use p2;
10368 with p1; use p1;
10369 with Text_IO; use Text_IO;
10370 procedure m is
10371    v1 : a1 := new int1;
10372    v2 : a2 := to_a2 (v1);
10373 begin
10374    v1.all := 1;
10375    v2.all := 0;
10376    put_line (int1'image (v1.all));
10377 end;
10378 @end cartouche
10379 @end smallexample
10380
10381 @noindent
10382 This program prints out 0 in @option{-O0} or @option{-O1}
10383 mode, but it prints out 1 in @option{-O2} mode. That's
10384 because in strict aliasing mode, the compiler can and
10385 does assume that the assignment to @code{v2.all} could not
10386 affect the value of @code{v1.all}, since different types
10387 are involved.
10388
10389 This behavior is not a case of non-conformance with the standard, since
10390 the Ada RM specifies that an unchecked conversion where the resulting
10391 bit pattern is not a correct value of the target type can result in an
10392 abnormal value and attempting to reference an abnormal value makes the
10393 execution of a program erroneous.  That's the case here since the result
10394 does not point to an object of type @code{int2}.  This means that the
10395 effect is entirely unpredictable.
10396
10397 However, although that explanation may satisfy a language
10398 lawyer, in practice an applications programmer expects an
10399 unchecked conversion involving pointers to create true
10400 aliases and the behavior of printing 1 seems plain wrong.
10401 In this case, the strict aliasing optimization is unwelcome.
10402
10403 Indeed the compiler recognizes this possibility, and the
10404 unchecked conversion generates a warning:
10405
10406 @smallexample
10407 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10408 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10409 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10410 @end smallexample
10411
10412 @noindent
10413 Unfortunately the problem is recognized when compiling the body of
10414 package @code{p2}, but the actual "bad" code is generated while
10415 compiling the body of @code{m} and this latter compilation does not see
10416 the suspicious @code{Unchecked_Conversion}.
10417
10418 As implied by the warning message, there are approaches you can use to
10419 avoid the unwanted strict aliasing optimization in a case like this.
10420
10421 One possibility is to simply avoid the use of @option{-O2}, but
10422 that is a bit drastic, since it throws away a number of useful
10423 optimizations that do not involve strict aliasing assumptions.
10424
10425 A less drastic approach is to compile the program using the
10426 option @option{-fno-strict-aliasing}. Actually it is only the
10427 unit containing the dereferencing of the suspicious pointer
10428 that needs to be compiled. So in this case, if we compile
10429 unit @code{m} with this switch, then we get the expected
10430 value of zero printed. Analyzing which units might need
10431 the switch can be painful, so a more reasonable approach
10432 is to compile the entire program with options @option{-O2}
10433 and @option{-fno-strict-aliasing}. If the performance is
10434 satisfactory with this combination of options, then the
10435 advantage is that the entire issue of possible "wrong"
10436 optimization due to strict aliasing is avoided.
10437
10438 To avoid the use of compiler switches, the configuration
10439 pragma @code{No_Strict_Aliasing} with no parameters may be
10440 used to specify that for all access types, the strict
10441 aliasing optimization should be suppressed.
10442
10443 However, these approaches are still overkill, in that they causes
10444 all manipulations of all access values to be deoptimized. A more
10445 refined approach is to concentrate attention on the specific
10446 access type identified as problematic.
10447
10448 First, if a careful analysis of uses of the pointer shows
10449 that there are no possible problematic references, then
10450 the warning can be suppressed by bracketing the
10451 instantiation of @code{Unchecked_Conversion} to turn
10452 the warning off:
10453
10454 @smallexample @c ada
10455    pragma Warnings (Off);
10456    function to_a2u is
10457      new Unchecked_Conversion (a1, a2);
10458    pragma Warnings (On);
10459 @end smallexample
10460
10461 @noindent
10462 Of course that approach is not appropriate for this particular
10463 example, since indeed there is a problematic reference. In this
10464 case we can take one of two other approaches.
10465
10466 The first possibility is to move the instantiation of unchecked
10467 conversion to the unit in which the type is declared. In
10468 this example, we would move the instantiation of
10469 @code{Unchecked_Conversion} from the body of package
10470 @code{p2} to the spec of package @code{p1}. Now the
10471 warning disappears. That's because any use of the
10472 access type knows there is a suspicious unchecked
10473 conversion, and the strict aliasing optimization
10474 is automatically suppressed for the type.
10475
10476 If it is not practical to move the unchecked conversion to the same unit
10477 in which the destination access type is declared (perhaps because the
10478 source type is not visible in that unit), you may use pragma
10479 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10480 same declarative sequence as the declaration of the access type:
10481
10482 @smallexample @c ada
10483    type a2 is access int2;
10484    pragma No_Strict_Aliasing (a2);
10485 @end smallexample
10486
10487 @noindent
10488 Here again, the compiler now knows that the strict aliasing optimization
10489 should be suppressed for any reference to type @code{a2} and the
10490 expected behavior is obtained.
10491
10492 Finally, note that although the compiler can generate warnings for
10493 simple cases of unchecked conversions, there are tricker and more
10494 indirect ways of creating type incorrect aliases which the compiler
10495 cannot detect. Examples are the use of address overlays and unchecked
10496 conversions involving composite types containing access types as
10497 components. In such cases, no warnings are generated, but there can
10498 still be aliasing problems. One safe coding practice is to forbid the
10499 use of address clauses for type overlaying, and to allow unchecked
10500 conversion only for primitive types. This is not really a significant
10501 restriction since any possible desired effect can be achieved by
10502 unchecked conversion of access values.
10503
10504 The aliasing analysis done in strict aliasing mode can certainly
10505 have significant benefits. We have seen cases of large scale
10506 application code where the time is increased by up to 5% by turning
10507 this optimization off. If you have code that includes significant
10508 usage of unchecked conversion, you might want to just stick with
10509 @option{-O1} and avoid the entire issue. If you get adequate
10510 performance at this level of optimization level, that's probably
10511 the safest approach. If tests show that you really need higher
10512 levels of optimization, then you can experiment with @option{-O2}
10513 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10514 has on size and speed of the code. If you really need to use
10515 @option{-O2} with strict aliasing in effect, then you should
10516 review any uses of unchecked conversion of access types,
10517 particularly if you are getting the warnings described above.
10518
10519 @ifset vms
10520 @node Coverage Analysis
10521 @subsection Coverage Analysis
10522
10523 @noindent
10524 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10525 the user to determine the distribution of execution time across a program,
10526 @pxref{Profiling} for details of usage.
10527 @end ifset
10528
10529
10530 @node Text_IO Suggestions
10531 @section @code{Text_IO} Suggestions
10532 @cindex @code{Text_IO} and performance
10533
10534 @noindent
10535 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10536 the requirement of maintaining page and line counts. If performance
10537 is critical, a recommendation is to use @code{Stream_IO} instead of
10538 @code{Text_IO} for volume output, since this package has less overhead.
10539
10540 If @code{Text_IO} must be used, note that by default output to the standard
10541 output and standard error files is unbuffered (this provides better
10542 behavior when output statements are used for debugging, or if the
10543 progress of a program is observed by tracking the output, e.g. by
10544 using the Unix @command{tail -f} command to watch redirected output.
10545
10546 If you are generating large volumes of output with @code{Text_IO} and
10547 performance is an important factor, use a designated file instead
10548 of the standard output file, or change the standard output file to
10549 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10550
10551
10552
10553 @node Reducing Size of Ada Executables with gnatelim
10554 @section Reducing Size of Ada Executables with @code{gnatelim}
10555 @findex gnatelim
10556
10557 @noindent
10558 This section describes @command{gnatelim}, a tool which detects unused
10559 subprograms and helps the compiler to create a smaller executable for your
10560 program.
10561
10562 @menu
10563 * About gnatelim::
10564 * Running gnatelim::
10565 * Correcting the List of Eliminate Pragmas::
10566 * Making Your Executables Smaller::
10567 * Summary of the gnatelim Usage Cycle::
10568 @end menu
10569
10570 @node About gnatelim
10571 @subsection About @code{gnatelim}
10572
10573 @noindent
10574 When a program shares a set of Ada
10575 packages with other programs, it may happen that this program uses
10576 only a fraction of the subprograms defined in these packages. The code
10577 created for these unused subprograms increases the size of the executable.
10578
10579 @code{gnatelim} tracks unused subprograms in an Ada program and
10580 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10581 subprograms that are declared but never called. By placing the list of
10582 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10583 recompiling your program, you may decrease the size of its executable,
10584 because the compiler will not generate the code for 'eliminated' subprograms.
10585 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10586 information about this pragma.
10587
10588 @code{gnatelim} needs as its input data the name of the main subprogram
10589 and a bind file for a main subprogram.
10590
10591 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10592 the main subprogram. @code{gnatelim} can work with both Ada and C
10593 bind files; when both are present, it uses the Ada bind file.
10594 The following commands will build the program and create the bind file:
10595
10596 @smallexample
10597 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10598 $ gnatbind main_prog
10599 @end smallexample
10600
10601 Note that @code{gnatelim} needs neither object nor ALI files.
10602
10603 @node Running gnatelim
10604 @subsection Running @code{gnatelim}
10605
10606 @noindent
10607 @code{gnatelim} has the following command-line interface:
10608
10609 @smallexample
10610 $ gnatelim @ovar{options} name
10611 @end smallexample
10612
10613 @noindent
10614 @code{name} should be a name of a source file that contains the main subprogram
10615 of a program (partition).
10616
10617 @code{gnatelim} has the following switches:
10618
10619 @table @option
10620 @c !sort!
10621 @item ^-q^/QUIET^
10622 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10623 Quiet mode: by default @code{gnatelim} outputs to the standard error
10624 stream the number of program units left to be processed. This option turns
10625 this trace off.
10626
10627 @item ^-v^/VERBOSE^
10628 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10629 Verbose mode: @code{gnatelim} version information is printed as Ada
10630 comments to the standard output stream. Also, in addition to the number of
10631 program units left @code{gnatelim} will output the name of the current unit
10632 being processed.
10633
10634 @item ^-a^/ALL^
10635 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10636 Also look for subprograms from the GNAT run time that can be eliminated. Note
10637 that when @file{gnat.adc} is produced using this switch, the entire program
10638 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10639
10640 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10641 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10642 When looking for source files also look in directory @var{dir}. Specifying
10643 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10644 sources in the current directory.
10645
10646 @item ^-b^/BIND_FILE=^@var{bind_file}
10647 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10648 Specifies @var{bind_file} as the bind file to process. If not set, the name
10649 of the bind file is computed from the full expanded Ada name
10650 of a main subprogram.
10651
10652 @item ^-C^/CONFIG_FILE=^@var{config_file}
10653 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10654 Specifies a file @var{config_file} that contains configuration pragmas. The
10655 file must be specified with full path.
10656
10657 @item ^--GCC^/COMPILER^=@var{compiler_name}
10658 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10659 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10660 available on the path.
10661
10662 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10663 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10664 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10665 available on the path.
10666 @end table
10667
10668 @noindent
10669 @code{gnatelim} sends its output to the standard output stream, and all the
10670 tracing and debug information is sent to the standard error stream.
10671 In order to produce a proper GNAT configuration file
10672 @file{gnat.adc}, redirection must be used:
10673
10674 @smallexample
10675 @ifset vms
10676 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10677 @end ifset
10678 @ifclear vms
10679 $ gnatelim main_prog.adb > gnat.adc
10680 @end ifclear
10681 @end smallexample
10682
10683 @ifclear vms
10684 @noindent
10685 or
10686
10687 @smallexample
10688 $ gnatelim main_prog.adb >> gnat.adc
10689 @end smallexample
10690
10691 @noindent
10692 in order to append the @code{gnatelim} output to the existing contents of
10693 @file{gnat.adc}.
10694 @end ifclear
10695
10696 @node Correcting the List of Eliminate Pragmas
10697 @subsection Correcting the List of Eliminate Pragmas
10698
10699 @noindent
10700 In some rare cases @code{gnatelim} may try to eliminate
10701 subprograms that are actually called in the program. In this case, the
10702 compiler will generate an error message of the form:
10703
10704 @smallexample
10705 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10706 @end smallexample
10707
10708 @noindent
10709 You will need to manually remove the wrong @code{Eliminate} pragmas from
10710 the @file{gnat.adc} file. You should recompile your program
10711 from scratch after that, because you need a consistent @file{gnat.adc} file
10712 during the entire compilation.
10713
10714 @node Making Your Executables Smaller
10715 @subsection Making Your Executables Smaller
10716
10717 @noindent
10718 In order to get a smaller executable for your program you now have to
10719 recompile the program completely with the new @file{gnat.adc} file
10720 created by @code{gnatelim} in your current directory:
10721
10722 @smallexample
10723 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10724 @end smallexample
10725
10726 @noindent
10727 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10728 recompile everything
10729 with the set of pragmas @code{Eliminate} that you have obtained with
10730 @command{gnatelim}).
10731
10732 Be aware that the set of @code{Eliminate} pragmas is specific to each
10733 program. It is not recommended to merge sets of @code{Eliminate}
10734 pragmas created for different programs in one @file{gnat.adc} file.
10735
10736 @node Summary of the gnatelim Usage Cycle
10737 @subsection Summary of the gnatelim Usage Cycle
10738
10739 @noindent
10740 Here is a quick summary of the steps to be taken in order to reduce
10741 the size of your executables with @code{gnatelim}. You may use
10742 other GNAT options to control the optimization level,
10743 to produce the debugging information, to set search path, etc.
10744
10745 @enumerate
10746 @item
10747 Produce a bind file
10748
10749 @smallexample
10750 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10751 $ gnatbind main_prog
10752 @end smallexample
10753
10754 @item
10755 Generate a list of @code{Eliminate} pragmas
10756 @smallexample
10757 @ifset vms
10758 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10759 @end ifset
10760 @ifclear vms
10761 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10762 @end ifclear
10763 @end smallexample
10764
10765 @item
10766 Recompile the application
10767
10768 @smallexample
10769 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10770 @end smallexample
10771
10772 @end enumerate
10773
10774 @node Reducing Size of Executables with unused subprogram/data elimination
10775 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10776 @findex unused subprogram/data elimination
10777
10778 @noindent
10779 This section describes how you can eliminate unused subprograms and data from
10780 your executable just by setting options at compilation time.
10781
10782 @menu
10783 * About unused subprogram/data elimination::
10784 * Compilation options::
10785 * Example of unused subprogram/data elimination::
10786 @end menu
10787
10788 @node About unused subprogram/data elimination
10789 @subsection About unused subprogram/data elimination
10790
10791 @noindent
10792 By default, an executable contains all code and data of its composing objects
10793 (directly linked or coming from statically linked libraries), even data or code
10794 never used by this executable.
10795
10796 This feature will allow you to eliminate such unused code from your
10797 executable, making it smaller (in disk and in memory).
10798
10799 This functionality is available on all Linux platforms except for the IA-64
10800 architecture and on all cross platforms using the ELF binary file format.
10801 In both cases GNU binutils version 2.16 or later are required to enable it.
10802
10803 @node Compilation options
10804 @subsection Compilation options
10805
10806 @noindent
10807 The operation of eliminating the unused code and data from the final executable
10808 is directly performed by the linker.
10809
10810 In order to do this, it has to work with objects compiled with the
10811 following options:
10812 @option{-ffunction-sections} @option{-fdata-sections}.
10813 @cindex @option{-ffunction-sections} (@command{gcc})
10814 @cindex @option{-fdata-sections} (@command{gcc})
10815 These options are usable with C and Ada files.
10816 They will place respectively each
10817 function or data in a separate section in the resulting object file.
10818
10819 Once the objects and static libraries are created with these options, the
10820 linker can perform the dead code elimination. You can do this by setting
10821 the @option{-Wl,--gc-sections} option to gcc command or in the
10822 @option{-largs} section of @command{gnatmake}. This will perform a
10823 garbage collection of code and data never referenced.
10824
10825 If the linker performs a partial link (@option{-r} ld linker option), then you
10826 will need to provide one or several entry point using the
10827 @option{-e} / @option{--entry} ld option.
10828
10829 Note that objects compiled without the @option{-ffunction-sections} and
10830 @option{-fdata-sections} options can still be linked with the executable.
10831 However, no dead code elimination will be performed on those objects (they will
10832 be linked as is).
10833
10834 The GNAT static library is now compiled with -ffunction-sections and
10835 -fdata-sections on some platforms. This allows you to eliminate the unused code
10836 and data of the GNAT library from your executable.
10837
10838 @node Example of unused subprogram/data elimination
10839 @subsection Example of unused subprogram/data elimination
10840
10841 @noindent
10842 Here is a simple example:
10843
10844 @smallexample @c ada
10845 with Aux;
10846
10847 procedure Test is
10848 begin
10849    Aux.Used (10);
10850 end Test;
10851
10852 package Aux is
10853    Used_Data   : Integer;
10854    Unused_Data : Integer;
10855
10856    procedure Used   (Data : Integer);
10857    procedure Unused (Data : Integer);
10858 end Aux;
10859
10860 package body Aux is
10861    procedure Used (Data : Integer) is
10862    begin
10863       Used_Data := Data;
10864    end Used;
10865
10866    procedure Unused (Data : Integer) is
10867    begin
10868       Unused_Data := Data;
10869    end Unused;
10870 end Aux;
10871 @end smallexample
10872
10873 @noindent
10874 @code{Unused} and @code{Unused_Data} are never referenced in this code
10875 excerpt, and hence they may be safely removed from the final executable.
10876
10877 @smallexample
10878 $ gnatmake test
10879
10880 $ nm test | grep used
10881 020015f0 T aux__unused
10882 02005d88 B aux__unused_data
10883 020015cc T aux__used
10884 02005d84 B aux__used_data
10885
10886 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10887      -largs -Wl,--gc-sections
10888
10889 $ nm test | grep used
10890 02005350 T aux__used
10891 0201ffe0 B aux__used_data
10892 @end smallexample
10893
10894 @noindent
10895 It can be observed that the procedure @code{Unused} and the object
10896 @code{Unused_Data} are removed by the linker when using the
10897 appropriate options.
10898
10899 @c ********************************
10900 @node Renaming Files Using gnatchop
10901 @chapter Renaming Files Using @code{gnatchop}
10902 @findex gnatchop
10903
10904 @noindent
10905 This chapter discusses how to handle files with multiple units by using
10906 the @code{gnatchop} utility. This utility is also useful in renaming
10907 files to meet the standard GNAT default file naming conventions.
10908
10909 @menu
10910 * Handling Files with Multiple Units::
10911 * Operating gnatchop in Compilation Mode::
10912 * Command Line for gnatchop::
10913 * Switches for gnatchop::
10914 * Examples of gnatchop Usage::
10915 @end menu
10916
10917 @node Handling Files with Multiple Units
10918 @section Handling Files with Multiple Units
10919
10920 @noindent
10921 The basic compilation model of GNAT requires that a file submitted to the
10922 compiler have only one unit and there be a strict correspondence
10923 between the file name and the unit name.
10924
10925 The @code{gnatchop} utility allows both of these rules to be relaxed,
10926 allowing GNAT to process files which contain multiple compilation units
10927 and files with arbitrary file names. @code{gnatchop}
10928 reads the specified file and generates one or more output files,
10929 containing one unit per file. The unit and the file name correspond,
10930 as required by GNAT.
10931
10932 If you want to permanently restructure a set of ``foreign'' files so that
10933 they match the GNAT rules, and do the remaining development using the
10934 GNAT structure, you can simply use @command{gnatchop} once, generate the
10935 new set of files and work with them from that point on.
10936
10937 Alternatively, if you want to keep your files in the ``foreign'' format,
10938 perhaps to maintain compatibility with some other Ada compilation
10939 system, you can set up a procedure where you use @command{gnatchop} each
10940 time you compile, regarding the source files that it writes as temporary
10941 files that you throw away.
10942
10943 Note that if your file containing multiple units starts with a byte order
10944 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
10945 will each start with a copy of this BOM, meaning that they can be compiled
10946 automatically in UTF-8 mode without needing to specify an explicit encoding.
10947
10948 @node Operating gnatchop in Compilation Mode
10949 @section Operating gnatchop in Compilation Mode
10950
10951 @noindent
10952 The basic function of @code{gnatchop} is to take a file with multiple units
10953 and split it into separate files. The boundary between files is reasonably
10954 clear, except for the issue of comments and pragmas. In default mode, the
10955 rule is that any pragmas between units belong to the previous unit, except
10956 that configuration pragmas always belong to the following unit. Any comments
10957 belong to the following unit. These rules
10958 almost always result in the right choice of
10959 the split point without needing to mark it explicitly and most users will
10960 find this default to be what they want. In this default mode it is incorrect to
10961 submit a file containing only configuration pragmas, or one that ends in
10962 configuration pragmas, to @code{gnatchop}.
10963
10964 However, using a special option to activate ``compilation mode'',
10965 @code{gnatchop}
10966 can perform another function, which is to provide exactly the semantics
10967 required by the RM for handling of configuration pragmas in a compilation.
10968 In the absence of configuration pragmas (at the main file level), this
10969 option has no effect, but it causes such configuration pragmas to be handled
10970 in a quite different manner.
10971
10972 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10973 only configuration pragmas, then this file is appended to the
10974 @file{gnat.adc} file in the current directory. This behavior provides
10975 the required behavior described in the RM for the actions to be taken
10976 on submitting such a file to the compiler, namely that these pragmas
10977 should apply to all subsequent compilations in the same compilation
10978 environment. Using GNAT, the current directory, possibly containing a
10979 @file{gnat.adc} file is the representation
10980 of a compilation environment. For more information on the
10981 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10982
10983 Second, in compilation mode, if @code{gnatchop}
10984 is given a file that starts with
10985 configuration pragmas, and contains one or more units, then these
10986 configuration pragmas are prepended to each of the chopped files. This
10987 behavior provides the required behavior described in the RM for the
10988 actions to be taken on compiling such a file, namely that the pragmas
10989 apply to all units in the compilation, but not to subsequently compiled
10990 units.
10991
10992 Finally, if configuration pragmas appear between units, they are appended
10993 to the previous unit. This results in the previous unit being illegal,
10994 since the compiler does not accept configuration pragmas that follow
10995 a unit. This provides the required RM behavior that forbids configuration
10996 pragmas other than those preceding the first compilation unit of a
10997 compilation.
10998
10999 For most purposes, @code{gnatchop} will be used in default mode. The
11000 compilation mode described above is used only if you need exactly
11001 accurate behavior with respect to compilations, and you have files
11002 that contain multiple units and configuration pragmas. In this
11003 circumstance the use of @code{gnatchop} with the compilation mode
11004 switch provides the required behavior, and is for example the mode
11005 in which GNAT processes the ACVC tests.
11006
11007 @node Command Line for gnatchop
11008 @section Command Line for @code{gnatchop}
11009
11010 @noindent
11011 The @code{gnatchop} command has the form:
11012
11013 @smallexample
11014 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11015       @ovar{directory}
11016 @end smallexample
11017
11018 @noindent
11019 The only required argument is the file name of the file to be chopped.
11020 There are no restrictions on the form of this file name. The file itself
11021 contains one or more Ada units, in normal GNAT format, concatenated
11022 together. As shown, more than one file may be presented to be chopped.
11023
11024 When run in default mode, @code{gnatchop} generates one output file in
11025 the current directory for each unit in each of the files.
11026
11027 @var{directory}, if specified, gives the name of the directory to which
11028 the output files will be written. If it is not specified, all files are
11029 written to the current directory.
11030
11031 For example, given a
11032 file called @file{hellofiles} containing
11033
11034 @smallexample @c ada
11035 @group
11036 @cartouche
11037 procedure hello;
11038
11039 with Text_IO; use Text_IO;
11040 procedure hello is
11041 begin
11042    Put_Line ("Hello");
11043 end hello;
11044 @end cartouche
11045 @end group
11046 @end smallexample
11047
11048 @noindent
11049 the command
11050
11051 @smallexample
11052 $ gnatchop ^hellofiles^HELLOFILES.^
11053 @end smallexample
11054
11055 @noindent
11056 generates two files in the current directory, one called
11057 @file{hello.ads} containing the single line that is the procedure spec,
11058 and the other called @file{hello.adb} containing the remaining text. The
11059 original file is not affected. The generated files can be compiled in
11060 the normal manner.
11061
11062 @noindent
11063 When gnatchop is invoked on a file that is empty or that contains only empty
11064 lines and/or comments, gnatchop will not fail, but will not produce any
11065 new sources.
11066
11067 For example, given a
11068 file called @file{toto.txt} containing
11069
11070 @smallexample @c ada
11071 @group
11072 @cartouche
11073 --  Just a comment
11074 @end cartouche
11075 @end group
11076 @end smallexample
11077
11078 @noindent
11079 the command
11080
11081 @smallexample
11082 $ gnatchop ^toto.txt^TOT.TXT^
11083 @end smallexample
11084
11085 @noindent
11086 will not produce any new file and will result in the following warnings:
11087
11088 @smallexample
11089 toto.txt:1:01: warning: empty file, contains no compilation units
11090 no compilation units found
11091 no source files written
11092 @end smallexample
11093
11094 @node Switches for gnatchop
11095 @section Switches for @code{gnatchop}
11096
11097 @noindent
11098 @command{gnatchop} recognizes the following switches:
11099
11100 @table @option
11101 @c !sort!
11102
11103 @item --version
11104 @cindex @option{--version} @command{gnatchop}
11105 Display Copyright and version, then exit disregarding all other options.
11106
11107 @item --help
11108 @cindex @option{--help} @command{gnatchop}
11109 If @option{--version} was not used, display usage, then exit disregarding
11110 all other options.
11111
11112 @item ^-c^/COMPILATION^
11113 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11114 Causes @code{gnatchop} to operate in compilation mode, in which
11115 configuration pragmas are handled according to strict RM rules. See
11116 previous section for a full description of this mode.
11117
11118 @ifclear vms
11119 @item -gnat@var{xxx}
11120 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11121 used to parse the given file. Not all @var{xxx} options make sense,
11122 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11123 process a source file that uses Latin-2 coding for identifiers.
11124 @end ifclear
11125
11126 @item ^-h^/HELP^
11127 Causes @code{gnatchop} to generate a brief help summary to the standard
11128 output file showing usage information.
11129
11130 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11131 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11132 Limit generated file names to the specified number @code{mm}
11133 of characters.
11134 This is useful if the
11135 resulting set of files is required to be interoperable with systems
11136 which limit the length of file names.
11137 @ifset vms
11138 If no value is given, or
11139 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11140 a default of 39, suitable for OpenVMS Alpha
11141 Systems, is assumed
11142 @end ifset
11143 @ifclear vms
11144 No space is allowed between the @option{-k} and the numeric value. The numeric
11145 value may be omitted in which case a default of @option{-k8},
11146 suitable for use
11147 with DOS-like file systems, is used. If no @option{-k} switch
11148 is present then
11149 there is no limit on the length of file names.
11150 @end ifclear
11151
11152 @item ^-p^/PRESERVE^
11153 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11154 Causes the file ^modification^creation^ time stamp of the input file to be
11155 preserved and used for the time stamp of the output file(s). This may be
11156 useful for preserving coherency of time stamps in an environment where
11157 @code{gnatchop} is used as part of a standard build process.
11158
11159 @item ^-q^/QUIET^
11160 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11161 Causes output of informational messages indicating the set of generated
11162 files to be suppressed. Warnings and error messages are unaffected.
11163
11164 @item ^-r^/REFERENCE^
11165 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11166 @findex Source_Reference
11167 Generate @code{Source_Reference} pragmas. Use this switch if the output
11168 files are regarded as temporary and development is to be done in terms
11169 of the original unchopped file. This switch causes
11170 @code{Source_Reference} pragmas to be inserted into each of the
11171 generated files to refers back to the original file name and line number.
11172 The result is that all error messages refer back to the original
11173 unchopped file.
11174 In addition, the debugging information placed into the object file (when
11175 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11176 specified)
11177 also refers back to this original file so that tools like profilers and
11178 debuggers will give information in terms of the original unchopped file.
11179
11180 If the original file to be chopped itself contains
11181 a @code{Source_Reference}
11182 pragma referencing a third file, then gnatchop respects
11183 this pragma, and the generated @code{Source_Reference} pragmas
11184 in the chopped file refer to the original file, with appropriate
11185 line numbers. This is particularly useful when @code{gnatchop}
11186 is used in conjunction with @code{gnatprep} to compile files that
11187 contain preprocessing statements and multiple units.
11188
11189 @item ^-v^/VERBOSE^
11190 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11191 Causes @code{gnatchop} to operate in verbose mode. The version
11192 number and copyright notice are output, as well as exact copies of
11193 the gnat1 commands spawned to obtain the chop control information.
11194
11195 @item ^-w^/OVERWRITE^
11196 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11197 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11198 fatal error if there is already a file with the same name as a
11199 file it would otherwise output, in other words if the files to be
11200 chopped contain duplicated units. This switch bypasses this
11201 check, and causes all but the last instance of such duplicated
11202 units to be skipped.
11203
11204 @ifclear vms
11205 @item --GCC=@var{xxxx}
11206 @cindex @option{--GCC=} (@code{gnatchop})
11207 Specify the path of the GNAT parser to be used. When this switch is used,
11208 no attempt is made to add the prefix to the GNAT parser executable.
11209 @end ifclear
11210 @end table
11211
11212 @node Examples of gnatchop Usage
11213 @section Examples of @code{gnatchop} Usage
11214
11215 @table @code
11216 @ifset vms
11217 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11218 @end ifset
11219 @ifclear vms
11220 @item gnatchop -w hello_s.ada prerelease/files
11221 @end ifclear
11222
11223 Chops the source file @file{hello_s.ada}. The output files will be
11224 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11225 overwriting any
11226 files with matching names in that directory (no files in the current
11227 directory are modified).
11228
11229 @item gnatchop ^archive^ARCHIVE.^
11230 Chops the source file @file{^archive^ARCHIVE.^}
11231 into the current directory. One
11232 useful application of @code{gnatchop} is in sending sets of sources
11233 around, for example in email messages. The required sources are simply
11234 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11235 command), and then
11236 @command{gnatchop} is used at the other end to reconstitute the original
11237 file names.
11238
11239 @item gnatchop file1 file2 file3 direc
11240 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11241 the resulting files in the directory @file{direc}. Note that if any units
11242 occur more than once anywhere within this set of files, an error message
11243 is generated, and no files are written. To override this check, use the
11244 @option{^-w^/OVERWRITE^} switch,
11245 in which case the last occurrence in the last file will
11246 be the one that is output, and earlier duplicate occurrences for a given
11247 unit will be skipped.
11248 @end table
11249
11250 @node Configuration Pragmas
11251 @chapter Configuration Pragmas
11252 @cindex Configuration pragmas
11253 @cindex Pragmas, configuration
11254
11255 @noindent
11256 Configuration pragmas include those pragmas described as
11257 such in the Ada Reference Manual, as well as
11258 implementation-dependent pragmas that are configuration pragmas.
11259 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11260 for details on these additional GNAT-specific configuration pragmas.
11261 Most notably, the pragma @code{Source_File_Name}, which allows
11262 specifying non-default names for source files, is a configuration
11263 pragma. The following is a complete list of configuration pragmas
11264 recognized by GNAT:
11265
11266 @smallexample
11267    Ada_83
11268    Ada_95
11269    Ada_05
11270    Ada_2005
11271    Assertion_Policy
11272    C_Pass_By_Copy
11273    Check_Name
11274    Check_Policy
11275    Compile_Time_Error
11276    Compile_Time_Warning
11277    Compiler_Unit
11278    Component_Alignment
11279    Debug_Policy
11280    Detect_Blocking
11281    Discard_Names
11282    Elaboration_Checks
11283    Eliminate
11284    Extend_System
11285    External_Name_Casing
11286    Fast_Math
11287    Favor_Top_Level
11288    Float_Representation
11289    Implicit_Packing
11290    Initialize_Scalars
11291    Interrupt_State
11292    License
11293    Locking_Policy
11294    Long_Float
11295    No_Run_Time
11296    No_Strict_Aliasing
11297    Normalize_Scalars
11298    Optimize_Alignment
11299    Persistent_BSS
11300    Polling
11301    Priority_Specific_Dispatching
11302    Profile
11303    Profile_Warnings
11304    Propagate_Exceptions
11305    Queuing_Policy
11306    Ravenscar
11307    Restricted_Run_Time
11308    Restrictions
11309    Restrictions_Warnings
11310    Reviewable
11311    Source_File_Name
11312    Source_File_Name_Project
11313    Style_Checks
11314    Suppress
11315    Suppress_Exception_Locations
11316    Task_Dispatching_Policy
11317    Universal_Data
11318    Unsuppress
11319    Use_VADS_Size
11320    Validity_Checks
11321    Warnings
11322    Wide_Character_Encoding
11323
11324 @end smallexample
11325
11326 @menu
11327 * Handling of Configuration Pragmas::
11328 * The Configuration Pragmas Files::
11329 @end menu
11330
11331 @node Handling of Configuration Pragmas
11332 @section Handling of Configuration Pragmas
11333
11334 Configuration pragmas may either appear at the start of a compilation
11335 unit, in which case they apply only to that unit, or they may apply to
11336 all compilations performed in a given compilation environment.
11337
11338 GNAT also provides the @code{gnatchop} utility to provide an automatic
11339 way to handle configuration pragmas following the semantics for
11340 compilations (that is, files with multiple units), described in the RM.
11341 See @ref{Operating gnatchop in Compilation Mode} for details.
11342 However, for most purposes, it will be more convenient to edit the
11343 @file{gnat.adc} file that contains configuration pragmas directly,
11344 as described in the following section.
11345
11346 @node The Configuration Pragmas Files
11347 @section The Configuration Pragmas Files
11348 @cindex @file{gnat.adc}
11349
11350 @noindent
11351 In GNAT a compilation environment is defined by the current
11352 directory at the time that a compile command is given. This current
11353 directory is searched for a file whose name is @file{gnat.adc}. If
11354 this file is present, it is expected to contain one or more
11355 configuration pragmas that will be applied to the current compilation.
11356 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11357 considered.
11358
11359 Configuration pragmas may be entered into the @file{gnat.adc} file
11360 either by running @code{gnatchop} on a source file that consists only of
11361 configuration pragmas, or more conveniently  by
11362 direct editing of the @file{gnat.adc} file, which is a standard format
11363 source file.
11364
11365 In addition to @file{gnat.adc}, additional files containing configuration
11366 pragmas may be applied to the current compilation using the switch
11367 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11368 contains only configuration pragmas. These configuration pragmas are
11369 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11370 is present and switch @option{-gnatA} is not used).
11371
11372 It is allowed to specify several switches @option{-gnatec}, all of which
11373 will be taken into account.
11374
11375 If you are using project file, a separate mechanism is provided using
11376 project attributes, see @ref{Specifying Configuration Pragmas} for more
11377 details.
11378
11379 @ifset vms
11380 Of special interest to GNAT OpenVMS Alpha is the following
11381 configuration pragma:
11382
11383 @smallexample @c ada
11384 @cartouche
11385 pragma Extend_System (Aux_DEC);
11386 @end cartouche
11387 @end smallexample
11388
11389 @noindent
11390 In the presence of this pragma, GNAT adds to the definition of the
11391 predefined package SYSTEM all the additional types and subprograms that are
11392 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11393 @end ifset
11394
11395 @node Handling Arbitrary File Naming Conventions Using gnatname
11396 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11397 @cindex Arbitrary File Naming Conventions
11398
11399 @menu
11400 * Arbitrary File Naming Conventions::
11401 * Running gnatname::
11402 * Switches for gnatname::
11403 * Examples of gnatname Usage::
11404 @end menu
11405
11406 @node Arbitrary File Naming Conventions
11407 @section Arbitrary File Naming Conventions
11408
11409 @noindent
11410 The GNAT compiler must be able to know the source file name of a compilation
11411 unit.  When using the standard GNAT default file naming conventions
11412 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11413 does not need additional information.
11414
11415 @noindent
11416 When the source file names do not follow the standard GNAT default file naming
11417 conventions, the GNAT compiler must be given additional information through
11418 a configuration pragmas file (@pxref{Configuration Pragmas})
11419 or a project file.
11420 When the non-standard file naming conventions are well-defined,
11421 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11422 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11423 if the file naming conventions are irregular or arbitrary, a number
11424 of pragma @code{Source_File_Name} for individual compilation units
11425 must be defined.
11426 To help maintain the correspondence between compilation unit names and
11427 source file names within the compiler,
11428 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11429 set of files.
11430
11431 @node Running gnatname
11432 @section Running @code{gnatname}
11433
11434 @noindent
11435 The usual form of the @code{gnatname} command is
11436
11437 @smallexample
11438 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11439       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11440 @end smallexample
11441
11442 @noindent
11443 All of the arguments are optional. If invoked without any argument,
11444 @code{gnatname} will display its usage.
11445
11446 @noindent
11447 When used with at least one naming pattern, @code{gnatname} will attempt to
11448 find all the compilation units in files that follow at least one of the
11449 naming patterns. To find these compilation units,
11450 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11451 regular files.
11452
11453 @noindent
11454 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11455 Each Naming Pattern is enclosed between double quotes.
11456 A Naming Pattern is a regular expression similar to the wildcard patterns
11457 used in file names by the Unix shells or the DOS prompt.
11458
11459 @noindent
11460 @code{gnatname} may be called with several sections of directories/patterns.
11461 Sections are separated by switch @code{--and}. In each section, there must be
11462 at least one pattern. If no directory is specified in a section, the current
11463 directory (or the project directory is @code{-P} is used) is implied.
11464 The options other that the directory switches and the patterns apply globally
11465 even if they are in different sections.
11466
11467 @noindent
11468 Examples of Naming Patterns are
11469
11470 @smallexample
11471    "*.[12].ada"
11472    "*.ad[sb]*"
11473    "body_*"    "spec_*"
11474 @end smallexample
11475
11476 @noindent
11477 For a more complete description of the syntax of Naming Patterns,
11478 see the second kind of regular expressions described in @file{g-regexp.ads}
11479 (the ``Glob'' regular expressions).
11480
11481 @noindent
11482 When invoked with no switch @code{-P}, @code{gnatname} will create a
11483 configuration pragmas file @file{gnat.adc} in the current working directory,
11484 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11485 unit.
11486
11487 @node Switches for gnatname
11488 @section Switches for @code{gnatname}
11489
11490 @noindent
11491 Switches for @code{gnatname} must precede any specified Naming Pattern.
11492
11493 @noindent
11494 You may specify any of the following switches to @code{gnatname}:
11495
11496 @table @option
11497 @c !sort!
11498
11499 @item --version
11500 @cindex @option{--version} @command{gnatname}
11501 Display Copyright and version, then exit disregarding all other options.
11502
11503 @item --help
11504 @cindex @option{--help} @command{gnatname}
11505 If @option{--version} was not used, display usage, then exit disregarding
11506 all other options.
11507
11508 @item --and
11509 Start another section of directories/patterns.
11510
11511 @item ^-c^/CONFIG_FILE=^@file{file}
11512 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11513 Create a configuration pragmas file @file{file} (instead of the default
11514 @file{gnat.adc}).
11515 @ifclear vms
11516 There may be zero, one or more space between @option{-c} and
11517 @file{file}.
11518 @end ifclear
11519 @file{file} may include directory information. @file{file} must be
11520 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11521 When a switch @option{^-c^/CONFIG_FILE^} is
11522 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11523
11524 @item ^-d^/SOURCE_DIRS=^@file{dir}
11525 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11526 Look for source files in directory @file{dir}. There may be zero, one or more
11527 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11528 When a switch @option{^-d^/SOURCE_DIRS^}
11529 is specified, the current working directory will not be searched for source
11530 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11531 or @option{^-D^/DIR_FILES^} switch.
11532 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11533 If @file{dir} is a relative path, it is relative to the directory of
11534 the configuration pragmas file specified with switch
11535 @option{^-c^/CONFIG_FILE^},
11536 or to the directory of the project file specified with switch
11537 @option{^-P^/PROJECT_FILE^} or,
11538 if neither switch @option{^-c^/CONFIG_FILE^}
11539 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11540 current working directory. The directory
11541 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11542
11543 @item ^-D^/DIRS_FILE=^@file{file}
11544 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11545 Look for source files in all directories listed in text file @file{file}.
11546 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11547 and @file{file}.
11548 @file{file} must be an existing, readable text file.
11549 Each nonempty line in @file{file} must be a directory.
11550 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11551 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11552 @file{file}.
11553
11554 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11555 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11556 Foreign patterns. Using this switch, it is possible to add sources of languages
11557 other than Ada to the list of sources of a project file.
11558 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11559 For example,
11560 @smallexample
11561 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11562 @end smallexample
11563 @noindent
11564 will look for Ada units in all files with the @file{.ada} extension,
11565 and will add to the list of file for project @file{prj.gpr} the C files
11566 with extension @file{.^c^C^}.
11567
11568 @item ^-h^/HELP^
11569 @cindex @option{^-h^/HELP^} (@code{gnatname})
11570 Output usage (help) information. The output is written to @file{stdout}.
11571
11572 @item ^-P^/PROJECT_FILE=^@file{proj}
11573 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11574 Create or update project file @file{proj}. There may be zero, one or more space
11575 between @option{-P} and @file{proj}. @file{proj} may include directory
11576 information. @file{proj} must be writable.
11577 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11578 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11579 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11580
11581 @item ^-v^/VERBOSE^
11582 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11583 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11584 This includes name of the file written, the name of the directories to search
11585 and, for each file in those directories whose name matches at least one of
11586 the Naming Patterns, an indication of whether the file contains a unit,
11587 and if so the name of the unit.
11588
11589 @item ^-v -v^/VERBOSE /VERBOSE^
11590 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11591 Very Verbose mode. In addition to the output produced in verbose mode,
11592 for each file in the searched directories whose name matches none of
11593 the Naming Patterns, an indication is given that there is no match.
11594
11595 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11596 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11597 Excluded patterns. Using this switch, it is possible to exclude some files
11598 that would match the name patterns. For example,
11599 @smallexample
11600 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11601 @end smallexample
11602 @noindent
11603 will look for Ada units in all files with the @file{.ada} extension,
11604 except those whose names end with @file{_nt.ada}.
11605
11606 @end table
11607
11608 @node Examples of gnatname Usage
11609 @section Examples of @code{gnatname} Usage
11610
11611 @ifset vms
11612 @smallexample
11613 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11614 @end smallexample
11615 @end ifset
11616
11617 @ifclear vms
11618 @smallexample
11619 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11620 @end smallexample
11621 @end ifclear
11622
11623 @noindent
11624 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11625 and be writable. In addition, the directory
11626 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11627 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11628
11629 @ifclear vms
11630 Note the optional spaces after @option{-c} and @option{-d}.
11631 @end ifclear
11632
11633 @smallexample
11634 @ifclear vms
11635 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11636   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11637 @end ifclear
11638 @ifset vms
11639 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11640   /EXCLUDED_PATTERN=*_nt_body.ada
11641   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11642   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11643 @end ifset
11644 @end smallexample
11645
11646 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11647 even in conjunction with one or several switches
11648 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11649 are used in this example.
11650
11651 @c *****************************************
11652 @c * G N A T  P r o j e c t  M a n a g e r *
11653 @c *****************************************
11654 @node GNAT Project Manager
11655 @chapter GNAT Project Manager
11656
11657 @menu
11658 * Introduction::
11659 * Examples of Project Files::
11660 * Project File Syntax::
11661 * Objects and Sources in Project Files::
11662 * Importing Projects::
11663 * Project Extension::
11664 * Project Hierarchy Extension::
11665 * External References in Project Files::
11666 * Packages in Project Files::
11667 * Variables from Imported Projects::
11668 * Naming Schemes::
11669 * Library Projects::
11670 * Stand-alone Library Projects::
11671 * Switches Related to Project Files::
11672 * Tools Supporting Project Files::
11673 * An Extended Example::
11674 * Project File Complete Syntax::
11675 @end menu
11676
11677 @c ****************
11678 @c * Introduction *
11679 @c ****************
11680
11681 @node Introduction
11682 @section Introduction
11683
11684 @noindent
11685 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11686 you to manage complex builds involving a number of source files, directories,
11687 and compilation options for different system configurations. In particular,
11688 project files allow you to specify:
11689 @itemize @bullet
11690 @item
11691 The directory or set of directories containing the source files, and/or the
11692 names of the specific source files themselves
11693 @item
11694 The directory in which the compiler's output
11695 (@file{ALI} files, object files, tree files) is to be placed
11696 @item
11697 The directory in which the executable programs is to be placed
11698 @item
11699 ^Switch^Switch^ settings for any of the project-enabled tools
11700 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11701 @code{gnatfind}); you can apply these settings either globally or to individual
11702 compilation units.
11703 @item
11704 The source files containing the main subprogram(s) to be built
11705 @item
11706 The source programming language(s) (currently Ada and/or C)
11707 @item
11708 Source file naming conventions; you can specify these either globally or for
11709 individual compilation units
11710 @end itemize
11711
11712 @menu
11713 * Project Files::
11714 @end menu
11715
11716 @node Project Files
11717 @subsection Project Files
11718
11719 @noindent
11720 Project files are written in a syntax close to that of Ada, using  familiar
11721 notions such as packages, context clauses, declarations, default values,
11722 assignments, and inheritance. Finally, project files can be built
11723 hierarchically from other project files, simplifying complex system
11724 integration and project reuse.
11725
11726 A @dfn{project} is a specific set of values for various compilation properties.
11727 The settings for a given project are described by means of
11728 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11729 Property values in project files are either strings or lists of strings.
11730 Properties that are not explicitly set receive default values.  A project
11731 file may interrogate the values of @dfn{external variables} (user-defined
11732 command-line switches or environment variables), and it may specify property
11733 settings conditionally, based on the value of such variables.
11734
11735 In simple cases, a project's source files depend only on other source files
11736 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11737 used in
11738 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11739 the Project Manager also allows more sophisticated arrangements,
11740 where the source files in one project depend on source files in other
11741 projects:
11742 @itemize @bullet
11743 @item
11744 One project can @emph{import} other projects containing needed source files.
11745 @item
11746 You can organize GNAT projects in a hierarchy: a @emph{child} project
11747 can extend a @emph{parent} project, inheriting the parent's source files and
11748 optionally overriding any of them with alternative versions
11749 @end itemize
11750
11751 @noindent
11752 More generally, the Project Manager lets you structure large development
11753 efforts into hierarchical subsystems, where build decisions are delegated
11754 to the subsystem level, and thus different compilation environments
11755 (^switch^switch^ settings) used for different subsystems.
11756
11757 The Project Manager is invoked through the
11758 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11759 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11760 @ifclear vms
11761 There may be zero, one or more spaces between @option{-P} and
11762 @option{@emph{projectfile}}.
11763 @end ifclear
11764 If you want to define (on the command line) an external variable that is
11765 queried by the project file, you must use the
11766 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11767 The Project Manager parses and interprets the project file, and drives the
11768 invoked tool based on the project settings.
11769
11770 The Project Manager supports a wide range of development strategies,
11771 for systems of all sizes.  Here are some typical practices that are
11772 easily handled:
11773 @itemize @bullet
11774 @item
11775 Using a common set of source files, but generating object files in different
11776 directories via different ^switch^switch^ settings
11777 @item
11778 Using a mostly-shared set of source files, but with different versions of
11779 some unit or units
11780 @end itemize
11781
11782 @noindent
11783 The destination of an executable can be controlled inside a project file
11784 using the @option{^-o^-o^}
11785 ^switch^switch^.
11786 In the absence of such a ^switch^switch^ either inside
11787 the project file or on the command line, any executable files generated by
11788 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11789 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11790 in the object directory of the project.
11791
11792 You can use project files to achieve some of the effects of a source
11793 versioning system (for example, defining separate projects for
11794 the different sets of sources that comprise different releases) but the
11795 Project Manager is independent of any source configuration management tools
11796 that might be used by the developers.
11797
11798 The next section introduces the main features of GNAT's project facility
11799 through a sequence of examples; subsequent sections will present the syntax
11800 and semantics in more detail. A more formal description of the project
11801 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11802 Reference Manual}.
11803
11804 @c *****************************
11805 @c * Examples of Project Files *
11806 @c *****************************
11807
11808 @node Examples of Project Files
11809 @section Examples of Project Files
11810 @noindent
11811 This section illustrates some of the typical uses of project files and
11812 explains their basic structure and behavior.
11813
11814 @menu
11815 * Common Sources with Different ^Switches^Switches^ and Directories::
11816 * Using External Variables::
11817 * Importing Other Projects::
11818 * Extending a Project::
11819 @end menu
11820
11821 @node Common Sources with Different ^Switches^Switches^ and Directories
11822 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11823
11824 @menu
11825 * Source Files::
11826 * Specifying the Object Directory::
11827 * Specifying the Exec Directory::
11828 * Project File Packages::
11829 * Specifying ^Switch^Switch^ Settings::
11830 * Main Subprograms::
11831 * Executable File Names::
11832 * Source File Naming Conventions::
11833 * Source Language(s)::
11834 @end menu
11835
11836 @noindent
11837 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11838 @file{proc.adb} are in the @file{/common} directory.  The file
11839 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11840 package @code{Pack}.  We want to compile these source files under two sets
11841 of ^switches^switches^:
11842 @itemize @bullet
11843 @item
11844 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11845 and the @option{^-gnata^-gnata^},
11846 @option{^-gnato^-gnato^},
11847 and @option{^-gnatE^-gnatE^} switches to the
11848 compiler; the compiler's output is to appear in @file{/common/debug}
11849 @item
11850 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11851 to the compiler; the compiler's output is to appear in @file{/common/release}
11852 @end itemize
11853
11854 @noindent
11855 The GNAT project files shown below, respectively @file{debug.gpr} and
11856 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11857
11858 Schematically:
11859 @smallexample
11860 @group
11861 ^/common^[COMMON]^
11862   debug.gpr
11863   release.gpr
11864   pack.ads
11865   pack.adb
11866   proc.adb
11867 @end group
11868 @group
11869 ^/common/debug^[COMMON.DEBUG]^
11870   proc.ali, proc.o
11871   pack.ali, pack.o
11872 @end group
11873 @group
11874 ^/common/release^[COMMON.RELEASE]^
11875   proc.ali, proc.o
11876   pack.ali, pack.o
11877 @end group
11878 @end smallexample
11879 Here are the corresponding project files:
11880
11881 @smallexample @c projectfile
11882 @group
11883 project Debug is
11884   for Object_Dir use "debug";
11885   for Main use ("proc");
11886
11887   package Builder is
11888     for ^Default_Switches^Default_Switches^ ("Ada")
11889         use ("^-g^-g^");
11890     for Executable ("proc.adb") use "proc1";
11891   end Builder;
11892 @end group
11893
11894 @group
11895   package Compiler is
11896     for ^Default_Switches^Default_Switches^ ("Ada")
11897        use ("-fstack-check",
11898             "^-gnata^-gnata^",
11899             "^-gnato^-gnato^",
11900             "^-gnatE^-gnatE^");
11901   end Compiler;
11902 end Debug;
11903 @end group
11904 @end smallexample
11905
11906 @smallexample @c projectfile
11907 @group
11908 project Release is
11909   for Object_Dir use "release";
11910   for Exec_Dir use ".";
11911   for Main use ("proc");
11912
11913   package Compiler is
11914     for ^Default_Switches^Default_Switches^ ("Ada")
11915         use ("^-O2^-O2^");
11916   end Compiler;
11917 end Release;
11918 @end group
11919 @end smallexample
11920
11921 @noindent
11922 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11923 insensitive), and analogously the project defined by @file{release.gpr} is
11924 @code{"Release"}.  For consistency the file should have the same name as the
11925 project, and the project file's extension should be @code{"gpr"}. These
11926 conventions are not required, but a warning is issued if they are not followed.
11927
11928 If the current directory is @file{^/temp^[TEMP]^}, then the command
11929 @smallexample
11930 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11931 @end smallexample
11932
11933 @noindent
11934 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11935 as well as the @code{^proc1^PROC1.EXE^} executable,
11936 using the ^switch^switch^ settings defined in the project file.
11937
11938 Likewise, the command
11939 @smallexample
11940 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11941 @end smallexample
11942
11943 @noindent
11944 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11945 and the @code{^proc^PROC.EXE^}
11946 executable in @file{^/common^[COMMON]^},
11947 using the ^switch^switch^ settings from the project file.
11948
11949 @node Source Files
11950 @unnumberedsubsubsec Source Files
11951
11952 @noindent
11953 If a project file does not explicitly specify a set of source directories or
11954 a set of source files, then by default the project's source files are the
11955 Ada source files in the project file directory.  Thus @file{pack.ads},
11956 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11957
11958 @node Specifying the Object Directory
11959 @unnumberedsubsubsec Specifying the Object Directory
11960
11961 @noindent
11962 Several project properties are modeled by Ada-style @emph{attributes};
11963 a property is defined by supplying the equivalent of an Ada attribute
11964 definition clause in the project file.
11965 A project's object directory is another such a property; the corresponding
11966 attribute is @code{Object_Dir}, and its value is also a string expression,
11967 specified either as absolute or relative. In the later case,
11968 it is relative to the project file directory. Thus the compiler's
11969 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11970 (for the @code{Debug} project)
11971 and to @file{^/common/release^[COMMON.RELEASE]^}
11972 (for the @code{Release} project).
11973 If @code{Object_Dir} is not specified, then the default is the project file
11974 directory itself.
11975
11976 @node Specifying the Exec Directory
11977 @unnumberedsubsubsec Specifying the Exec Directory
11978
11979 @noindent
11980 A project's exec directory is another property; the corresponding
11981 attribute is @code{Exec_Dir}, and its value is also a string expression,
11982 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11983 then the default is the object directory (which may also be the project file
11984 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11985 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11986 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11987 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11988
11989 @node Project File Packages
11990 @unnumberedsubsubsec Project File Packages
11991
11992 @noindent
11993 A GNAT tool that is integrated with the Project Manager is modeled by a
11994 corresponding package in the project file. In the example above,
11995 The @code{Debug} project defines the packages @code{Builder}
11996 (for @command{gnatmake}) and @code{Compiler};
11997 the @code{Release} project defines only the @code{Compiler} package.
11998
11999 The Ada-like package syntax is not to be taken literally.  Although packages in
12000 project files bear a surface resemblance to packages in Ada source code, the
12001 notation is simply a way to convey a grouping of properties for a named
12002 entity.  Indeed, the package names permitted in project files are restricted
12003 to a predefined set, corresponding to the project-aware tools, and the contents
12004 of packages are limited to a small set of constructs.
12005 The packages in the example above contain attribute definitions.
12006
12007 @node Specifying ^Switch^Switch^ Settings
12008 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12009
12010 @noindent
12011 ^Switch^Switch^ settings for a project-aware tool can be specified through
12012 attributes in the package that corresponds to the tool.
12013 The example above illustrates one of the relevant attributes,
12014 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12015 in both project files.
12016 Unlike simple attributes like @code{Source_Dirs},
12017 @code{^Default_Switches^Default_Switches^} is
12018 known as an @emph{associative array}.  When you define this attribute, you must
12019 supply an ``index'' (a literal string), and the effect of the attribute
12020 definition is to set the value of the array at the specified index.
12021 For the @code{^Default_Switches^Default_Switches^} attribute,
12022 the index is a programming language (in our case, Ada),
12023 and the value specified (after @code{use}) must be a list
12024 of string expressions.
12025
12026 The attributes permitted in project files are restricted to a predefined set.
12027 Some may appear at project level, others in packages.
12028 For any attribute that is an associative array, the index must always be a
12029 literal string, but the restrictions on this string (e.g., a file name or a
12030 language name) depend on the individual attribute.
12031 Also depending on the attribute, its specified value will need to be either a
12032 string or a string list.
12033
12034 In the @code{Debug} project, we set the switches for two tools,
12035 @command{gnatmake} and the compiler, and thus we include the two corresponding
12036 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12037 attribute with index @code{"Ada"}.
12038 Note that the package corresponding to
12039 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12040 similar, but only includes the @code{Compiler} package.
12041
12042 In project @code{Debug} above, the ^switches^switches^ starting with
12043 @option{-gnat} that are specified in package @code{Compiler}
12044 could have been placed in package @code{Builder}, since @command{gnatmake}
12045 transmits all such ^switches^switches^ to the compiler.
12046
12047 @node Main Subprograms
12048 @unnumberedsubsubsec Main Subprograms
12049
12050 @noindent
12051 One of the specifiable properties of a project is a list of files that contain
12052 main subprograms.  This property is captured in the @code{Main} attribute,
12053 whose value is a list of strings.  If a project defines the @code{Main}
12054 attribute, it is not necessary to identify the main subprogram(s) when
12055 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12056
12057 @node Executable File Names
12058 @unnumberedsubsubsec Executable File Names
12059
12060 @noindent
12061 By default, the executable file name corresponding to a main source is
12062 deduced from the main source file name. Through the attributes
12063 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12064 it is possible to change this default.
12065 In project @code{Debug} above, the executable file name
12066 for main source @file{^proc.adb^PROC.ADB^} is
12067 @file{^proc1^PROC1.EXE^}.
12068 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12069 of the executable files, when no attribute @code{Executable} applies:
12070 its value replace the platform-specific executable suffix.
12071 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12072 specify a non-default executable file name when several mains are built at once
12073 in a single @command{gnatmake} command.
12074
12075 @node Source File Naming Conventions
12076 @unnumberedsubsubsec Source File Naming Conventions
12077
12078 @noindent
12079 Since the project files above do not specify any source file naming
12080 conventions, the GNAT defaults are used.  The mechanism for defining source
12081 file naming conventions -- a package named @code{Naming} --
12082 is described below (@pxref{Naming Schemes}).
12083
12084 @node Source Language(s)
12085 @unnumberedsubsubsec Source Language(s)
12086
12087 @noindent
12088 Since the project files do not specify a @code{Languages} attribute, by
12089 default the GNAT tools assume that the language of the project file is Ada.
12090 More generally, a project can comprise source files
12091 in Ada, C, and/or other languages.
12092
12093 @node Using External Variables
12094 @subsection Using External Variables
12095
12096 @noindent
12097 Instead of supplying different project files for debug and release, we can
12098 define a single project file that queries an external variable (set either
12099 on the command line or via an ^environment variable^logical name^) in order to
12100 conditionally define the appropriate settings.  Again, assume that the
12101 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12102 located in directory @file{^/common^[COMMON]^}.  The following project file,
12103 @file{build.gpr}, queries the external variable named @code{STYLE} and
12104 defines an object directory and ^switch^switch^ settings based on whether
12105 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12106 the default is @code{"deb"}.
12107
12108 @smallexample @c projectfile
12109 @group
12110 project Build is
12111   for Main use ("proc");
12112
12113   type Style_Type is ("deb", "rel");
12114   Style : Style_Type := external ("STYLE", "deb");
12115
12116   case Style is
12117     when "deb" =>
12118       for Object_Dir use "debug";
12119
12120     when "rel" =>
12121       for Object_Dir use "release";
12122       for Exec_Dir use ".";
12123   end case;
12124 @end group
12125
12126 @group
12127   package Builder is
12128
12129     case Style is
12130       when "deb" =>
12131         for ^Default_Switches^Default_Switches^ ("Ada")
12132             use ("^-g^-g^");
12133         for Executable ("proc") use "proc1";
12134       when others =>
12135         null;
12136     end case;
12137
12138   end Builder;
12139 @end group
12140
12141 @group
12142   package Compiler is
12143
12144     case Style is
12145       when "deb" =>
12146         for ^Default_Switches^Default_Switches^ ("Ada")
12147             use ("^-gnata^-gnata^",
12148                  "^-gnato^-gnato^",
12149                  "^-gnatE^-gnatE^");
12150
12151       when "rel" =>
12152         for ^Default_Switches^Default_Switches^ ("Ada")
12153             use ("^-O2^-O2^");
12154     end case;
12155
12156   end Compiler;
12157
12158 end Build;
12159 @end group
12160 @end smallexample
12161
12162 @noindent
12163 @code{Style_Type} is an example of a @emph{string type}, which is the project
12164 file analog of an Ada enumeration type but whose components are string literals
12165 rather than identifiers.  @code{Style} is declared as a variable of this type.
12166
12167 The form @code{external("STYLE", "deb")} is known as an
12168 @emph{external reference}; its first argument is the name of an
12169 @emph{external variable}, and the second argument is a default value to be
12170 used if the external variable doesn't exist.  You can define an external
12171 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12172 or you can use ^an environment variable^a logical name^
12173 as an external variable.
12174
12175 Each @code{case} construct is expanded by the Project Manager based on the
12176 value of @code{Style}. Thus the command
12177 @ifclear vms
12178 @smallexample
12179 gnatmake -P/common/build.gpr -XSTYLE=deb
12180 @end smallexample
12181 @end ifclear
12182
12183 @ifset vms
12184 @smallexample
12185 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12186 @end smallexample
12187 @end ifset
12188
12189 @noindent
12190 is equivalent to the @command{gnatmake} invocation using the project file
12191 @file{debug.gpr} in the earlier example.  So is the command
12192 @smallexample
12193 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12194 @end smallexample
12195
12196 @noindent
12197 since @code{"deb"} is the default for @code{STYLE}.
12198
12199 Analogously,
12200
12201 @ifclear vms
12202 @smallexample
12203 gnatmake -P/common/build.gpr -XSTYLE=rel
12204 @end smallexample
12205 @end ifclear
12206
12207 @ifset vms
12208 @smallexample
12209 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12210 @end smallexample
12211 @end ifset
12212
12213 @noindent
12214 is equivalent to the @command{gnatmake} invocation using the project file
12215 @file{release.gpr} in the earlier example.
12216
12217 @node Importing Other Projects
12218 @subsection Importing Other Projects
12219 @cindex @code{ADA_PROJECT_PATH}
12220
12221 @noindent
12222 A compilation unit in a source file in one project may depend on compilation
12223 units in source files in other projects.  To compile this unit under
12224 control of a project file, the
12225 dependent project must @emph{import} the projects containing the needed source
12226 files.
12227 This effect is obtained using syntax similar to an Ada @code{with} clause,
12228 but where @code{with}ed entities are strings that denote project files.
12229
12230 As an example, suppose that the two projects @code{GUI_Proj} and
12231 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12232 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12233 and @file{^/comm^[COMM]^}, respectively.
12234 Suppose that the source files for @code{GUI_Proj} are
12235 @file{gui.ads} and @file{gui.adb}, and that the source files for
12236 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12237 files is located in its respective project file directory.  Schematically:
12238
12239 @smallexample
12240 @group
12241 ^/gui^[GUI]^
12242   gui_proj.gpr
12243   gui.ads
12244   gui.adb
12245 @end group
12246
12247 @group
12248 ^/comm^[COMM]^
12249   comm_proj.gpr
12250   comm.ads
12251   comm.adb
12252 @end group
12253 @end smallexample
12254
12255 @noindent
12256 We want to develop an application in directory @file{^/app^[APP]^} that
12257 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12258 the corresponding project files (e.g.@: the ^switch^switch^ settings
12259 and object directory).
12260 Skeletal code for a main procedure might be something like the following:
12261
12262 @smallexample @c ada
12263 @group
12264 with GUI, Comm;
12265 procedure App_Main is
12266    @dots{}
12267 begin
12268    @dots{}
12269 end App_Main;
12270 @end group
12271 @end smallexample
12272
12273 @noindent
12274 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12275 effect:
12276
12277 @smallexample @c projectfile
12278 @group
12279 with "/gui/gui_proj", "/comm/comm_proj";
12280 project App_Proj is
12281    for Main use ("app_main");
12282 end App_Proj;
12283 @end group
12284 @end smallexample
12285
12286 @noindent
12287 Building an executable is achieved through the command:
12288 @smallexample
12289 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12290 @end smallexample
12291 @noindent
12292 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12293 in the directory where @file{app_proj.gpr} resides.
12294
12295 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12296 (as illustrated above) the @code{with} clause can omit the extension.
12297
12298 Our example specified an absolute path for each imported project file.
12299 Alternatively, the directory name of an imported object can be omitted
12300 if either
12301 @itemize @bullet
12302 @item
12303 The imported project file is in the same directory as the importing project
12304 file, or
12305 @item
12306 You have defined ^an environment variable^a logical name^
12307 that includes the directory containing
12308 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12309 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12310 directory names separated by colons (semicolons on Windows).
12311 @end itemize
12312
12313 @noindent
12314 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12315 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12316 as follows:
12317
12318 @smallexample @c projectfile
12319 @group
12320 with "gui_proj", "comm_proj";
12321 project App_Proj is
12322    for Main use ("app_main");
12323 end App_Proj;
12324 @end group
12325 @end smallexample
12326
12327 @noindent
12328 Importing other projects can create ambiguities.
12329 For example, the same unit might be present in different imported projects, or
12330 it might be present in both the importing project and in an imported project.
12331 Both of these conditions are errors.  Note that in the current version of
12332 the Project Manager, it is illegal to have an ambiguous unit even if the
12333 unit is never referenced by the importing project.  This restriction may be
12334 relaxed in a future release.
12335
12336 @node Extending a Project
12337 @subsection Extending a Project
12338
12339 @noindent
12340 In large software systems it is common to have multiple
12341 implementations of a common interface; in Ada terms, multiple versions of a
12342 package body for the same spec.  For example, one implementation
12343 might be safe for use in tasking programs, while another might only be used
12344 in sequential applications.  This can be modeled in GNAT using the concept
12345 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12346 another project (the ``parent'') then by default all source files of the
12347 parent project are inherited by the child, but the child project can
12348 override any of the parent's source files with new versions, and can also
12349 add new files.  This facility is the project analog of a type extension in
12350 Object-Oriented Programming.  Project hierarchies are permitted (a child
12351 project may be the parent of yet another project), and a project that
12352 inherits one project can also import other projects.
12353
12354 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12355 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12356 @file{pack.adb}, and @file{proc.adb}:
12357
12358 @smallexample
12359 @group
12360 ^/seq^[SEQ]^
12361   pack.ads
12362   pack.adb
12363   proc.adb
12364   seq_proj.gpr
12365 @end group
12366 @end smallexample
12367
12368 @noindent
12369 Note that the project file can simply be empty (that is, no attribute or
12370 package is defined):
12371
12372 @smallexample @c projectfile
12373 @group
12374 project Seq_Proj is
12375 end Seq_Proj;
12376 @end group
12377 @end smallexample
12378
12379 @noindent
12380 implying that its source files are all the Ada source files in the project
12381 directory.
12382
12383 Suppose we want to supply an alternate version of @file{pack.adb}, in
12384 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12385 @file{pack.ads} and @file{proc.adb}.  We can define a project
12386 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12387
12388 @smallexample
12389 @group
12390 ^/tasking^[TASKING]^
12391   pack.adb
12392   tasking_proj.gpr
12393 @end group
12394
12395 @group
12396 project Tasking_Proj extends "/seq/seq_proj" is
12397 end Tasking_Proj;
12398 @end group
12399 @end smallexample
12400
12401 @noindent
12402 The version of @file{pack.adb} used in a build depends on which project file
12403 is specified.
12404
12405 Note that we could have obtained the desired behavior using project import
12406 rather than project inheritance; a @code{base} project would contain the
12407 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12408 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12409 would import @code{base} and add a different version of @file{pack.adb}.  The
12410 choice depends on whether other sources in the original project need to be
12411 overridden.  If they do, then project extension is necessary, otherwise,
12412 importing is sufficient.
12413
12414 @noindent
12415 In a project file that extends another project file, it is possible to
12416 indicate that an inherited source is not part of the sources of the extending
12417 project. This is necessary sometimes when a package spec has been overloaded
12418 and no longer requires a body: in this case, it is necessary to indicate that
12419 the inherited body is not part of the sources of the project, otherwise there
12420 will be a compilation error when compiling the spec.
12421
12422 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12423 Its value is a string list: a list of file names. It is also possible to use
12424 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12425 the file name of a text file containing a list of file names, one per line.
12426
12427 @smallexample @c @projectfile
12428 project B extends "a" is
12429    for Source_Files use ("pkg.ads");
12430    --  New spec of Pkg does not need a completion
12431    for Excluded_Source_Files use ("pkg.adb");
12432 end B;
12433 @end smallexample
12434
12435 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12436 is still needed: if it is possible to build using @command{gnatmake} when such
12437 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12438 it is possible to remove the source completely from a system that includes
12439 project P.
12440
12441 @c ***********************
12442 @c * Project File Syntax *
12443 @c ***********************
12444
12445 @node Project File Syntax
12446 @section Project File Syntax
12447
12448 @menu
12449 * Basic Syntax::
12450 * Qualified Projects::
12451 * Packages::
12452 * Expressions::
12453 * String Types::
12454 * Variables::
12455 * Attributes::
12456 * Associative Array Attributes::
12457 * case Constructions::
12458 @end menu
12459
12460 @noindent
12461 This section describes the structure of project files.
12462
12463 A project may be an @emph{independent project}, entirely defined by a single
12464 project file. Any Ada source file in an independent project depends only
12465 on the predefined library and other Ada source files in the same project.
12466
12467 @noindent
12468 A project may also @dfn{depend on} other projects, in either or both of
12469 the following ways:
12470 @itemize @bullet
12471 @item It may import any number of projects
12472 @item It may extend at most one other project
12473 @end itemize
12474
12475 @noindent
12476 The dependence relation is a directed acyclic graph (the subgraph reflecting
12477 the ``extends'' relation is a tree).
12478
12479 A project's @dfn{immediate sources} are the source files directly defined by
12480 that project, either implicitly by residing in the project file's directory,
12481 or explicitly through any of the source-related attributes described below.
12482 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12483 of @var{proj} together with the immediate sources (unless overridden) of any
12484 project on which @var{proj} depends (either directly or indirectly).
12485
12486 @node Basic Syntax
12487 @subsection Basic Syntax
12488
12489 @noindent
12490 As seen in the earlier examples, project files have an Ada-like syntax.
12491 The minimal project file is:
12492 @smallexample @c projectfile
12493 @group
12494 project Empty is
12495
12496 end Empty;
12497 @end group
12498 @end smallexample
12499
12500 @noindent
12501 The identifier @code{Empty} is the name of the project.
12502 This project name must be present after the reserved
12503 word @code{end} at the end of the project file, followed by a semi-colon.
12504
12505 Any name in a project file, such as the project name or a variable name,
12506 has the same syntax as an Ada identifier.
12507
12508 The reserved words of project files are the Ada 95 reserved words plus
12509 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12510 reserved words currently used in project file syntax are:
12511
12512 @itemize @bullet
12513 @item
12514 @code{all}
12515 @item
12516 @code{at}
12517 @item
12518 @code{case}
12519 @item
12520 @code{end}
12521 @item
12522 @code{for}
12523 @item
12524 @code{is}
12525 @item
12526 @code{limited}
12527 @item
12528 @code{null}
12529 @item
12530 @code{others}
12531 @item
12532 @code{package}
12533 @item
12534 @code{renames}
12535 @item
12536 @code{type}
12537 @item
12538 @code{use}
12539 @item
12540 @code{when}
12541 @item
12542 @code{with}
12543 @end itemize
12544
12545 @noindent
12546 Comments in project files have the same syntax as in Ada, two consecutive
12547 hyphens through the end of the line.
12548
12549 @node Qualified Projects
12550 @subsection Qualified Projects
12551
12552 @noindent
12553 Before the reserved @code{project}, there may be one or two "qualifiers", that
12554 is identifiers or other reserved words, to qualify the project.
12555
12556 The current list of qualifiers is:
12557
12558 @itemize @bullet
12559 @item
12560 @code{abstract}: qualify a project with no sources. An abstract project must
12561 have a declaration specifying that there are no sources in the project, and,
12562 if it extends another project, the project it extends must also be a qualified
12563 abstract project.
12564
12565 @item
12566 @code{standard}: a standard project is a non library project with sources.
12567
12568 @item
12569 @code{aggregate}: for future extension
12570
12571 @item
12572 @code{aggregate library}: for future extension
12573
12574 @item
12575 @code{library}: a library project must declare both attributes
12576 @code{Library_Name} and @code{Library_Dir}.
12577
12578 @item
12579 @code{configuration}: a configuration project cannot be in a project tree.
12580 @end itemize
12581
12582 @node Packages
12583 @subsection Packages
12584
12585 @noindent
12586 A project file may contain @emph{packages}. The name of a package must be one
12587 of the identifiers from the following list. A package
12588 with a given name may only appear once in a project file. Package names are
12589 case insensitive. The following package names are legal:
12590
12591 @itemize @bullet
12592 @item
12593 @code{Naming}
12594 @item
12595 @code{Builder}
12596 @item
12597 @code{Compiler}
12598 @item
12599 @code{Binder}
12600 @item
12601 @code{Linker}
12602 @item
12603 @code{Finder}
12604 @item
12605 @code{Cross_Reference}
12606 @item
12607 @code{Eliminate}
12608 @item
12609 @code{Pretty_Printer}
12610 @item
12611 @code{Metrics}
12612 @item
12613 @code{gnatls}
12614 @item
12615 @code{gnatstub}
12616 @item
12617 @code{IDE}
12618 @item
12619 @code{Language_Processing}
12620 @end itemize
12621
12622 @noindent
12623 In its simplest form, a package may be empty:
12624
12625 @smallexample @c projectfile
12626 @group
12627 project Simple is
12628   package Builder is
12629   end Builder;
12630 end Simple;
12631 @end group
12632 @end smallexample
12633
12634 @noindent
12635 A package may contain @emph{attribute declarations},
12636 @emph{variable declarations} and @emph{case constructions}, as will be
12637 described below.
12638
12639 When there is ambiguity between a project name and a package name,
12640 the name always designates the project. To avoid possible confusion, it is
12641 always a good idea to avoid naming a project with one of the
12642 names allowed for packages or any name that starts with @code{gnat}.
12643
12644 @node Expressions
12645 @subsection Expressions
12646
12647 @noindent
12648 An @emph{expression} is either a @emph{string expression} or a
12649 @emph{string list expression}.
12650
12651 A @emph{string expression} is either a @emph{simple string expression} or a
12652 @emph{compound string expression}.
12653
12654 A @emph{simple string expression} is one of the following:
12655 @itemize @bullet
12656 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12657 @item A string-valued variable reference (@pxref{Variables})
12658 @item A string-valued attribute reference (@pxref{Attributes})
12659 @item An external reference (@pxref{External References in Project Files})
12660 @end itemize
12661
12662 @noindent
12663 A @emph{compound string expression} is a concatenation of string expressions,
12664 using the operator @code{"&"}
12665 @smallexample
12666        Path & "/" & File_Name & ".ads"
12667 @end smallexample
12668
12669 @noindent
12670 A @emph{string list expression} is either a
12671 @emph{simple string list expression} or a
12672 @emph{compound string list expression}.
12673
12674 A @emph{simple string list expression} is one of the following:
12675 @itemize @bullet
12676 @item A parenthesized list of zero or more string expressions,
12677 separated by commas
12678 @smallexample
12679    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12680    Empty_List := ();
12681 @end smallexample
12682 @item A string list-valued variable reference
12683 @item A string list-valued attribute reference
12684 @end itemize
12685
12686 @noindent
12687 A @emph{compound string list expression} is the concatenation (using
12688 @code{"&"}) of a simple string list expression and an expression.  Note that
12689 each term in a compound string list expression, except the first, may be
12690 either a string expression or a string list expression.
12691
12692 @smallexample @c projectfile
12693 @group
12694    File_Name_List := () & File_Name; --  One string in this list
12695    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12696    --  Two strings
12697    Big_List := File_Name_List & Extended_File_Name_List;
12698    --  Concatenation of two string lists: three strings
12699    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12700    --  Illegal: must start with a string list
12701 @end group
12702 @end smallexample
12703
12704 @node String Types
12705 @subsection String Types
12706
12707 @noindent
12708 A @emph{string type declaration} introduces a discrete set of string literals.
12709 If a string variable is declared to have this type, its value
12710 is restricted to the given set of literals.
12711
12712 Here is an example of a string type declaration:
12713
12714 @smallexample @c projectfile
12715    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12716 @end smallexample
12717
12718 @noindent
12719 Variables of a string type are called @emph{typed variables}; all other
12720 variables are called @emph{untyped variables}. Typed variables are
12721 particularly useful in @code{case} constructions, to support conditional
12722 attribute declarations.
12723 (@pxref{case Constructions}).
12724
12725 The string literals in the list are case sensitive and must all be different.
12726 They may include any graphic characters allowed in Ada, including spaces.
12727
12728 A string type may only be declared at the project level, not inside a package.
12729
12730 A string type may be referenced by its name if it has been declared in the same
12731 project file, or by an expanded name whose prefix is the name of the project
12732 in which it is declared.
12733
12734 @node Variables
12735 @subsection Variables
12736
12737 @noindent
12738 A variable may be declared at the project file level, or within a package.
12739 Here are some examples of variable declarations:
12740
12741 @smallexample @c projectfile
12742 @group
12743    This_OS : OS := external ("OS"); --  a typed variable declaration
12744    That_OS := "GNU/Linux";          --  an untyped variable declaration
12745 @end group
12746 @end smallexample
12747
12748 @noindent
12749 The syntax of a @emph{typed variable declaration} is identical to the Ada
12750 syntax for an object declaration. By contrast, the syntax of an untyped
12751 variable declaration is identical to an Ada assignment statement. In fact,
12752 variable declarations in project files have some of the characteristics of
12753 an assignment, in that successive declarations for the same variable are
12754 allowed. Untyped variable declarations do establish the expected kind of the
12755 variable (string or string list), and successive declarations for it must
12756 respect the initial kind.
12757
12758 @noindent
12759 A string variable declaration (typed or untyped) declares a variable
12760 whose value is a string. This variable may be used as a string expression.
12761 @smallexample @c projectfile
12762    File_Name       := "readme.txt";
12763    Saved_File_Name := File_Name & ".saved";
12764 @end smallexample
12765
12766 @noindent
12767 A string list variable declaration declares a variable whose value is a list
12768 of strings. The list may contain any number (zero or more) of strings.
12769
12770 @smallexample @c projectfile
12771    Empty_List := ();
12772    List_With_One_Element := ("^-gnaty^-gnaty^");
12773    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12774    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12775                  "pack2.ada", "util_.ada", "util.ada");
12776 @end smallexample
12777
12778 @noindent
12779 The same typed variable may not be declared more than once at project level,
12780 and it may not be declared more than once in any package; it is in effect
12781 a constant.
12782
12783 The same untyped variable may be declared several times. Declarations are
12784 elaborated in the order in which they appear, so  the new value replaces
12785 the old one, and any subsequent reference to the variable uses the new value.
12786 However, as noted above, if a variable has been declared as a string, all
12787 subsequent
12788 declarations must give it a string value. Similarly, if a variable has
12789 been declared as a string list, all subsequent declarations
12790 must give it a string list value.
12791
12792 A @emph{variable reference} may take several forms:
12793
12794 @itemize @bullet
12795 @item The simple variable name, for a variable in the current package (if any)
12796 or in the current project
12797 @item An expanded name, whose prefix is a context name.
12798 @end itemize
12799
12800 @noindent
12801 A @emph{context} may be one of the following:
12802
12803 @itemize @bullet
12804 @item The name of an existing package in the current project
12805 @item The name of an imported project of the current project
12806 @item The name of an ancestor project (i.e., a project extended by the current
12807 project, either directly or indirectly)
12808 @item An expanded name whose prefix is an imported/parent project name, and
12809 whose selector is a package name in that project.
12810 @end itemize
12811
12812 @noindent
12813 A variable reference may be used in an expression.
12814
12815 @node Attributes
12816 @subsection Attributes
12817
12818 @noindent
12819 A project (and its packages) may have @emph{attributes} that define
12820 the project's properties.  Some attributes have values that are strings;
12821 others have values that are string lists.
12822
12823 There are two categories of attributes: @emph{simple attributes}
12824 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12825
12826 Legal project attribute names, and attribute names for each legal package are
12827 listed below. Attributes names are case-insensitive.
12828
12829 The following attributes are defined on projects (all are simple attributes):
12830
12831 @multitable @columnfractions .4 .3
12832 @item @emph{Attribute Name}
12833 @tab @emph{Value}
12834 @item @code{Source_Files}
12835 @tab string list
12836 @item @code{Source_Dirs}
12837 @tab string list
12838 @item @code{Source_List_File}
12839 @tab string
12840 @item @code{Object_Dir}
12841 @tab string
12842 @item @code{Exec_Dir}
12843 @tab string
12844 @item @code{Excluded_Source_Dirs}
12845 @tab string list
12846 @item @code{Excluded_Source_Files}
12847 @tab string list
12848 @item @code{Excluded_Source_List_File}
12849 @tab string
12850 @item @code{Languages}
12851 @tab string list
12852 @item @code{Main}
12853 @tab string list
12854 @item @code{Library_Dir}
12855 @tab string
12856 @item @code{Library_Name}
12857 @tab string
12858 @item @code{Library_Kind}
12859 @tab string
12860 @item @code{Library_Version}
12861 @tab string
12862 @item @code{Library_Interface}
12863 @tab string
12864 @item @code{Library_Auto_Init}
12865 @tab string
12866 @item @code{Library_Options}
12867 @tab string list
12868 @item @code{Library_Src_Dir}
12869 @tab string
12870 @item @code{Library_ALI_Dir}
12871 @tab string
12872 @item @code{Library_GCC}
12873 @tab string
12874 @item @code{Library_Symbol_File}
12875 @tab string
12876 @item @code{Library_Symbol_Policy}
12877 @tab string
12878 @item @code{Library_Reference_Symbol_File}
12879 @tab string
12880 @item @code{Externally_Built}
12881 @tab string
12882 @end multitable
12883
12884 @noindent
12885 The following attributes are defined for package  @code{Naming}
12886 (@pxref{Naming Schemes}):
12887
12888 @multitable @columnfractions .4 .2 .2 .2
12889 @item Attribute Name @tab Category @tab Index @tab Value
12890 @item @code{Spec_Suffix}
12891 @tab associative array
12892 @tab language name
12893 @tab string
12894 @item @code{Body_Suffix}
12895 @tab associative array
12896 @tab language name
12897 @tab string
12898 @item @code{Separate_Suffix}
12899 @tab simple attribute
12900 @tab n/a
12901 @tab string
12902 @item @code{Casing}
12903 @tab simple attribute
12904 @tab n/a
12905 @tab string
12906 @item @code{Dot_Replacement}
12907 @tab simple attribute
12908 @tab n/a
12909 @tab string
12910 @item @code{Spec}
12911 @tab associative array
12912 @tab Ada unit name
12913 @tab string
12914 @item @code{Body}
12915 @tab associative array
12916 @tab Ada unit name
12917 @tab string
12918 @item @code{Specification_Exceptions}
12919 @tab associative array
12920 @tab language name
12921 @tab string list
12922 @item @code{Implementation_Exceptions}
12923 @tab associative array
12924 @tab language name
12925 @tab string list
12926 @end multitable
12927
12928 @noindent
12929 The following attributes are defined for packages @code{Builder},
12930 @code{Compiler}, @code{Binder},
12931 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12932 (@pxref{^Switches^Switches^ and Project Files}).
12933
12934 @multitable @columnfractions .4 .2 .2 .2
12935 @item Attribute Name @tab Category @tab Index @tab Value
12936 @item @code{^Default_Switches^Default_Switches^}
12937 @tab associative array
12938 @tab language name
12939 @tab string list
12940 @item @code{^Switches^Switches^}
12941 @tab associative array
12942 @tab file name
12943 @tab string list
12944 @end multitable
12945
12946 @noindent
12947 In addition, package @code{Compiler} has a single string attribute
12948 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12949 string attribute @code{Global_Configuration_Pragmas}.
12950
12951 @noindent
12952 Each simple attribute has a default value: the empty string (for string-valued
12953 attributes) and the empty list (for string list-valued attributes).
12954
12955 An attribute declaration defines a new value for an attribute.
12956
12957 Examples of simple attribute declarations:
12958
12959 @smallexample @c projectfile
12960    for Object_Dir use "objects";
12961    for Source_Dirs use ("units", "test/drivers");
12962 @end smallexample
12963
12964 @noindent
12965 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12966 attribute definition clause in Ada.
12967
12968 Attributes references may be appear in expressions.
12969 The general form for such a reference is @code{<entity>'<attribute>}:
12970 Associative array attributes are functions. Associative
12971 array attribute references must have an argument that is a string literal.
12972
12973 Examples are:
12974
12975 @smallexample @c projectfile
12976   project'Object_Dir
12977   Naming'Dot_Replacement
12978   Imported_Project'Source_Dirs
12979   Imported_Project.Naming'Casing
12980   Builder'^Default_Switches^Default_Switches^("Ada")
12981 @end smallexample
12982
12983 @noindent
12984 The prefix of an attribute may be:
12985 @itemize @bullet
12986 @item @code{project} for an attribute of the current project
12987 @item The name of an existing package of the current project
12988 @item The name of an imported project
12989 @item The name of a parent project that is extended by the current project
12990 @item An expanded name whose prefix is imported/parent project name,
12991 and whose selector is a package name
12992 @end itemize
12993
12994 @noindent
12995 Example:
12996 @smallexample @c projectfile
12997 @group
12998    project Prj is
12999      for Source_Dirs use project'Source_Dirs & "units";
13000      for Source_Dirs use project'Source_Dirs & "test/drivers"
13001    end Prj;
13002 @end group
13003 @end smallexample
13004
13005 @noindent
13006 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13007 has the default value: an empty string list. After this declaration,
13008 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13009 After the second attribute declaration @code{Source_Dirs} is a string list of
13010 two elements: @code{"units"} and @code{"test/drivers"}.
13011
13012 Note: this example is for illustration only. In practice,
13013 the project file would contain only one attribute declaration:
13014
13015 @smallexample @c projectfile
13016    for Source_Dirs use ("units", "test/drivers");
13017 @end smallexample
13018
13019 @node Associative Array Attributes
13020 @subsection Associative Array Attributes
13021
13022 @noindent
13023 Some attributes are defined as @emph{associative arrays}. An associative
13024 array may be regarded as a function that takes a string as a parameter
13025 and delivers a string or string list value as its result.
13026
13027 Here are some examples of single associative array attribute associations:
13028
13029 @smallexample @c projectfile
13030    for Body ("main") use "Main.ada";
13031    for ^Switches^Switches^ ("main.ada")
13032        use ("^-v^-v^",
13033             "^-gnatv^-gnatv^");
13034    for ^Switches^Switches^ ("main.ada")
13035             use Builder'^Switches^Switches^ ("main.ada")
13036               & "^-g^-g^";
13037 @end smallexample
13038
13039 @noindent
13040 Like untyped variables and simple attributes, associative array attributes
13041 may be declared several times. Each declaration supplies a new value for the
13042 attribute, and replaces the previous setting.
13043
13044 @noindent
13045 An associative array attribute may be declared as a full associative array
13046 declaration, with the value of the same attribute in an imported or extended
13047 project.
13048
13049 @smallexample @c projectfile
13050    package Builder is
13051       for Default_Switches use Default.Builder'Default_Switches;
13052    end Builder;
13053 @end smallexample
13054
13055 @noindent
13056 In this example, @code{Default} must be either a project imported by the
13057 current project, or the project that the current project extends. If the
13058 attribute is in a package (in this case, in package @code{Builder}), the same
13059 package needs to be specified.
13060
13061 @noindent
13062 A full associative array declaration replaces any other declaration for the
13063 attribute, including other full associative array declaration. Single
13064 associative array associations may be declare after a full associative
13065 declaration, modifying the value for a single association of the attribute.
13066
13067 @node case Constructions
13068 @subsection @code{case} Constructions
13069
13070 @noindent
13071 A @code{case} construction is used in a project file to effect conditional
13072 behavior.
13073 Here is a typical example:
13074
13075 @smallexample @c projectfile
13076 @group
13077 project MyProj is
13078    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13079
13080    OS : OS_Type := external ("OS", "GNU/Linux");
13081 @end group
13082
13083 @group
13084    package Compiler is
13085      case OS is
13086        when "GNU/Linux" | "Unix" =>
13087          for ^Default_Switches^Default_Switches^ ("Ada")
13088              use ("^-gnath^-gnath^");
13089        when "NT" =>
13090          for ^Default_Switches^Default_Switches^ ("Ada")
13091              use ("^-gnatP^-gnatP^");
13092        when others =>
13093      end case;
13094    end Compiler;
13095 end MyProj;
13096 @end group
13097 @end smallexample
13098
13099 @noindent
13100 The syntax of a @code{case} construction is based on the Ada case statement
13101 (although there is no @code{null} construction for empty alternatives).
13102
13103 The case expression must be a typed string variable.
13104 Each alternative comprises the reserved word @code{when}, either a list of
13105 literal strings separated by the @code{"|"} character or the reserved word
13106 @code{others},  and the @code{"=>"} token.
13107 Each literal string must belong to the string type that is the type of the
13108 case variable.
13109 An @code{others} alternative, if present, must occur last.
13110
13111 After each @code{=>}, there are zero or more constructions.  The only
13112 constructions allowed in a case construction are other case constructions,
13113 attribute declarations and variable declarations. String type declarations and
13114 package declarations are not allowed. Variable declarations are restricted to
13115 variables that have already been declared before the case construction.
13116
13117 The value of the case variable is often given by an external reference
13118 (@pxref{External References in Project Files}).
13119
13120 @c ****************************************
13121 @c * Objects and Sources in Project Files *
13122 @c ****************************************
13123
13124 @node Objects and Sources in Project Files
13125 @section Objects and Sources in Project Files
13126
13127 @menu
13128 * Object Directory::
13129 * Exec Directory::
13130 * Source Directories::
13131 * Source File Names::
13132 @end menu
13133
13134 @noindent
13135 Each project has exactly one object directory and one or more source
13136 directories. The source directories must contain at least one source file,
13137 unless  the project file explicitly specifies that no source files are present
13138 (@pxref{Source File Names}).
13139
13140 @node Object Directory
13141 @subsection Object Directory
13142
13143 @noindent
13144 The object directory for a project is the directory containing the compiler's
13145 output (such as @file{ALI} files and object files) for the project's immediate
13146 sources.
13147
13148 The object directory is given by the value of the attribute @code{Object_Dir}
13149 in the project file.
13150
13151 @smallexample @c projectfile
13152    for Object_Dir use "objects";
13153 @end smallexample
13154
13155 @noindent
13156 The attribute @code{Object_Dir} has a string value, the path name of the object
13157 directory. The path name may be absolute or relative to the directory of the
13158 project file. This directory must already exist, and be readable and writable.
13159
13160 By default, when the attribute @code{Object_Dir} is not given an explicit value
13161 or when its value is the empty string, the object directory is the same as the
13162 directory containing the project file.
13163
13164 @node Exec Directory
13165 @subsection Exec Directory
13166
13167 @noindent
13168 The exec directory for a project is the directory containing the executables
13169 for the project's main subprograms.
13170
13171 The exec directory is given by the value of the attribute @code{Exec_Dir}
13172 in the project file.
13173
13174 @smallexample @c projectfile
13175    for Exec_Dir use "executables";
13176 @end smallexample
13177
13178 @noindent
13179 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13180 directory. The path name may be absolute or relative to the directory of the
13181 project file. This directory must already exist, and be writable.
13182
13183 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13184 or when its value is the empty string, the exec directory is the same as the
13185 object directory of the project file.
13186
13187 @node Source Directories
13188 @subsection Source Directories
13189
13190 @noindent
13191 The source directories of a project are specified by the project file
13192 attribute @code{Source_Dirs}.
13193
13194 This attribute's value is a string list. If the attribute is not given an
13195 explicit value, then there is only one source directory, the one where the
13196 project file resides.
13197
13198 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13199 as in
13200
13201 @smallexample @c projectfile
13202     for Source_Dirs use ();
13203 @end smallexample
13204
13205 @noindent
13206 indicates that the project contains no source files.
13207
13208 Otherwise, each string in the string list designates one or more
13209 source directories.
13210
13211 @smallexample @c projectfile
13212    for Source_Dirs use ("sources", "test/drivers");
13213 @end smallexample
13214
13215 @noindent
13216 If a string in the list ends with @code{"/**"},  then the directory whose path
13217 name precedes the two asterisks, as well as all its subdirectories
13218 (recursively), are source directories.
13219
13220 @smallexample @c projectfile
13221    for Source_Dirs use ("/system/sources/**");
13222 @end smallexample
13223
13224 @noindent
13225 Here the directory @code{/system/sources} and all of its subdirectories
13226 (recursively) are source directories.
13227
13228 To specify that the source directories are the directory of the project file
13229 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13230 @smallexample @c projectfile
13231    for Source_Dirs use ("./**");
13232 @end smallexample
13233
13234 @noindent
13235 Each of the source directories must exist and be readable.
13236
13237 @node Source File Names
13238 @subsection Source File Names
13239
13240 @noindent
13241 In a project that contains source files, their names may be specified by the
13242 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13243 (a string). Source file names never include any directory information.
13244
13245 If the attribute @code{Source_Files} is given an explicit value, then each
13246 element of the list is a source file name.
13247
13248 @smallexample @c projectfile
13249    for Source_Files use ("main.adb");
13250    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13251 @end smallexample
13252
13253 @noindent
13254 If the attribute @code{Source_Files} is not given an explicit value,
13255 but the attribute @code{Source_List_File} is given a string value,
13256 then the source file names are contained in the text file whose path name
13257 (absolute or relative to the directory of the project file) is the
13258 value of the attribute @code{Source_List_File}.
13259
13260 Each line in the file that is not empty or is not a comment
13261 contains a source file name.
13262
13263 @smallexample @c projectfile
13264    for Source_List_File use "source_list.txt";
13265 @end smallexample
13266
13267 @noindent
13268 By default, if neither the attribute @code{Source_Files} nor the attribute
13269 @code{Source_List_File} is given an explicit value, then each file in the
13270 source directories that conforms to the project's naming scheme
13271 (@pxref{Naming Schemes}) is an immediate source of the project.
13272
13273 A warning is issued if both attributes @code{Source_Files} and
13274 @code{Source_List_File} are given explicit values. In this case, the attribute
13275 @code{Source_Files} prevails.
13276
13277 Each source file name must be the name of one existing source file
13278 in one of the source directories.
13279
13280 A @code{Source_Files} attribute whose value is an empty list
13281 indicates that there are no source files in the project.
13282
13283 If the order of the source directories is known statically, that is if
13284 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13285 be several files with the same source file name. In this case, only the file
13286 in the first directory is considered as an immediate source of the project
13287 file. If the order of the source directories is not known statically, it is
13288 an error to have several files with the same source file name.
13289
13290 Projects can be specified to have no Ada source
13291 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
13292 list, or the @code{"Ada"} may be absent from @code{Languages}:
13293
13294 @smallexample @c projectfile
13295    for Source_Dirs use ();
13296    for Source_Files use ();
13297    for Languages use ("C", "C++");
13298 @end smallexample
13299
13300 @noindent
13301 Otherwise, a project must contain at least one immediate source.
13302
13303 Projects with no source files are useful as template packages
13304 (@pxref{Packages in Project Files}) for other projects; in particular to
13305 define a package @code{Naming} (@pxref{Naming Schemes}).
13306
13307 @c ****************************
13308 @c * Importing Projects *
13309 @c ****************************
13310
13311 @node  Importing Projects
13312 @section Importing Projects
13313 @cindex @code{ADA_PROJECT_PATH}
13314
13315 @noindent
13316 An immediate source of a project P may depend on source files that
13317 are neither immediate sources of P nor in the predefined library.
13318 To get this effect, P must @emph{import} the projects that contain the needed
13319 source files.
13320
13321 @smallexample @c projectfile
13322 @group
13323   with "project1", "utilities.gpr";
13324   with "/namings/apex.gpr";
13325   project Main is
13326     @dots{}
13327 @end group
13328 @end smallexample
13329
13330 @noindent
13331 As can be seen in this example, the syntax for importing projects is similar
13332 to the syntax for importing compilation units in Ada. However, project files
13333 use literal strings instead of names, and the @code{with} clause identifies
13334 project files rather than packages.
13335
13336 Each literal string is the file name or path name (absolute or relative) of a
13337 project file. If a string corresponds to a file name, with no path or a
13338 relative path, then its location is determined by the @emph{project path}. The
13339 latter can be queried using @code{gnatls -v}. It contains:
13340
13341 @itemize @bullet
13342 @item
13343 In first position, the directory containing the current project file.
13344 @item
13345 In last position, the default project directory. This default project directory
13346 is part of the GNAT installation and is the standard place to install project
13347 files giving access to standard support libraries.
13348 @ifclear vms
13349 @ref{Installing a library}
13350 @end ifclear
13351
13352 @item
13353 In between, all the directories referenced in the
13354 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13355 @end itemize
13356
13357 @noindent
13358 If a relative pathname is used, as in
13359
13360 @smallexample @c projectfile
13361   with "tests/proj";
13362 @end smallexample
13363
13364 @noindent
13365 then the full path for the project is constructed by concatenating this
13366 relative path to those in the project path, in order, until a matching file is
13367 found. Any symbolic link will be fully resolved in the directory of the
13368 importing project file before the imported project file is examined.
13369
13370 If the @code{with}'ed project file name does not have an extension,
13371 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13372 then the file name as specified in the @code{with} clause (no extension) will
13373 be used. In the above example, if a file @code{project1.gpr} is found, then it
13374 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13375 then it will be used; if neither file exists, this is an error.
13376
13377 A warning is issued if the name of the project file does not match the
13378 name of the project; this check is case insensitive.
13379
13380 Any source file that is an immediate source of the imported project can be
13381 used by the immediate sources of the importing project, transitively. Thus
13382 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13383 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13384 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13385 because if and when @code{B} ceases to import @code{C}, some sources in
13386 @code{A} will no longer compile.
13387
13388 A side effect of this capability is that normally cyclic dependencies are not
13389 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13390 is not allowed to import @code{A}. However, there are cases when cyclic
13391 dependencies would be beneficial. For these cases, another form of import
13392 between projects exists, the @code{limited with}: a project @code{A} that
13393 imports a project @code{B} with a straight @code{with} may also be imported,
13394 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13395 to @code{A} include at least one @code{limited with}.
13396
13397 @smallexample @c 0projectfile
13398 with "../b/b.gpr";
13399 with "../c/c.gpr";
13400 project A is
13401 end A;
13402
13403 limited with "../a/a.gpr";
13404 project B is
13405 end B;
13406
13407 with "../d/d.gpr";
13408 project C is
13409 end C;
13410
13411 limited with "../a/a.gpr";
13412 project D is
13413 end D;
13414 @end smallexample
13415
13416 @noindent
13417 In the above legal example, there are two project cycles:
13418 @itemize @bullet
13419 @item A-> B-> A
13420 @item A -> C -> D -> A
13421 @end itemize
13422
13423 @noindent
13424 In each of these cycle there is one @code{limited with}: import of @code{A}
13425 from @code{B} and import of @code{A} from @code{D}.
13426
13427 The difference between straight @code{with} and @code{limited with} is that
13428 the name of a project imported with a @code{limited with} cannot be used in the
13429 project that imports it. In particular, its packages cannot be renamed and
13430 its variables cannot be referred to.
13431
13432 An exception to the above rules for @code{limited with} is that for the main
13433 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13434 @code{limited with} is equivalent to a straight @code{with}. For example,
13435 in the example above, projects @code{B} and @code{D} could not be main
13436 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13437 each have a @code{limited with} that is the only one in a cycle of importing
13438 projects.
13439
13440 @c *********************
13441 @c * Project Extension *
13442 @c *********************
13443
13444 @node Project Extension
13445 @section Project Extension
13446
13447 @noindent
13448 During development of a large system, it is sometimes necessary to use
13449 modified versions of some of the source files, without changing the original
13450 sources. This can be achieved through the @emph{project extension} facility.
13451
13452 @smallexample @c projectfile
13453    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13454 @end smallexample
13455
13456 @noindent
13457 A project extension declaration introduces an extending project
13458 (the @emph{child}) and a project being extended (the @emph{parent}).
13459
13460 By default, a child project inherits all the sources of its parent.
13461 However, inherited sources can be overridden: a unit in a parent is hidden
13462 by a unit of the same name in the child.
13463
13464 Inherited sources are considered to be sources (but not immediate sources)
13465 of the child project; see @ref{Project File Syntax}.
13466
13467 An inherited source file retains any switches specified in the parent project.
13468
13469 For example if the project @code{Utilities} contains the spec and the
13470 body of an Ada package @code{Util_IO}, then the project
13471 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13472 The original body of @code{Util_IO} will not be considered in program builds.
13473 However, the package spec will still be found in the project
13474 @code{Utilities}.
13475
13476 A child project can have only one parent, except when it is qualified as
13477 abstract. But it may import any number of other projects.
13478
13479 A project is not allowed to import directly or indirectly at the same time a
13480 child project and any of its ancestors.
13481
13482 @c *******************************
13483 @c * Project Hierarchy Extension *
13484 @c *******************************
13485
13486 @node Project Hierarchy Extension
13487 @section Project Hierarchy Extension
13488
13489 @noindent
13490 When extending a large system spanning multiple projects, it is often
13491 inconvenient to extend every project in the hierarchy that is impacted by a
13492 small change introduced. In such cases, it is possible to create a virtual
13493 extension of entire hierarchy using @code{extends all} relationship.
13494
13495 When the project is extended using @code{extends all} inheritance, all projects
13496 that are imported by it, both directly and indirectly, are considered virtually
13497 extended. That is, the Project Manager creates "virtual projects"
13498 that extend every project in the hierarchy; all these virtual projects have
13499 no sources of their own and have as object directory the object directory of
13500 the root of "extending all" project.
13501
13502 It is possible to explicitly extend one or more projects in the hierarchy
13503 in order to modify the sources. These extending projects must be imported by
13504 the "extending all" project, which will replace the corresponding virtual
13505 projects with the explicit ones.
13506
13507 When building such a project hierarchy extension, the Project Manager will
13508 ensure that both modified sources and sources in virtual extending projects
13509 that depend on them, are recompiled.
13510
13511 By means of example, consider the following hierarchy of projects.
13512
13513 @enumerate
13514 @item
13515 project A, containing package P1
13516 @item
13517 project B importing A and containing package P2 which depends on P1
13518 @item
13519 project C importing B and containing package P3 which depends on P2
13520 @end enumerate
13521
13522 @noindent
13523 We want to modify packages P1 and P3.
13524
13525 This project hierarchy will need to be extended as follows:
13526
13527 @enumerate
13528 @item
13529 Create project A1 that extends A, placing modified P1 there:
13530
13531 @smallexample @c 0projectfile
13532 project A1 extends "(@dots{})/A" is
13533 end A1;
13534 @end smallexample
13535
13536 @item
13537 Create project C1 that "extends all" C and imports A1, placing modified
13538 P3 there:
13539
13540 @smallexample @c 0projectfile
13541 with "(@dots{})/A1";
13542 project C1 extends all "(@dots{})/C" is
13543 end C1;
13544 @end smallexample
13545 @end enumerate
13546
13547 When you build project C1, your entire modified project space will be
13548 recompiled, including the virtual project B1 that has been impacted by the
13549 "extending all" inheritance of project C.
13550
13551 Note that if a Library Project in the hierarchy is virtually extended,
13552 the virtual project that extends the Library Project is not a Library Project.
13553
13554 @c ****************************************
13555 @c * External References in Project Files *
13556 @c ****************************************
13557
13558 @node  External References in Project Files
13559 @section External References in Project Files
13560
13561 @noindent
13562 A project file may contain references to external variables; such references
13563 are called @emph{external references}.
13564
13565 An external variable is either defined as part of the environment (an
13566 environment variable in Unix, for example) or else specified on the command
13567 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13568 If both, then the command line value is used.
13569
13570 The value of an external reference is obtained by means of the built-in
13571 function @code{external}, which returns a string value.
13572 This function has two forms:
13573 @itemize @bullet
13574 @item @code{external (external_variable_name)}
13575 @item @code{external (external_variable_name, default_value)}
13576 @end itemize
13577
13578 @noindent
13579 Each parameter must be a string literal.  For example:
13580
13581 @smallexample @c projectfile
13582    external ("USER")
13583    external ("OS", "GNU/Linux")
13584 @end smallexample
13585
13586 @noindent
13587 In the form with one parameter, the function returns the value of
13588 the external variable given as parameter. If this name is not present in the
13589 environment, the function returns an empty string.
13590
13591 In the form with two string parameters, the second argument is
13592 the value returned when the variable given as the first argument is not
13593 present in the environment. In the example above, if @code{"OS"} is not
13594 the name of ^an environment variable^a logical name^ and is not passed on
13595 the command line, then the returned value is @code{"GNU/Linux"}.
13596
13597 An external reference may be part of a string expression or of a string
13598 list expression, and can therefore appear in a variable declaration or
13599 an attribute declaration.
13600
13601 @smallexample @c projectfile
13602 @group
13603    type Mode_Type is ("Debug", "Release");
13604    Mode : Mode_Type := external ("MODE");
13605    case Mode is
13606      when "Debug" =>
13607         @dots{}
13608 @end group
13609 @end smallexample
13610
13611 @c *****************************
13612 @c * Packages in Project Files *
13613 @c *****************************
13614
13615 @node  Packages in Project Files
13616 @section Packages in Project Files
13617
13618 @noindent
13619 A @emph{package} defines the settings for project-aware tools within a
13620 project.
13621 For each such tool one can declare a package; the names for these
13622 packages are preset (@pxref{Packages}).
13623 A package may contain variable declarations, attribute declarations, and case
13624 constructions.
13625
13626 @smallexample @c projectfile
13627 @group
13628    project Proj is
13629       package Builder is  -- used by gnatmake
13630          for ^Default_Switches^Default_Switches^ ("Ada")
13631              use ("^-v^-v^",
13632                   "^-g^-g^");
13633       end Builder;
13634    end Proj;
13635 @end group
13636 @end smallexample
13637
13638 @noindent
13639 The syntax of package declarations mimics that of package in Ada.
13640
13641 Most of the packages have an attribute
13642 @code{^Default_Switches^Default_Switches^}.
13643 This attribute is an associative array, and its value is a string list.
13644 The index of the associative array is the name of a programming language (case
13645 insensitive). This attribute indicates the ^switch^switch^
13646 or ^switches^switches^ to be used
13647 with the corresponding tool.
13648
13649 Some packages also have another attribute, @code{^Switches^Switches^},
13650 an associative array whose value is a string list.
13651 The index is the name of a source file.
13652 This attribute indicates the ^switch^switch^
13653 or ^switches^switches^ to be used by the corresponding
13654 tool when dealing with this specific file.
13655
13656 Further information on these ^switch^switch^-related attributes is found in
13657 @ref{^Switches^Switches^ and Project Files}.
13658
13659 A package may be declared as a @emph{renaming} of another package; e.g., from
13660 the project file for an imported project.
13661
13662 @smallexample @c projectfile
13663 @group
13664   with "/global/apex.gpr";
13665   project Example is
13666     package Naming renames Apex.Naming;
13667     @dots{}
13668   end Example;
13669 @end group
13670 @end smallexample
13671
13672 @noindent
13673 Packages that are renamed in other project files often come from project files
13674 that have no sources: they are just used as templates. Any modification in the
13675 template will be reflected automatically in all the project files that rename
13676 a package from the template.
13677
13678 In addition to the tool-oriented packages, you can also declare a package
13679 named @code{Naming} to establish specialized source file naming conventions
13680 (@pxref{Naming Schemes}).
13681
13682 @c ************************************
13683 @c * Variables from Imported Projects *
13684 @c ************************************
13685
13686 @node Variables from Imported Projects
13687 @section Variables from Imported Projects
13688
13689 @noindent
13690 An attribute or variable defined in an imported or parent project can
13691 be used in expressions in the importing / extending project.
13692 Such an attribute or variable is denoted by an expanded name whose prefix
13693 is either the name of the project or the expanded name of a package within
13694 a project.
13695
13696 @smallexample @c projectfile
13697 @group
13698   with "imported";
13699   project Main extends "base" is
13700      Var1 := Imported.Var;
13701      Var2 := Base.Var & ".new";
13702 @end group
13703
13704 @group
13705      package Builder is
13706         for ^Default_Switches^Default_Switches^ ("Ada")
13707             use Imported.Builder'Ada_^Switches^Switches^ &
13708                 "^-gnatg^-gnatg^" &
13709                 "^-v^-v^";
13710      end Builder;
13711 @end group
13712
13713 @group
13714      package Compiler is
13715         for ^Default_Switches^Default_Switches^ ("Ada")
13716             use Base.Compiler'Ada_^Switches^Switches^;
13717      end Compiler;
13718   end Main;
13719 @end group
13720 @end smallexample
13721
13722 @noindent
13723 In this example:
13724
13725 @itemize @bullet
13726 @item
13727 The value of @code{Var1} is a copy of the variable @code{Var} defined
13728 in the project file @file{"imported.gpr"}
13729 @item
13730 the value of @code{Var2} is a copy of the value of variable @code{Var}
13731 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13732 @item
13733 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13734 @code{Builder} is a string list that includes in its value a copy of the value
13735 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13736 in project file @file{imported.gpr} plus two new elements:
13737 @option{"^-gnatg^-gnatg^"}
13738 and @option{"^-v^-v^"};
13739 @item
13740 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13741 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13742 defined in the @code{Compiler} package in project file @file{base.gpr},
13743 the project being extended.
13744 @end itemize
13745
13746 @c ******************
13747 @c * Naming Schemes *
13748 @c ******************
13749
13750 @node  Naming Schemes
13751 @section Naming Schemes
13752
13753 @noindent
13754 Sometimes an Ada software system is ported from a foreign compilation
13755 environment to GNAT, and the file names do not use the default GNAT
13756 conventions. Instead of changing all the file names (which for a variety
13757 of reasons might not be possible), you can define the relevant file
13758 naming scheme in the @code{Naming} package in your project file.
13759
13760 @noindent
13761 Note that the use of pragmas described in
13762 @ref{Alternative File Naming Schemes} by mean of a configuration
13763 pragmas file is not supported when using project files. You must use
13764 the features described in this paragraph. You can however use specify
13765 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13766
13767 @ifclear vms
13768 For example, the following
13769 package models the Apex file naming rules:
13770
13771 @smallexample @c projectfile
13772 @group
13773   package Naming is
13774     for Casing               use "lowercase";
13775     for Dot_Replacement      use ".";
13776     for Spec_Suffix ("Ada")  use ".1.ada";
13777     for Body_Suffix ("Ada")  use ".2.ada";
13778   end Naming;
13779 @end group
13780 @end smallexample
13781 @end ifclear
13782
13783 @ifset vms
13784 For example, the following package models the HP Ada file naming rules:
13785
13786 @smallexample @c projectfile
13787 @group
13788   package Naming is
13789     for Casing               use "lowercase";
13790     for Dot_Replacement      use "__";
13791     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13792     for Body_Suffix ("Ada")  use ".^ada^ada^";
13793   end Naming;
13794 @end group
13795 @end smallexample
13796
13797 @noindent
13798 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13799 names in lower case)
13800 @end ifset
13801
13802 @noindent
13803 You can define the following attributes in package @code{Naming}:
13804
13805 @table @code
13806
13807 @item @code{Casing}
13808 This must be a string with one of the three values @code{"lowercase"},
13809 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13810
13811 @noindent
13812 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13813
13814 @item @code{Dot_Replacement}
13815 This must be a string whose value satisfies the following conditions:
13816
13817 @itemize @bullet
13818 @item It must not be empty
13819 @item It cannot start or end with an alphanumeric character
13820 @item It cannot be a single underscore
13821 @item It cannot start with an underscore followed by an alphanumeric
13822 @item It cannot contain a dot @code{'.'} except if the entire string
13823 is @code{"."}
13824 @end itemize
13825
13826 @noindent
13827 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13828
13829 @item @code{Spec_Suffix}
13830 This is an associative array (indexed by the programming language name, case
13831 insensitive) whose value is a string that must satisfy the following
13832 conditions:
13833
13834 @itemize @bullet
13835 @item It must not be empty
13836 @item It must include at least one dot
13837 @end itemize
13838 @noindent
13839 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13840 @code{"^.ads^.ADS^"}.
13841
13842 @item @code{Body_Suffix}
13843 This is an associative array (indexed by the programming language name, case
13844 insensitive) whose value is a string that must satisfy the following
13845 conditions:
13846
13847 @itemize @bullet
13848 @item It must not be empty
13849 @item It must include at least one dot
13850 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13851 @end itemize
13852 @noindent
13853 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13854 same string, then a file name that ends with the longest of these two suffixes
13855 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13856 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13857
13858 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13859 @code{"^.adb^.ADB^"}.
13860
13861 @item @code{Separate_Suffix}
13862 This must be a string whose value satisfies the same conditions as
13863 @code{Body_Suffix}. The same "longest suffix" rules apply.
13864
13865 @noindent
13866 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13867 value as @code{Body_Suffix ("Ada")}.
13868
13869 @item @code{Spec}
13870 @noindent
13871 You can use the associative array attribute @code{Spec}  to define
13872 the source file name for an individual Ada compilation unit's spec. The array
13873 index must be a string literal that identifies the Ada unit (case insensitive).
13874 The value of this attribute must be a string that identifies the file that
13875 contains this unit's spec (case sensitive or insensitive depending on the
13876 operating system).
13877
13878 @smallexample @c projectfile
13879    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13880 @end smallexample
13881
13882 When the source file contains several units, you can indicate at what
13883 position the unit occurs in the file, with the following. The first unit
13884 in the file has index 1
13885
13886 @smallexample @c projectfile
13887   for Body ("top") use "foo.a" at 1;
13888   for Body ("foo") use "foo.a" at 2;
13889 @end smallexample
13890
13891 @item @code{Body}
13892
13893 You can use the associative array attribute @code{Body} to
13894 define the source file name for an individual Ada compilation unit's body
13895 (possibly a subunit).  The array index must be a string literal that identifies
13896 the Ada unit (case insensitive).  The value of this attribute must be a string
13897 that identifies the file that contains this unit's body or subunit (case
13898 sensitive or insensitive depending on the operating system).
13899
13900 @smallexample @c projectfile
13901    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13902 @end smallexample
13903 @end table
13904
13905 @c ********************
13906 @c * Library Projects *
13907 @c ********************
13908
13909 @node Library Projects
13910 @section Library Projects
13911
13912 @noindent
13913 @emph{Library projects} are projects whose object code is placed in a library.
13914 (Note that this facility is not yet supported on all platforms).
13915
13916 @code{gnatmake} or @code{gprbuild} will collect all object files into a
13917 single archive, which might either be a shared or a static library. This
13918 library can later on be linked with multiple executables, potentially
13919 reducing their sizes.
13920
13921 If your project file specifies languages other than Ada, but you are still
13922 using @code{gnatmake} to compile and link, the latter will not try to
13923 compile your sources other than Ada (you should use @code{gprbuild} if that
13924 is your intent). However, @code{gnatmake} will automatically link all object
13925 files found in the object directory, whether or not they were compiled from
13926 an Ada source file. This specific behavior only applies when multiple
13927 languages are specified.
13928
13929 To create a library project, you need to define in its project file
13930 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13931 Additionally, you may define other library-related attributes such as
13932 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13933 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13934
13935 The @code{Library_Name} attribute has a string value. There is no restriction
13936 on the name of a library. It is the responsibility of the developer to
13937 choose a name that will be accepted by the platform. It is recommended to
13938 choose names that could be Ada identifiers; such names are almost guaranteed
13939 to be acceptable on all platforms.
13940
13941 The @code{Library_Dir} attribute has a string value that designates the path
13942 (absolute or relative) of the directory where the library will reside.
13943 It must designate an existing directory, and this directory must be writable,
13944 different from the project's object directory and from any source directory
13945 in the project tree.
13946
13947 If both @code{Library_Name} and @code{Library_Dir} are specified and
13948 are legal, then the project file defines a library project.  The optional
13949 library-related attributes are checked only for such project files.
13950
13951 The @code{Library_Kind} attribute has a string value that must be one of the
13952 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13953 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13954 attribute is not specified, the library is a static library, that is
13955 an archive of object files that can be potentially linked into a
13956 static executable. Otherwise, the library may be dynamic or
13957 relocatable, that is a library that is loaded only at the start of execution.
13958
13959 If you need to build both a static and a dynamic library, you should use two
13960 different object directories, since in some cases some extra code needs to
13961 be generated for the latter. For such cases, it is recommended to either use
13962 two different project files, or a single one which uses external variables
13963 to indicate what kind of library should be build.
13964
13965 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13966 directory where the ALI files of the library will be copied. When it is
13967 not specified, the ALI files are copied to the directory specified in
13968 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13969 must be writable and different from the project's object directory and from
13970 any source directory in the project tree.
13971
13972 The @code{Library_Version} attribute has a string value whose interpretation
13973 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13974 used only for dynamic/relocatable libraries as the internal name of the
13975 library (the @code{"soname"}). If the library file name (built from the
13976 @code{Library_Name}) is different from the @code{Library_Version}, then the
13977 library file will be a symbolic link to the actual file whose name will be
13978 @code{Library_Version}.
13979
13980 Example (on Unix):
13981
13982 @smallexample @c projectfile
13983 @group
13984 project Plib is
13985
13986    Version := "1";
13987
13988    for Library_Dir use "lib_dir";
13989    for Library_Name use "dummy";
13990    for Library_Kind use "relocatable";
13991    for Library_Version use "libdummy.so." & Version;
13992
13993 end Plib;
13994 @end group
13995 @end smallexample
13996
13997 @noindent
13998 Directory @file{lib_dir} will contain the internal library file whose name
13999 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14000 @file{libdummy.so.1}.
14001
14002 When @command{gnatmake} detects that a project file
14003 is a library project file, it will check all immediate sources of the project
14004 and rebuild the library if any of the sources have been recompiled.
14005
14006 Standard project files can import library project files. In such cases,
14007 the libraries will only be rebuilt if some of its sources are recompiled
14008 because they are in the closure of some other source in an importing project.
14009 Sources of the library project files that are not in such a closure will
14010 not be checked, unless the full library is checked, because one of its sources
14011 needs to be recompiled.
14012
14013 For instance, assume the project file @code{A} imports the library project file
14014 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14015 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14016 @file{l2.ads}, @file{l2.adb}.
14017
14018 If @file{l1.adb} has been modified, then the library associated with @code{L}
14019 will be rebuilt when compiling all the immediate sources of @code{A} only
14020 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14021 @code{"with L1;"}.
14022
14023 To be sure that all the sources in the library associated with @code{L} are
14024 up to date, and that all the sources of project @code{A} are also up to date,
14025 the following two commands needs to be used:
14026
14027 @smallexample
14028 gnatmake -Pl.gpr
14029 gnatmake -Pa.gpr
14030 @end smallexample
14031
14032 When a library is built or rebuilt, an attempt is made first to delete all
14033 files in the library directory.
14034 All @file{ALI} files will also be copied from the object directory to the
14035 library directory. To build executables, @command{gnatmake} will use the
14036 library rather than the individual object files.
14037
14038 @ifclear vms
14039 It is also possible to create library project files for third-party libraries
14040 that are precompiled and cannot be compiled locally thanks to the
14041 @code{externally_built} attribute. (See @ref{Installing a library}).
14042 @end ifclear
14043
14044 @c *******************************
14045 @c * Stand-alone Library Projects *
14046 @c *******************************
14047
14048 @node Stand-alone Library Projects
14049 @section Stand-alone Library Projects
14050
14051 @noindent
14052 A Stand-alone Library is a library that contains the necessary code to
14053 elaborate the Ada units that are included in the library. A Stand-alone
14054 Library is suitable to be used in an executable when the main is not
14055 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14056 subprogram.
14057
14058 A Stand-alone Library Project is a Library Project where the library is
14059 a Stand-alone Library.
14060
14061 To be a Stand-alone Library Project, in addition to the two attributes
14062 that make a project a Library Project (@code{Library_Name} and
14063 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14064 @code{Library_Interface} must be defined.
14065
14066 @smallexample @c projectfile
14067 @group
14068    for Library_Dir use "lib_dir";
14069    for Library_Name use "dummy";
14070    for Library_Interface use ("int1", "int1.child");
14071 @end group
14072 @end smallexample
14073
14074 Attribute @code{Library_Interface} has a nonempty string list value,
14075 each string in the list designating a unit contained in an immediate source
14076 of the project file.
14077
14078 When a Stand-alone Library is built, first the binder is invoked to build
14079 a package whose name depends on the library name
14080 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14081 This binder-generated package includes initialization and
14082 finalization procedures whose
14083 names depend on the library name (dummyinit and dummyfinal in the example
14084 above). The object corresponding to this package is included in the library.
14085
14086 A dynamic or relocatable Stand-alone Library is automatically initialized
14087 if automatic initialization of Stand-alone Libraries is supported on the
14088 platform and if attribute @code{Library_Auto_Init} is not specified or
14089 is specified with the value "true". A static Stand-alone Library is never
14090 automatically initialized.
14091
14092 Single string attribute @code{Library_Auto_Init} may be specified with only
14093 two possible values: "false" or "true" (case-insensitive). Specifying
14094 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14095 initialization of dynamic or relocatable libraries.
14096
14097 When a non-automatically initialized Stand-alone Library is used
14098 in an executable, its initialization procedure must be called before
14099 any service of the library is used.
14100 When the main subprogram is in Ada, it may mean that the initialization
14101 procedure has to be called during elaboration of another package.
14102
14103 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14104 (those that are listed in attribute @code{Library_Interface}) are copied to
14105 the Library Directory. As a consequence, only the Interface Units may be
14106 imported from Ada units outside of the library. If other units are imported,
14107 the binding phase will fail.
14108
14109 When a Stand-Alone Library is bound, the switches that are specified in
14110 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14111 used in the call to @command{gnatbind}.
14112
14113 The string list attribute @code{Library_Options} may be used to specified
14114 additional switches to the call to @command{gcc} to link the library.
14115
14116 The attribute @code{Library_Src_Dir}, may be specified for a
14117 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14118 single string value. Its value must be the path (absolute or relative to the
14119 project directory) of an existing directory. This directory cannot be the
14120 object directory or one of the source directories, but it can be the same as
14121 the library directory. The sources of the Interface
14122 Units of the library, necessary to an Ada client of the library, will be
14123 copied to the designated directory, called Interface Copy directory.
14124 These sources includes the specs of the Interface Units, but they may also
14125 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14126 are used, or when there is a generic units in the spec. Before the sources
14127 are copied to the Interface Copy directory, an attempt is made to delete all
14128 files in the Interface Copy directory.
14129
14130 @c *************************************
14131 @c * Switches Related to Project Files *
14132 @c *************************************
14133 @node Switches Related to Project Files
14134 @section Switches Related to Project Files
14135
14136 @noindent
14137 The following switches are used by GNAT tools that support project files:
14138
14139 @table @option
14140
14141 @item ^-P^/PROJECT_FILE=^@var{project}
14142 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14143 Indicates the name of a project file. This project file will be parsed with
14144 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14145 if any, and using the external references indicated
14146 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14147 @ifclear vms
14148 There may zero, one or more spaces between @option{-P} and @var{project}.
14149 @end ifclear
14150
14151 @noindent
14152 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14153
14154 @noindent
14155 Since the Project Manager parses the project file only after all the switches
14156 on the command line are checked, the order of the switches
14157 @option{^-P^/PROJECT_FILE^},
14158 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14159 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14160
14161 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14162 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14163 Indicates that external variable @var{name} has the value @var{value}.
14164 The Project Manager will use this value for occurrences of
14165 @code{external(name)} when parsing the project file.
14166
14167 @ifclear vms
14168 @noindent
14169 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14170 put between quotes.
14171 @smallexample
14172   -XOS=NT
14173   -X"user=John Doe"
14174 @end smallexample
14175 @end ifclear
14176
14177 @noindent
14178 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14179 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14180 @var{name}, only the last one is used.
14181
14182 @noindent
14183 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14184 takes precedence over the value of the same name in the environment.
14185
14186 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14187 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14188 Indicates the verbosity of the parsing of GNAT project files.
14189
14190 @ifclear vms
14191 @option{-vP0} means Default;
14192 @option{-vP1} means Medium;
14193 @option{-vP2} means High.
14194 @end ifclear
14195
14196 @ifset vms
14197 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14198 HIGH.
14199 @end ifset
14200
14201 @noindent
14202 The default is ^Default^DEFAULT^: no output for syntactically correct
14203 project files.
14204 @noindent
14205 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14206 only the last one is used.
14207
14208 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14209 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14210 Add directory <dir> at the beginning of the project search path, in order,
14211 after the current working directory.
14212
14213 @ifclear vms
14214 @item -eL
14215 @cindex @option{-eL} (any project-aware tool)
14216 Follow all symbolic links when processing project files.
14217 @end ifclear
14218
14219 @item ^--subdirs^/SUBDIRS^=<subdir>
14220 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14221 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14222 directories (except the source directories) are the subdirectories <subdir>
14223 of the directories specified in the project files. This applies in particular
14224 to object directories, library directories and exec directories. If the
14225 subdirectories do not exist, they are created automatically.
14226
14227 @end table
14228
14229 @c **********************************
14230 @c * Tools Supporting Project Files *
14231 @c **********************************
14232
14233 @node  Tools Supporting Project Files
14234 @section Tools Supporting Project Files
14235
14236 @menu
14237 * gnatmake and Project Files::
14238 * The GNAT Driver and Project Files::
14239 @end menu
14240
14241 @node gnatmake and Project Files
14242 @subsection gnatmake and Project Files
14243
14244 @noindent
14245 This section covers several topics related to @command{gnatmake} and
14246 project files: defining ^switches^switches^ for @command{gnatmake}
14247 and for the tools that it invokes; specifying configuration pragmas;
14248 the use of the @code{Main} attribute; building and rebuilding library project
14249 files.
14250
14251 @menu
14252 * ^Switches^Switches^ and Project Files::
14253 * Specifying Configuration Pragmas::
14254 * Project Files and Main Subprograms::
14255 * Library Project Files::
14256 @end menu
14257
14258 @node ^Switches^Switches^ and Project Files
14259 @subsubsection ^Switches^Switches^ and Project Files
14260
14261 @ifset vms
14262 It is not currently possible to specify VMS style qualifiers in the project
14263 files; only Unix style ^switches^switches^ may be specified.
14264 @end ifset
14265
14266 @noindent
14267 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14268 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14269 attribute, a @code{^Switches^Switches^} attribute, or both;
14270 as their names imply, these ^switch^switch^-related
14271 attributes affect the ^switches^switches^ that are used for each of these GNAT
14272 components when
14273 @command{gnatmake} is invoked.  As will be explained below, these
14274 component-specific ^switches^switches^ precede
14275 the ^switches^switches^ provided on the @command{gnatmake} command line.
14276
14277 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14278 array indexed by language name (case insensitive) whose value is a string list.
14279 For example:
14280
14281 @smallexample @c projectfile
14282 @group
14283 package Compiler is
14284   for ^Default_Switches^Default_Switches^ ("Ada")
14285       use ("^-gnaty^-gnaty^",
14286            "^-v^-v^");
14287 end Compiler;
14288 @end group
14289 @end smallexample
14290
14291 @noindent
14292 The @code{^Switches^Switches^} attribute is also an associative array,
14293 indexed by a file name (which may or may not be case sensitive, depending
14294 on the operating system) whose value is a string list.  For example:
14295
14296 @smallexample @c projectfile
14297 @group
14298 package Builder is
14299    for ^Switches^Switches^ ("main1.adb")
14300        use ("^-O2^-O2^");
14301    for ^Switches^Switches^ ("main2.adb")
14302        use ("^-g^-g^");
14303 end Builder;
14304 @end group
14305 @end smallexample
14306
14307 @noindent
14308 For the @code{Builder} package, the file names must designate source files
14309 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14310 file names must designate @file{ALI} or source files for main subprograms.
14311 In each case just the file name without an explicit extension is acceptable.
14312
14313 For each tool used in a program build (@command{gnatmake}, the compiler, the
14314 binder, and the linker), the corresponding package @dfn{contributes} a set of
14315 ^switches^switches^ for each file on which the tool is invoked, based on the
14316 ^switch^switch^-related attributes defined in the package.
14317 In particular, the ^switches^switches^
14318 that each of these packages contributes for a given file @var{f} comprise:
14319
14320 @itemize @bullet
14321 @item
14322 the value of attribute @code{^Switches^Switches^ (@var{f})},
14323 if it is specified in the package for the given file,
14324 @item
14325 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14326 if it is specified in the package.
14327 @end itemize
14328
14329 @noindent
14330 If neither of these attributes is defined in the package, then the package does
14331 not contribute any ^switches^switches^ for the given file.
14332
14333 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14334 two sets, in the following order: those contributed for the file
14335 by the @code{Builder} package;
14336 and the switches passed on the command line.
14337
14338 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14339 the ^switches^switches^ passed to the tool comprise three sets,
14340 in the following order:
14341
14342 @enumerate
14343 @item
14344 the applicable ^switches^switches^ contributed for the file
14345 by the @code{Builder} package in the project file supplied on the command line;
14346
14347 @item
14348 those contributed for the file by the package (in the relevant project file --
14349 see below) corresponding to the tool; and
14350
14351 @item
14352 the applicable switches passed on the command line.
14353 @end enumerate
14354
14355 @noindent
14356 The term @emph{applicable ^switches^switches^} reflects the fact that
14357 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14358 tools, depending on the individual ^switch^switch^.
14359
14360 @command{gnatmake} may invoke the compiler on source files from different
14361 projects. The Project Manager will use the appropriate project file to
14362 determine the @code{Compiler} package for each source file being compiled.
14363 Likewise for the @code{Binder} and @code{Linker} packages.
14364
14365 As an example, consider the following package in a project file:
14366
14367 @smallexample @c projectfile
14368 @group
14369 project Proj1 is
14370    package Compiler is
14371       for ^Default_Switches^Default_Switches^ ("Ada")
14372           use ("^-g^-g^");
14373       for ^Switches^Switches^ ("a.adb")
14374           use ("^-O1^-O1^");
14375       for ^Switches^Switches^ ("b.adb")
14376           use ("^-O2^-O2^",
14377                "^-gnaty^-gnaty^");
14378    end Compiler;
14379 end Proj1;
14380 @end group
14381 @end smallexample
14382
14383 @noindent
14384 If @command{gnatmake} is invoked with this project file, and it needs to
14385 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14386 @file{a.adb} will be compiled with the ^switch^switch^
14387 @option{^-O1^-O1^},
14388 @file{b.adb} with ^switches^switches^
14389 @option{^-O2^-O2^}
14390 and @option{^-gnaty^-gnaty^},
14391 and @file{c.adb} with @option{^-g^-g^}.
14392
14393 The following example illustrates the ordering of the ^switches^switches^
14394 contributed by different packages:
14395
14396 @smallexample @c projectfile
14397 @group
14398 project Proj2 is
14399    package Builder is
14400       for ^Switches^Switches^ ("main.adb")
14401           use ("^-g^-g^",
14402                "^-O1^-)1^",
14403                "^-f^-f^");
14404    end Builder;
14405 @end group
14406
14407 @group
14408    package Compiler is
14409       for ^Switches^Switches^ ("main.adb")
14410           use ("^-O2^-O2^");
14411    end Compiler;
14412 end Proj2;
14413 @end group
14414 @end smallexample
14415
14416 @noindent
14417 If you issue the command:
14418
14419 @smallexample
14420     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14421 @end smallexample
14422
14423 @noindent
14424 then the compiler will be invoked on @file{main.adb} with the following
14425 sequence of ^switches^switches^
14426
14427 @smallexample
14428    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14429 @end smallexample
14430
14431 with the last @option{^-O^-O^}
14432 ^switch^switch^ having precedence over the earlier ones;
14433 several other ^switches^switches^
14434 (such as @option{^-c^-c^}) are added implicitly.
14435
14436 The ^switches^switches^
14437 @option{^-g^-g^}
14438 and @option{^-O1^-O1^} are contributed by package
14439 @code{Builder},  @option{^-O2^-O2^} is contributed
14440 by the package @code{Compiler}
14441 and @option{^-O0^-O0^} comes from the command line.
14442
14443 The @option{^-g^-g^}
14444 ^switch^switch^ will also be passed in the invocation of
14445 @command{Gnatlink.}
14446
14447 A final example illustrates switch contributions from packages in different
14448 project files:
14449
14450 @smallexample @c projectfile
14451 @group
14452 project Proj3 is
14453    for Source_Files use ("pack.ads", "pack.adb");
14454    package Compiler is
14455       for ^Default_Switches^Default_Switches^ ("Ada")
14456           use ("^-gnata^-gnata^");
14457    end Compiler;
14458 end Proj3;
14459 @end group
14460
14461 @group
14462 with "Proj3";
14463 project Proj4 is
14464    for Source_Files use ("foo_main.adb", "bar_main.adb");
14465    package Builder is
14466       for ^Switches^Switches^ ("foo_main.adb")
14467           use ("^-s^-s^",
14468                "^-g^-g^");
14469    end Builder;
14470 end Proj4;
14471 @end group
14472
14473 @group
14474 -- Ada source file:
14475 with Pack;
14476 procedure Foo_Main is
14477    @dots{}
14478 end Foo_Main;
14479 @end group
14480 @end smallexample
14481
14482 If the command is
14483 @smallexample
14484 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14485 @end smallexample
14486
14487 @noindent
14488 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14489 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14490 @option{^-gnato^-gnato^} (passed on the command line).
14491 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14492 are @option{^-g^-g^} from @code{Proj4.Builder},
14493 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14494 and @option{^-gnato^-gnato^} from the command line.
14495
14496 @noindent
14497 When using @command{gnatmake} with project files, some ^switches^switches^ or
14498 arguments may be expressed as relative paths. As the working directory where
14499 compilation occurs may change, these relative paths are converted to absolute
14500 paths. For the ^switches^switches^ found in a project file, the relative paths
14501 are relative to the project file directory, for the switches on the command
14502 line, they are relative to the directory where @command{gnatmake} is invoked.
14503 The ^switches^switches^ for which this occurs are:
14504 ^-I^-I^,
14505 ^-A^-A^,
14506 ^-L^-L^,
14507 ^-aO^-aO^,
14508 ^-aL^-aL^,
14509 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14510 ^switch^switch^
14511 ^-o^-o^, object files specified in package @code{Linker} or after
14512 -largs on the command line). The exception to this rule is the ^switch^switch^
14513 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14514
14515 @node Specifying Configuration Pragmas
14516 @subsubsection Specifying Configuration Pragmas
14517
14518 When using @command{gnatmake} with project files, if there exists a file
14519 @file{gnat.adc} that contains configuration pragmas, this file will be
14520 ignored.
14521
14522 Configuration pragmas can be defined by means of the following attributes in
14523 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14524 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14525
14526 Both these attributes are single string attributes. Their values is the path
14527 name of a file containing configuration pragmas. If a path name is relative,
14528 then it is relative to the project directory of the project file where the
14529 attribute is defined.
14530
14531 When compiling a source, the configuration pragmas used are, in order,
14532 those listed in the file designated by attribute
14533 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14534 project file, if it is specified, and those listed in the file designated by
14535 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14536 the project file of the source, if it exists.
14537
14538 @node Project Files and Main Subprograms
14539 @subsubsection Project Files and Main Subprograms
14540
14541 @noindent
14542 When using a project file, you can invoke @command{gnatmake}
14543 with one or several main subprograms, by specifying their source files on the
14544 command line.
14545
14546 @smallexample
14547     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14548 @end smallexample
14549
14550 @noindent
14551 Each of these needs to be a source file of the same project, except
14552 when the switch ^-u^/UNIQUE^ is used.
14553
14554 @noindent
14555 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14556 same project, one of the project in the tree rooted at the project specified
14557 on the command line. The package @code{Builder} of this common project, the
14558 "main project" is the one that is considered by @command{gnatmake}.
14559
14560 @noindent
14561 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14562 imported directly or indirectly by the project specified on the command line.
14563 Note that if such a source file is not part of the project specified on the
14564 command line, the ^switches^switches^ found in package @code{Builder} of the
14565 project specified on the command line, if any, that are transmitted
14566 to the compiler will still be used, not those found in the project file of
14567 the source file.
14568
14569 @noindent
14570 When using a project file, you can also invoke @command{gnatmake} without
14571 explicitly specifying any main, and the effect depends on whether you have
14572 defined the @code{Main} attribute.  This attribute has a string list value,
14573 where each element in the list is the name of a source file (the file
14574 extension is optional) that contains a unit that can be a main subprogram.
14575
14576 If the @code{Main} attribute is defined in a project file as a non-empty
14577 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14578 line, then invoking @command{gnatmake} with this project file but without any
14579 main on the command line is equivalent to invoking @command{gnatmake} with all
14580 the file names in the @code{Main} attribute on the command line.
14581
14582 Example:
14583 @smallexample @c projectfile
14584 @group
14585    project Prj is
14586       for Main use ("main1", "main2", "main3");
14587    end Prj;
14588 @end group
14589 @end smallexample
14590
14591 @noindent
14592 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14593 is equivalent to
14594 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14595
14596 When the project attribute @code{Main} is not specified, or is specified
14597 as an empty string list, or when the switch @option{-u} is used on the command
14598 line, then invoking @command{gnatmake} with no main on the command line will
14599 result in all immediate sources of the project file being checked, and
14600 potentially recompiled. Depending on the presence of the switch @option{-u},
14601 sources from other project files on which the immediate sources of the main
14602 project file depend are also checked and potentially recompiled. In other
14603 words, the @option{-u} switch is applied to all of the immediate sources of the
14604 main project file.
14605
14606 When no main is specified on the command line and attribute @code{Main} exists
14607 and includes several mains, or when several mains are specified on the
14608 command line, the default ^switches^switches^ in package @code{Builder} will
14609 be used for all mains, even if there are specific ^switches^switches^
14610 specified for one or several mains.
14611
14612 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14613 the specific ^switches^switches^ for each main, if they are specified.
14614
14615 @node Library Project Files
14616 @subsubsection Library Project Files
14617
14618 @noindent
14619 When @command{gnatmake} is invoked with a main project file that is a library
14620 project file, it is not allowed to specify one or more mains on the command
14621 line.
14622
14623 @noindent
14624 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14625 ^-l^/ACTION=LINK^ have special meanings.
14626
14627 @itemize @bullet
14628 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14629 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14630 library.
14631
14632 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14633 to @command{gnatmake} that the binder generated file should be compiled
14634 (in the case of a stand-alone library) and that the library should be built.
14635
14636 @end itemize
14637
14638 @node The GNAT Driver and Project Files
14639 @subsection The GNAT Driver and Project Files
14640
14641 @noindent
14642 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14643 can benefit from project files:
14644 @command{^gnatbind^gnatbind^},
14645 @command{^gnatcheck^gnatcheck^}),
14646 @command{^gnatclean^gnatclean^}),
14647 @command{^gnatelim^gnatelim^},
14648 @command{^gnatfind^gnatfind^},
14649 @command{^gnatlink^gnatlink^},
14650 @command{^gnatls^gnatls^},
14651 @command{^gnatmetric^gnatmetric^},
14652 @command{^gnatpp^gnatpp^},
14653 @command{^gnatstub^gnatstub^},
14654 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14655 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14656 They must be invoked through the @command{gnat} driver.
14657
14658 The @command{gnat} driver is a wrapper that accepts a number of commands and
14659 calls the corresponding tool. It was designed initially for VMS platforms (to
14660 convert VMS qualifiers to Unix-style switches), but it is now available on all
14661 GNAT platforms.
14662
14663 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14664 (case insensitive):
14665
14666 @itemize @bullet
14667 @item
14668 BIND to invoke @command{^gnatbind^gnatbind^}
14669 @item
14670 CHOP to invoke @command{^gnatchop^gnatchop^}
14671 @item
14672 CLEAN to invoke @command{^gnatclean^gnatclean^}
14673 @item
14674 COMP or COMPILE to invoke the compiler
14675 @item
14676 ELIM to invoke @command{^gnatelim^gnatelim^}
14677 @item
14678 FIND to invoke @command{^gnatfind^gnatfind^}
14679 @item
14680 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14681 @item
14682 LINK to invoke @command{^gnatlink^gnatlink^}
14683 @item
14684 LS or LIST to invoke @command{^gnatls^gnatls^}
14685 @item
14686 MAKE to invoke @command{^gnatmake^gnatmake^}
14687 @item
14688 NAME to invoke @command{^gnatname^gnatname^}
14689 @item
14690 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14691 @item
14692 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14693 @item
14694 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14695 @item
14696 STUB to invoke @command{^gnatstub^gnatstub^}
14697 @item
14698 XREF to invoke @command{^gnatxref^gnatxref^}
14699 @end itemize
14700
14701 @noindent
14702 (note that the compiler is invoked using the command
14703 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14704
14705 @noindent
14706 On non-VMS platforms, between @command{gnat} and the command, two
14707 special switches may be used:
14708
14709 @itemize @bullet
14710 @item
14711 @command{-v} to display the invocation of the tool.
14712 @item
14713 @command{-dn} to prevent the @command{gnat} driver from removing
14714 the temporary files it has created. These temporary files are
14715 configuration files and temporary file list files.
14716 @end itemize
14717
14718 @noindent
14719 The command may be followed by switches and arguments for the invoked
14720 tool.
14721
14722 @smallexample
14723   gnat bind -C main.ali
14724   gnat ls -a main
14725   gnat chop foo.txt
14726 @end smallexample
14727
14728 @noindent
14729 Switches may also be put in text files, one switch per line, and the text
14730 files may be specified with their path name preceded by '@@'.
14731
14732 @smallexample
14733    gnat bind @@args.txt main.ali
14734 @end smallexample
14735
14736 @noindent
14737 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14738 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14739 (@option{^-P^/PROJECT_FILE^},
14740 @option{^-X^/EXTERNAL_REFERENCE^} and
14741 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14742 the switches of the invoking tool.
14743
14744 @noindent
14745 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14746 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14747 the immediate sources of the specified project file.
14748
14749 @noindent
14750 When GNAT METRIC is used with a project file, but with no source
14751 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14752 with all the immediate sources of the specified project file and with
14753 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14754 of the project.
14755
14756 @noindent
14757 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14758 a project file, no source is specified on the command line and
14759 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14760 the underlying tool (^gnatpp^gnatpp^ or
14761 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14762 not only for the immediate sources of the main project.
14763 @ifclear vms
14764 (-U stands for Universal or Union of the project files of the project tree)
14765 @end ifclear
14766
14767 @noindent
14768 For each of the following commands, there is optionally a corresponding
14769 package in the main project.
14770
14771 @itemize @bullet
14772 @item
14773 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14774
14775 @item
14776 package @code{Check} for command CHECK (invoking
14777 @code{^gnatcheck^gnatcheck^})
14778
14779 @item
14780 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14781
14782 @item
14783 package @code{Cross_Reference} for command XREF (invoking
14784 @code{^gnatxref^gnatxref^})
14785
14786 @item
14787 package @code{Eliminate} for command ELIM (invoking
14788 @code{^gnatelim^gnatelim^})
14789
14790 @item
14791 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14792
14793 @item
14794 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14795
14796 @item
14797 package @code{Gnatstub} for command STUB
14798 (invoking @code{^gnatstub^gnatstub^})
14799
14800 @item
14801 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14802
14803 @item
14804 package @code{Metrics} for command METRIC
14805 (invoking @code{^gnatmetric^gnatmetric^})
14806
14807 @item
14808 package @code{Pretty_Printer} for command PP or PRETTY
14809 (invoking @code{^gnatpp^gnatpp^})
14810
14811 @end itemize
14812
14813 @noindent
14814 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14815 a simple variable with a string list value. It contains ^switches^switches^
14816 for the invocation of @code{^gnatls^gnatls^}.
14817
14818 @smallexample @c projectfile
14819 @group
14820 project Proj1 is
14821    package gnatls is
14822       for ^Switches^Switches^
14823           use ("^-a^-a^",
14824                "^-v^-v^");
14825    end gnatls;
14826 end Proj1;
14827 @end group
14828 @end smallexample
14829
14830 @noindent
14831 All other packages have two attribute @code{^Switches^Switches^} and
14832 @code{^Default_Switches^Default_Switches^}.
14833
14834 @noindent
14835 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14836 source file name, that has a string list value: the ^switches^switches^ to be
14837 used when the tool corresponding to the package is invoked for the specific
14838 source file.
14839
14840 @noindent
14841 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14842 indexed by  the programming language that has a string list value.
14843 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14844 ^switches^switches^ for the invocation of the tool corresponding
14845 to the package, except if a specific @code{^Switches^Switches^} attribute
14846 is specified for the source file.
14847
14848 @smallexample @c projectfile
14849 @group
14850 project Proj is
14851
14852    for Source_Dirs use ("./**");
14853
14854    package gnatls is
14855       for ^Switches^Switches^ use
14856           ("^-a^-a^",
14857            "^-v^-v^");
14858    end gnatls;
14859 @end group
14860 @group
14861
14862    package Compiler is
14863       for ^Default_Switches^Default_Switches^ ("Ada")
14864           use ("^-gnatv^-gnatv^",
14865                "^-gnatwa^-gnatwa^");
14866    end Binder;
14867 @end group
14868 @group
14869
14870    package Binder is
14871       for ^Default_Switches^Default_Switches^ ("Ada")
14872           use ("^-C^-C^",
14873                "^-e^-e^");
14874    end Binder;
14875 @end group
14876 @group
14877
14878    package Linker is
14879       for ^Default_Switches^Default_Switches^ ("Ada")
14880           use ("^-C^-C^");
14881       for ^Switches^Switches^ ("main.adb")
14882           use ("^-C^-C^",
14883                "^-v^-v^",
14884                "^-v^-v^");
14885    end Linker;
14886 @end group
14887 @group
14888
14889    package Finder is
14890       for ^Default_Switches^Default_Switches^ ("Ada")
14891            use ("^-a^-a^",
14892                 "^-f^-f^");
14893    end Finder;
14894 @end group
14895 @group
14896
14897    package Cross_Reference is
14898       for ^Default_Switches^Default_Switches^ ("Ada")
14899           use ("^-a^-a^",
14900                "^-f^-f^",
14901                "^-d^-d^",
14902                "^-u^-u^");
14903    end Cross_Reference;
14904 end Proj;
14905 @end group
14906 @end smallexample
14907
14908 @noindent
14909 With the above project file, commands such as
14910
14911 @smallexample
14912    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14913    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14914    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14915    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14916    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14917 @end smallexample
14918
14919 @noindent
14920 will set up the environment properly and invoke the tool with the switches
14921 found in the package corresponding to the tool:
14922 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14923 except @code{^Switches^Switches^ ("main.adb")}
14924 for @code{^gnatlink^gnatlink^}.
14925 It is also possible to invoke some of the tools,
14926 @code{^gnatcheck^gnatcheck^}),
14927 @code{^gnatmetric^gnatmetric^}),
14928 and @code{^gnatpp^gnatpp^})
14929 on a set of project units thanks to the combination of the switches
14930 @option{-P}, @option{-U} and possibly the main unit when one is interested
14931 in its closure. For instance,
14932 @smallexample
14933 gnat metric -Pproj
14934 @end smallexample
14935 will compute the metrics for all the immediate units of project
14936 @code{proj}.
14937 @smallexample
14938 gnat metric -Pproj -U
14939 @end smallexample
14940 will compute the metrics for all the units of the closure of projects
14941 rooted at @code{proj}.
14942 @smallexample
14943 gnat metric -Pproj -U main_unit
14944 @end smallexample
14945 will compute the metrics for the closure of units rooted at
14946 @code{main_unit}. This last possibility relies implicitly
14947 on @command{gnatbind}'s option @option{-R}.
14948
14949 @c **********************
14950 @node An Extended Example
14951 @section An Extended Example
14952
14953 @noindent
14954 Suppose that we have two programs, @var{prog1} and @var{prog2},
14955 whose sources are in corresponding directories. We would like
14956 to build them with a single @command{gnatmake} command, and we want to place
14957 their object files into @file{build} subdirectories of the source directories.
14958 Furthermore, we want to have to have two separate subdirectories
14959 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14960 the object files compiled with different set of compilation flags.
14961
14962 In other words, we have the following structure:
14963
14964 @smallexample
14965 @group
14966    main
14967      |- prog1
14968      |    |- build
14969      |         | debug
14970      |         | release
14971      |- prog2
14972           |- build
14973                | debug
14974                | release
14975 @end group
14976 @end smallexample
14977
14978 @noindent
14979 Here are the project files that we must place in a directory @file{main}
14980 to maintain this structure:
14981
14982 @enumerate
14983
14984 @item We create a @code{Common} project with a package @code{Compiler} that
14985 specifies the compilation ^switches^switches^:
14986
14987 @smallexample
14988 File "common.gpr":
14989 @group
14990 @b{project} Common @b{is}
14991
14992    @b{for} Source_Dirs @b{use} (); -- No source files
14993 @end group
14994
14995 @group
14996    @b{type} Build_Type @b{is} ("release", "debug");
14997    Build : Build_Type := External ("BUILD", "debug");
14998 @end group
14999 @group
15000    @b{package} Compiler @b{is}
15001       @b{case} Build @b{is}
15002          @b{when} "release" =>
15003            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15004                    @b{use} ("^-O2^-O2^");
15005          @b{when} "debug"   =>
15006            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15007                    @b{use} ("^-g^-g^");
15008       @b{end case};
15009    @b{end} Compiler;
15010
15011 @b{end} Common;
15012 @end group
15013 @end smallexample
15014
15015 @item We create separate projects for the two programs:
15016
15017 @smallexample
15018 @group
15019 File "prog1.gpr":
15020
15021 @b{with} "common";
15022 @b{project} Prog1 @b{is}
15023
15024     @b{for} Source_Dirs @b{use} ("prog1");
15025     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15026
15027     @b{package} Compiler @b{renames} Common.Compiler;
15028
15029 @b{end} Prog1;
15030 @end group
15031 @end smallexample
15032
15033 @smallexample
15034 @group
15035 File "prog2.gpr":
15036
15037 @b{with} "common";
15038 @b{project} Prog2 @b{is}
15039
15040     @b{for} Source_Dirs @b{use} ("prog2");
15041     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15042
15043     @b{package} Compiler @b{renames} Common.Compiler;
15044
15045 @end group
15046 @b{end} Prog2;
15047 @end smallexample
15048
15049 @item We create a wrapping project @code{Main}:
15050
15051 @smallexample
15052 @group
15053 File "main.gpr":
15054
15055 @b{with} "common";
15056 @b{with} "prog1";
15057 @b{with} "prog2";
15058 @b{project} Main @b{is}
15059
15060    @b{package} Compiler @b{renames} Common.Compiler;
15061
15062 @b{end} Main;
15063 @end group
15064 @end smallexample
15065
15066 @item Finally we need to create a dummy procedure that @code{with}s (either
15067 explicitly or implicitly) all the sources of our two programs.
15068
15069 @end enumerate
15070
15071 @noindent
15072 Now we can build the programs using the command
15073
15074 @smallexample
15075    gnatmake ^-P^/PROJECT_FILE=^main dummy
15076 @end smallexample
15077
15078 @noindent
15079 for the Debug mode, or
15080
15081 @ifclear vms
15082 @smallexample
15083    gnatmake -Pmain -XBUILD=release
15084 @end smallexample
15085 @end ifclear
15086
15087 @ifset vms
15088 @smallexample
15089    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15090 @end smallexample
15091 @end ifset
15092
15093 @noindent
15094 for the Release mode.
15095
15096 @c ********************************
15097 @c * Project File Complete Syntax *
15098 @c ********************************
15099
15100 @node Project File Complete Syntax
15101 @section Project File Complete Syntax
15102
15103 @smallexample
15104 project ::=
15105   context_clause project_declaration
15106
15107 context_clause ::=
15108   @{with_clause@}
15109
15110 with_clause ::=
15111   @b{with} path_name @{ , path_name @} ;
15112
15113 path_name ::=
15114    string_literal
15115
15116 project_declaration ::=
15117   simple_project_declaration | project_extension
15118
15119 simple_project_declaration ::=
15120   @b{project} <project_>simple_name @b{is}
15121     @{declarative_item@}
15122   @b{end} <project_>simple_name;
15123
15124 project_extension ::=
15125   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15126     @{declarative_item@}
15127   @b{end} <project_>simple_name;
15128
15129 declarative_item ::=
15130   package_declaration |
15131   typed_string_declaration |
15132   other_declarative_item
15133
15134 package_declaration ::=
15135   package_spec | package_renaming
15136
15137 package_spec ::=
15138   @b{package} package_identifier @b{is}
15139     @{simple_declarative_item@}
15140   @b{end} package_identifier ;
15141
15142 package_identifier ::=
15143   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15144   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15145   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15146
15147 package_renaming ::==
15148   @b{package} package_identifier @b{renames}
15149        <project_>simple_name.package_identifier ;
15150
15151 typed_string_declaration ::=
15152   @b{type} <typed_string_>_simple_name @b{is}
15153    ( string_literal @{, string_literal@} );
15154
15155 other_declarative_item ::=
15156   attribute_declaration |
15157   typed_variable_declaration |
15158   variable_declaration |
15159   case_construction
15160
15161 attribute_declaration ::=
15162   full_associative_array_declaration |
15163   @b{for} attribute_designator @b{use} expression ;
15164
15165 full_associative_array_declaration ::=
15166   @b{for} <associative_array_attribute_>simple_name @b{use}
15167   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15168
15169 attribute_designator ::=
15170   <simple_attribute_>simple_name |
15171   <associative_array_attribute_>simple_name ( string_literal )
15172
15173 typed_variable_declaration ::=
15174   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15175
15176 variable_declaration ::=
15177   <variable_>simple_name := expression;
15178
15179 expression ::=
15180   term @{& term@}
15181
15182 term ::=
15183   literal_string |
15184   string_list |
15185   <variable_>name |
15186   external_value |
15187   attribute_reference
15188
15189 string_literal ::=
15190   (same as Ada)
15191
15192 string_list ::=
15193   ( <string_>expression @{ , <string_>expression @} )
15194
15195 external_value ::=
15196   @b{external} ( string_literal [, string_literal] )
15197
15198 attribute_reference ::=
15199   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15200
15201 attribute_prefix ::=
15202   @b{project} |
15203   <project_>simple_name | package_identifier |
15204   <project_>simple_name . package_identifier
15205
15206 case_construction ::=
15207   @b{case} <typed_variable_>name @b{is}
15208     @{case_item@}
15209   @b{end case} ;
15210
15211 case_item ::=
15212   @b{when} discrete_choice_list =>
15213       @{case_construction | attribute_declaration@}
15214
15215 discrete_choice_list ::=
15216   string_literal @{| string_literal@} |
15217   @b{others}
15218
15219 name ::=
15220   simple_name @{. simple_name@}
15221
15222 simple_name ::=
15223   identifier (same as Ada)
15224
15225 @end smallexample
15226
15227 @node The Cross-Referencing Tools gnatxref and gnatfind
15228 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15229 @findex gnatxref
15230 @findex gnatfind
15231
15232 @noindent
15233 The compiler generates cross-referencing information (unless
15234 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15235 This information indicates where in the source each entity is declared and
15236 referenced. Note that entities in package Standard are not included, but
15237 entities in all other predefined units are included in the output.
15238
15239 Before using any of these two tools, you need to compile successfully your
15240 application, so that GNAT gets a chance to generate the cross-referencing
15241 information.
15242
15243 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15244 information to provide the user with the capability to easily locate the
15245 declaration and references to an entity. These tools are quite similar,
15246 the difference being that @code{gnatfind} is intended for locating
15247 definitions and/or references to a specified entity or entities, whereas
15248 @code{gnatxref} is oriented to generating a full report of all
15249 cross-references.
15250
15251 To use these tools, you must not compile your application using the
15252 @option{-gnatx} switch on the @command{gnatmake} command line
15253 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15254 information will not be generated.
15255
15256 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15257 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15258
15259 @menu
15260 * gnatxref Switches::
15261 * gnatfind Switches::
15262 * Project Files for gnatxref and gnatfind::
15263 * Regular Expressions in gnatfind and gnatxref::
15264 * Examples of gnatxref Usage::
15265 * Examples of gnatfind Usage::
15266 @end menu
15267
15268 @node gnatxref Switches
15269 @section @code{gnatxref} Switches
15270
15271 @noindent
15272 The command invocation for @code{gnatxref} is:
15273 @smallexample
15274 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15275 @end smallexample
15276
15277 @noindent
15278 where
15279
15280 @table @var
15281 @item sourcefile1
15282 @itemx sourcefile2
15283 identifies the source files for which a report is to be generated. The
15284 ``with''ed units will be processed too. You must provide at least one file.
15285
15286 These file names are considered to be regular expressions, so for instance
15287 specifying @file{source*.adb} is the same as giving every file in the current
15288 directory whose name starts with @file{source} and whose extension is
15289 @file{adb}.
15290
15291 You shouldn't specify any directory name, just base names. @command{gnatxref}
15292 and @command{gnatfind} will be able to locate these files by themselves using
15293 the source path. If you specify directories, no result is produced.
15294
15295 @end table
15296
15297 @noindent
15298 The switches can be:
15299 @table @option
15300 @c !sort!
15301 @item --version
15302 @cindex @option{--version} @command{gnatxref}
15303 Display Copyright and version, then exit disregarding all other options.
15304
15305 @item --help
15306 @cindex @option{--help} @command{gnatxref}
15307 If @option{--version} was not used, display usage, then exit disregarding
15308 all other options.
15309
15310 @item ^-a^/ALL_FILES^
15311 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15312 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15313 the read-only files found in the library search path. Otherwise, these files
15314 will be ignored. This option can be used to protect Gnat sources or your own
15315 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15316 much faster, and their output much smaller. Read-only here refers to access
15317 or permissions status in the file system for the current user.
15318
15319 @item -aIDIR
15320 @cindex @option{-aIDIR} (@command{gnatxref})
15321 When looking for source files also look in directory DIR. The order in which
15322 source file search is undertaken is the same as for @command{gnatmake}.
15323
15324 @item -aODIR
15325 @cindex @option{-aODIR} (@command{gnatxref})
15326 When searching for library and object files, look in directory
15327 DIR. The order in which library files are searched is the same as for
15328 @command{gnatmake}.
15329
15330 @item -nostdinc
15331 @cindex @option{-nostdinc} (@command{gnatxref})
15332 Do not look for sources in the system default directory.
15333
15334 @item -nostdlib
15335 @cindex @option{-nostdlib} (@command{gnatxref})
15336 Do not look for library files in the system default directory.
15337
15338 @item --RTS=@var{rts-path}
15339 @cindex @option{--RTS} (@command{gnatxref})
15340 Specifies the default location of the runtime library. Same meaning as the
15341 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15342
15343 @item ^-d^/DERIVED_TYPES^
15344 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15345 If this switch is set @code{gnatxref} will output the parent type
15346 reference for each matching derived types.
15347
15348 @item ^-f^/FULL_PATHNAME^
15349 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15350 If this switch is set, the output file names will be preceded by their
15351 directory (if the file was found in the search path). If this switch is
15352 not set, the directory will not be printed.
15353
15354 @item ^-g^/IGNORE_LOCALS^
15355 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15356 If this switch is set, information is output only for library-level
15357 entities, ignoring local entities. The use of this switch may accelerate
15358 @code{gnatfind} and @code{gnatxref}.
15359
15360 @item -IDIR
15361 @cindex @option{-IDIR} (@command{gnatxref})
15362 Equivalent to @samp{-aODIR -aIDIR}.
15363
15364 @item -pFILE
15365 @cindex @option{-pFILE} (@command{gnatxref})
15366 Specify a project file to use @xref{Project Files}.
15367 If you need to use the @file{.gpr}
15368 project files, you should use gnatxref through the GNAT driver
15369 (@command{gnat xref -Pproject}).
15370
15371 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15372 project file in the current directory.
15373
15374 If a project file is either specified or found by the tools, then the content
15375 of the source directory and object directory lines are added as if they
15376 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15377 and @samp{^-aO^OBJECT_SEARCH^}.
15378 @item ^-u^/UNUSED^
15379 Output only unused symbols. This may be really useful if you give your
15380 main compilation unit on the command line, as @code{gnatxref} will then
15381 display every unused entity and 'with'ed package.
15382
15383 @ifclear vms
15384 @item -v
15385 Instead of producing the default output, @code{gnatxref} will generate a
15386 @file{tags} file that can be used by vi. For examples how to use this
15387 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15388 to the standard output, thus you will have to redirect it to a file.
15389 @end ifclear
15390
15391 @end table
15392
15393 @noindent
15394 All these switches may be in any order on the command line, and may even
15395 appear after the file names. They need not be separated by spaces, thus
15396 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15397 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15398
15399 @node gnatfind Switches
15400 @section @code{gnatfind} Switches
15401
15402 @noindent
15403 The command line for @code{gnatfind} is:
15404
15405 @smallexample
15406 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15407       @r{[}@var{file1} @var{file2} @dots{}]
15408 @end smallexample
15409
15410 @noindent
15411 where
15412
15413 @table @var
15414 @item pattern
15415 An entity will be output only if it matches the regular expression found
15416 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15417
15418 Omitting the pattern is equivalent to specifying @samp{*}, which
15419 will match any entity. Note that if you do not provide a pattern, you
15420 have to provide both a sourcefile and a line.
15421
15422 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15423 for matching purposes. At the current time there is no support for
15424 8-bit codes other than Latin-1, or for wide characters in identifiers.
15425
15426 @item sourcefile
15427 @code{gnatfind} will look for references, bodies or declarations
15428 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15429 and column @var{column}. See @ref{Examples of gnatfind Usage}
15430 for syntax examples.
15431
15432 @item line
15433 is a decimal integer identifying the line number containing
15434 the reference to the entity (or entities) to be located.
15435
15436 @item column
15437 is a decimal integer identifying the exact location on the
15438 line of the first character of the identifier for the
15439 entity reference. Columns are numbered from 1.
15440
15441 @item file1 file2 @dots{}
15442 The search will be restricted to these source files. If none are given, then
15443 the search will be done for every library file in the search path.
15444 These file must appear only after the pattern or sourcefile.
15445
15446 These file names are considered to be regular expressions, so for instance
15447 specifying @file{source*.adb} is the same as giving every file in the current
15448 directory whose name starts with @file{source} and whose extension is
15449 @file{adb}.
15450
15451 The location of the spec of the entity will always be displayed, even if it
15452 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15453 occurrences of the entity in the separate units of the ones given on the
15454 command line will also be displayed.
15455
15456 Note that if you specify at least one file in this part, @code{gnatfind} may
15457 sometimes not be able to find the body of the subprograms.
15458
15459 @end table
15460
15461 @noindent
15462 At least one of 'sourcefile' or 'pattern' has to be present on
15463 the command line.
15464
15465 The following switches are available:
15466 @table @option
15467 @c !sort!
15468
15469 @cindex @option{--version} @command{gnatfind}
15470 Display Copyright and version, then exit disregarding all other options.
15471
15472 @item --help
15473 @cindex @option{--help} @command{gnatfind}
15474 If @option{--version} was not used, display usage, then exit disregarding
15475 all other options.
15476
15477 @item ^-a^/ALL_FILES^
15478 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15479 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15480 the read-only files found in the library search path. Otherwise, these files
15481 will be ignored. This option can be used to protect Gnat sources or your own
15482 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15483 much faster, and their output much smaller. Read-only here refers to access
15484 or permission status in the file system for the current user.
15485
15486 @item -aIDIR
15487 @cindex @option{-aIDIR} (@command{gnatfind})
15488 When looking for source files also look in directory DIR. The order in which
15489 source file search is undertaken is the same as for @command{gnatmake}.
15490
15491 @item -aODIR
15492 @cindex @option{-aODIR} (@command{gnatfind})
15493 When searching for library and object files, look in directory
15494 DIR. The order in which library files are searched is the same as for
15495 @command{gnatmake}.
15496
15497 @item -nostdinc
15498 @cindex @option{-nostdinc} (@command{gnatfind})
15499 Do not look for sources in the system default directory.
15500
15501 @item -nostdlib
15502 @cindex @option{-nostdlib} (@command{gnatfind})
15503 Do not look for library files in the system default directory.
15504
15505 @item --RTS=@var{rts-path}
15506 @cindex @option{--RTS} (@command{gnatfind})
15507 Specifies the default location of the runtime library. Same meaning as the
15508 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15509
15510 @item ^-d^/DERIVED_TYPE_INFORMATION^
15511 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15512 If this switch is set, then @code{gnatfind} will output the parent type
15513 reference for each matching derived types.
15514
15515 @item ^-e^/EXPRESSIONS^
15516 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15517 By default, @code{gnatfind} accept the simple regular expression set for
15518 @samp{pattern}. If this switch is set, then the pattern will be
15519 considered as full Unix-style regular expression.
15520
15521 @item ^-f^/FULL_PATHNAME^
15522 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15523 If this switch is set, the output file names will be preceded by their
15524 directory (if the file was found in the search path). If this switch is
15525 not set, the directory will not be printed.
15526
15527 @item ^-g^/IGNORE_LOCALS^
15528 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15529 If this switch is set, information is output only for library-level
15530 entities, ignoring local entities. The use of this switch may accelerate
15531 @code{gnatfind} and @code{gnatxref}.
15532
15533 @item -IDIR
15534 @cindex @option{-IDIR} (@command{gnatfind})
15535 Equivalent to @samp{-aODIR -aIDIR}.
15536
15537 @item -pFILE
15538 @cindex @option{-pFILE} (@command{gnatfind})
15539 Specify a project file (@pxref{Project Files}) to use.
15540 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15541 project file in the current directory.
15542
15543 If a project file is either specified or found by the tools, then the content
15544 of the source directory and object directory lines are added as if they
15545 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15546 @samp{^-aO^/OBJECT_SEARCH^}.
15547
15548 @item ^-r^/REFERENCES^
15549 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15550 By default, @code{gnatfind} will output only the information about the
15551 declaration, body or type completion of the entities. If this switch is
15552 set, the @code{gnatfind} will locate every reference to the entities in
15553 the files specified on the command line (or in every file in the search
15554 path if no file is given on the command line).
15555
15556 @item ^-s^/PRINT_LINES^
15557 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15558 If this switch is set, then @code{gnatfind} will output the content
15559 of the Ada source file lines were the entity was found.
15560
15561 @item ^-t^/TYPE_HIERARCHY^
15562 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15563 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15564 the specified type. It act like -d option but recursively from parent
15565 type to parent type. When this switch is set it is not possible to
15566 specify more than one file.
15567
15568 @end table
15569
15570 @noindent
15571 All these switches may be in any order on the command line, and may even
15572 appear after the file names. They need not be separated by spaces, thus
15573 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15574 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15575
15576 As stated previously, gnatfind will search in every directory in the
15577 search path. You can force it to look only in the current directory if
15578 you specify @code{*} at the end of the command line.
15579
15580 @node Project Files for gnatxref and gnatfind
15581 @section Project Files for @command{gnatxref} and @command{gnatfind}
15582
15583 @noindent
15584 Project files allow a programmer to specify how to compile its
15585 application, where to find sources, etc.  These files are used
15586 @ifclear vms
15587 primarily by GPS, but they can also be used
15588 @end ifclear
15589 by the two tools
15590 @code{gnatxref} and @code{gnatfind}.
15591
15592 A project file name must end with @file{.gpr}. If a single one is
15593 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15594 extract the information from it. If multiple project files are found, none of
15595 them is read, and you have to use the @samp{-p} switch to specify the one
15596 you want to use.
15597
15598 The following lines can be included, even though most of them have default
15599 values which can be used in most cases.
15600 The lines can be entered in any order in the file.
15601 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15602 each line. If you have multiple instances, only the last one is taken into
15603 account.
15604
15605 @table @code
15606 @item src_dir=DIR
15607 [default: @code{"^./^[]^"}]
15608 specifies a directory where to look for source files. Multiple @code{src_dir}
15609 lines can be specified and they will be searched in the order they
15610 are specified.
15611
15612 @item obj_dir=DIR
15613 [default: @code{"^./^[]^"}]
15614 specifies a directory where to look for object and library files. Multiple
15615 @code{obj_dir} lines can be specified, and they will be searched in the order
15616 they are specified
15617
15618 @item comp_opt=SWITCHES
15619 [default: @code{""}]
15620 creates a variable which can be referred to subsequently by using
15621 the @code{$@{comp_opt@}} notation. This is intended to store the default
15622 switches given to @command{gnatmake} and @command{gcc}.
15623
15624 @item bind_opt=SWITCHES
15625 [default: @code{""}]
15626 creates a variable which can be referred to subsequently by using
15627 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15628 switches given to @command{gnatbind}.
15629
15630 @item link_opt=SWITCHES
15631 [default: @code{""}]
15632 creates a variable which can be referred to subsequently by using
15633 the @samp{$@{link_opt@}} notation. This is intended to store the default
15634 switches given to @command{gnatlink}.
15635
15636 @item main=EXECUTABLE
15637 [default: @code{""}]
15638 specifies the name of the executable for the application. This variable can
15639 be referred to in the following lines by using the @samp{$@{main@}} notation.
15640
15641 @ifset vms
15642 @item comp_cmd=COMMAND
15643 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15644 @end ifset
15645 @ifclear vms
15646 @item comp_cmd=COMMAND
15647 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15648 @end ifclear
15649 specifies the command used to compile a single file in the application.
15650
15651 @ifset vms
15652 @item make_cmd=COMMAND
15653 [default: @code{"GNAT MAKE $@{main@}
15654 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15655 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15656 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15657 @end ifset
15658 @ifclear vms
15659 @item make_cmd=COMMAND
15660 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15661 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15662 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15663 @end ifclear
15664 specifies the command used to recompile the whole application.
15665
15666 @item run_cmd=COMMAND
15667 [default: @code{"$@{main@}"}]
15668 specifies the command used to run the application.
15669
15670 @item debug_cmd=COMMAND
15671 [default: @code{"gdb $@{main@}"}]
15672 specifies the command used to debug the application
15673
15674 @end table
15675
15676 @noindent
15677 @command{gnatxref} and @command{gnatfind} only take into account the
15678 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15679
15680 @node Regular Expressions in gnatfind and gnatxref
15681 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15682
15683 @noindent
15684 As specified in the section about @command{gnatfind}, the pattern can be a
15685 regular expression. Actually, there are to set of regular expressions
15686 which are recognized by the program:
15687
15688 @table @code
15689 @item globbing patterns
15690 These are the most usual regular expression. They are the same that you
15691 generally used in a Unix shell command line, or in a DOS session.
15692
15693 Here is a more formal grammar:
15694 @smallexample
15695 @group
15696 @iftex
15697 @leftskip=.5cm
15698 @end iftex
15699 regexp ::= term
15700 term   ::= elmt            -- matches elmt
15701 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15702 term   ::= *               -- any string of 0 or more characters
15703 term   ::= ?               -- matches any character
15704 term   ::= [char @{char@}]   -- matches any character listed
15705 term   ::= [char - char]   -- matches any character in range
15706 @end group
15707 @end smallexample
15708
15709 @item full regular expression
15710 The second set of regular expressions is much more powerful. This is the
15711 type of regular expressions recognized by utilities such a @file{grep}.
15712
15713 The following is the form of a regular expression, expressed in Ada
15714 reference manual style BNF is as follows
15715
15716 @smallexample
15717 @iftex
15718 @leftskip=.5cm
15719 @end iftex
15720 @group
15721 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15722
15723 term ::= item @{item@}       -- concatenation (item then item)
15724
15725 item ::= elmt              -- match elmt
15726 item ::= elmt *            -- zero or more elmt's
15727 item ::= elmt +            -- one or more elmt's
15728 item ::= elmt ?            -- matches elmt or nothing
15729 @end group
15730 @group
15731 elmt ::= nschar            -- matches given character
15732 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15733 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15734 elmt ::= [char - char]     -- matches chars in given range
15735 elmt ::= \ char            -- matches given character
15736 elmt ::= .                 -- matches any single character
15737 elmt ::= ( regexp )        -- parens used for grouping
15738
15739 char ::= any character, including special characters
15740 nschar ::= any character except ()[].*+?^^^
15741 @end group
15742 @end smallexample
15743
15744 Following are a few examples:
15745
15746 @table @samp
15747 @item abcde|fghi
15748 will match any of the two strings @samp{abcde} and @samp{fghi},
15749
15750 @item abc*d
15751 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15752 @samp{abcccd}, and so on,
15753
15754 @item [a-z]+
15755 will match any string which has only lowercase characters in it (and at
15756 least one character.
15757
15758 @end table
15759 @end table
15760
15761 @node Examples of gnatxref Usage
15762 @section Examples of @code{gnatxref} Usage
15763
15764 @subsection General Usage
15765
15766 @noindent
15767 For the following examples, we will consider the following units:
15768
15769 @smallexample @c ada
15770 @group
15771 @cartouche
15772 main.ads:
15773 1: with Bar;
15774 2: package Main is
15775 3:     procedure Foo (B : in Integer);
15776 4:     C : Integer;
15777 5: private
15778 6:     D : Integer;
15779 7: end Main;
15780
15781 main.adb:
15782 1: package body Main is
15783 2:     procedure Foo (B : in Integer) is
15784 3:     begin
15785 4:        C := B;
15786 5:        D := B;
15787 6:        Bar.Print (B);
15788 7:        Bar.Print (C);
15789 8:     end Foo;
15790 9: end Main;
15791
15792 bar.ads:
15793 1: package Bar is
15794 2:     procedure Print (B : Integer);
15795 3: end bar;
15796 @end cartouche
15797 @end group
15798 @end smallexample
15799
15800 @table @code
15801
15802 @noindent
15803 The first thing to do is to recompile your application (for instance, in
15804 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15805 the cross-referencing information.
15806 You can then issue any of the following commands:
15807
15808 @item gnatxref main.adb
15809 @code{gnatxref} generates cross-reference information for main.adb
15810 and every unit 'with'ed by main.adb.
15811
15812 The output would be:
15813 @smallexample
15814 @iftex
15815 @leftskip=0cm
15816 @end iftex
15817 B                                                      Type: Integer
15818   Decl: bar.ads           2:22
15819 B                                                      Type: Integer
15820   Decl: main.ads          3:20
15821   Body: main.adb          2:20
15822   Ref:  main.adb          4:13     5:13     6:19
15823 Bar                                                    Type: Unit
15824   Decl: bar.ads           1:9
15825   Ref:  main.adb          6:8      7:8
15826        main.ads           1:6
15827 C                                                      Type: Integer
15828   Decl: main.ads          4:5
15829   Modi: main.adb          4:8
15830   Ref:  main.adb          7:19
15831 D                                                      Type: Integer
15832   Decl: main.ads          6:5
15833   Modi: main.adb          5:8
15834 Foo                                                    Type: Unit
15835   Decl: main.ads          3:15
15836   Body: main.adb          2:15
15837 Main                                                    Type: Unit
15838   Decl: main.ads          2:9
15839   Body: main.adb          1:14
15840 Print                                                   Type: Unit
15841   Decl: bar.ads           2:15
15842   Ref:  main.adb          6:12     7:12
15843 @end smallexample
15844
15845 @noindent
15846 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15847 its body is in main.adb, line 1, column 14 and is not referenced any where.
15848
15849 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15850 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15851
15852 @item gnatxref package1.adb package2.ads
15853 @code{gnatxref} will generates cross-reference information for
15854 package1.adb, package2.ads and any other package 'with'ed by any
15855 of these.
15856
15857 @end table
15858
15859 @ifclear vms
15860 @subsection Using gnatxref with vi
15861
15862 @code{gnatxref} can generate a tags file output, which can be used
15863 directly from @command{vi}. Note that the standard version of @command{vi}
15864 will not work properly with overloaded symbols. Consider using another
15865 free implementation of @command{vi}, such as @command{vim}.
15866
15867 @smallexample
15868 $ gnatxref -v gnatfind.adb > tags
15869 @end smallexample
15870
15871 @noindent
15872 will generate the tags file for @code{gnatfind} itself (if the sources
15873 are in the search path!).
15874
15875 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15876 (replacing @var{entity} by whatever you are looking for), and vi will
15877 display a new file with the corresponding declaration of entity.
15878 @end ifclear
15879
15880 @node Examples of gnatfind Usage
15881 @section Examples of @code{gnatfind} Usage
15882
15883 @table @code
15884
15885 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15886 Find declarations for all entities xyz referenced at least once in
15887 main.adb. The references are search in every library file in the search
15888 path.
15889
15890 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15891 switch is set)
15892
15893 The output will look like:
15894 @smallexample
15895 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15896 ^directory/^[directory]^main.adb:24:10: xyz <= body
15897 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15898 @end smallexample
15899
15900 @noindent
15901 that is to say, one of the entities xyz found in main.adb is declared at
15902 line 12 of main.ads (and its body is in main.adb), and another one is
15903 declared at line 45 of foo.ads
15904
15905 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15906 This is the same command as the previous one, instead @code{gnatfind} will
15907 display the content of the Ada source file lines.
15908
15909 The output will look like:
15910
15911 @smallexample
15912 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15913    procedure xyz;
15914 ^directory/^[directory]^main.adb:24:10: xyz <= body
15915    procedure xyz is
15916 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15917    xyz : Integer;
15918 @end smallexample
15919
15920 @noindent
15921 This can make it easier to find exactly the location your are looking
15922 for.
15923
15924 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15925 Find references to all entities containing an x that are
15926 referenced on line 123 of main.ads.
15927 The references will be searched only in main.ads and foo.adb.
15928
15929 @item gnatfind main.ads:123
15930 Find declarations and bodies for all entities that are referenced on
15931 line 123 of main.ads.
15932
15933 This is the same as @code{gnatfind "*":main.adb:123}.
15934
15935 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15936 Find the declaration for the entity referenced at column 45 in
15937 line 123 of file main.adb in directory mydir. Note that it
15938 is usual to omit the identifier name when the column is given,
15939 since the column position identifies a unique reference.
15940
15941 The column has to be the beginning of the identifier, and should not
15942 point to any character in the middle of the identifier.
15943
15944 @end table
15945
15946 @c *********************************
15947 @node The GNAT Pretty-Printer gnatpp
15948 @chapter The GNAT Pretty-Printer @command{gnatpp}
15949 @findex gnatpp
15950 @cindex Pretty-Printer
15951
15952 @noindent
15953 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15954 for source reformatting / pretty-printing.
15955 It takes an Ada source file as input and generates a reformatted
15956 version as output.
15957 You can specify various style directives via switches; e.g.,
15958 identifier case conventions, rules of indentation, and comment layout.
15959
15960 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15961 tree for the input source and thus requires the input to be syntactically and
15962 semantically legal.
15963 If this condition is not met, @command{gnatpp} will terminate with an
15964 error message; no output file will be generated.
15965
15966 If the source files presented to @command{gnatpp} contain
15967 preprocessing directives, then the output file will
15968 correspond to the generated source after all
15969 preprocessing is carried out. There is no way
15970 using @command{gnatpp} to obtain pretty printed files that
15971 include the preprocessing directives.
15972
15973 If the compilation unit
15974 contained in the input source depends semantically upon units located
15975 outside the current directory, you have to provide the source search path
15976 when invoking @command{gnatpp}, if these units are contained in files with
15977 names that do not follow the GNAT file naming rules, you have to provide
15978 the configuration file describing the corresponding naming scheme;
15979 see the description of the @command{gnatpp}
15980 switches below. Another possibility is to use a project file and to
15981 call @command{gnatpp} through the @command{gnat} driver
15982
15983 The @command{gnatpp} command has the form
15984
15985 @smallexample
15986 $ gnatpp @ovar{switches} @var{filename}
15987 @end smallexample
15988
15989 @noindent
15990 where
15991 @itemize @bullet
15992 @item
15993 @var{switches} is an optional sequence of switches defining such properties as
15994 the formatting rules, the source search path, and the destination for the
15995 output source file
15996
15997 @item
15998 @var{filename} is the name (including the extension) of the source file to
15999 reformat; ``wildcards'' or several file names on the same gnatpp command are
16000 allowed.  The file name may contain path information; it does not have to
16001 follow the GNAT file naming rules
16002 @end itemize
16003
16004 @menu
16005 * Switches for gnatpp::
16006 * Formatting Rules::
16007 @end menu
16008
16009 @node Switches for gnatpp
16010 @section Switches for @command{gnatpp}
16011
16012 @noindent
16013 The following subsections describe the various switches accepted by
16014 @command{gnatpp}, organized by category.
16015
16016 @ifclear vms
16017 You specify a switch by supplying a name and generally also a value.
16018 In many cases the values for a switch with a given name are incompatible with
16019 each other
16020 (for example the switch that controls the casing of a reserved word may have
16021 exactly one value: upper case, lower case, or
16022 mixed case) and thus exactly one such switch can be in effect for an
16023 invocation of @command{gnatpp}.
16024 If more than one is supplied, the last one is used.
16025 However, some values for the same switch are mutually compatible.
16026 You may supply several such switches to @command{gnatpp}, but then
16027 each must be specified in full, with both the name and the value.
16028 Abbreviated forms (the name appearing once, followed by each value) are
16029 not permitted.
16030 For example, to set
16031 the alignment of the assignment delimiter both in declarations and in
16032 assignment statements, you must write @option{-A2A3}
16033 (or @option{-A2 -A3}), but not @option{-A23}.
16034 @end ifclear
16035
16036 @ifset vms
16037 In many cases the set of options for a given qualifier are incompatible with
16038 each other (for example the qualifier that controls the casing of a reserved
16039 word may have exactly one option, which specifies either upper case, lower
16040 case, or mixed case), and thus exactly one such option can be in effect for
16041 an invocation of @command{gnatpp}.
16042 If more than one is supplied, the last one is used.
16043 However, some qualifiers have options that are mutually compatible,
16044 and then you may then supply several such options when invoking
16045 @command{gnatpp}.
16046 @end ifset
16047
16048 In most cases, it is obvious whether or not the
16049 ^values for a switch with a given name^options for a given qualifier^
16050 are compatible with each other.
16051 When the semantics might not be evident, the summaries below explicitly
16052 indicate the effect.
16053
16054 @menu
16055 * Alignment Control::
16056 * Casing Control::
16057 * Construct Layout Control::
16058 * General Text Layout Control::
16059 * Other Formatting Options::
16060 * Setting the Source Search Path::
16061 * Output File Control::
16062 * Other gnatpp Switches::
16063 @end menu
16064
16065 @node Alignment Control
16066 @subsection Alignment Control
16067 @cindex Alignment control in @command{gnatpp}
16068
16069 @noindent
16070 Programs can be easier to read if certain constructs are vertically aligned.
16071 By default all alignments are set ON.
16072 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16073 OFF, and then use one or more of the other
16074 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16075 to activate alignment for specific constructs.
16076
16077 @table @option
16078 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16079
16080 @ifset vms
16081 @item /ALIGN=ON
16082 Set all alignments to ON
16083 @end ifset
16084
16085 @item ^-A0^/ALIGN=OFF^
16086 Set all alignments to OFF
16087
16088 @item ^-A1^/ALIGN=COLONS^
16089 Align @code{:} in declarations
16090
16091 @item ^-A2^/ALIGN=DECLARATIONS^
16092 Align @code{:=} in initializations in declarations
16093
16094 @item ^-A3^/ALIGN=STATEMENTS^
16095 Align @code{:=} in assignment statements
16096
16097 @item ^-A4^/ALIGN=ARROWS^
16098 Align @code{=>} in associations
16099
16100 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16101 Align @code{at} keywords in the component clauses in record
16102 representation clauses
16103 @end table
16104
16105 @noindent
16106 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16107 is allowed.
16108
16109 @node Casing Control
16110 @subsection Casing Control
16111 @cindex Casing control in @command{gnatpp}
16112
16113 @noindent
16114 @command{gnatpp} allows you to specify the casing for reserved words,
16115 pragma names, attribute designators and identifiers.
16116 For identifiers you may define a
16117 general rule for name casing but also override this rule
16118 via a set of dictionary files.
16119
16120 Three types of casing are supported: lower case, upper case, and mixed case.
16121 Lower and upper case are self-explanatory (but since some letters in
16122 Latin1 and other GNAT-supported character sets
16123 exist only in lower-case form, an upper case conversion will have no
16124 effect on them.)
16125 ``Mixed case'' means that the first letter, and also each letter immediately
16126 following an underscore, are converted to their uppercase forms;
16127 all the other letters are converted to their lowercase forms.
16128
16129 @table @option
16130 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16131 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16132 Attribute designators are lower case
16133
16134 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16135 Attribute designators are upper case
16136
16137 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16138 Attribute designators are mixed case (this is the default)
16139
16140 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16141 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16142 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16143 lower case (this is the default)
16144
16145 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16146 Keywords are upper case
16147
16148 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16149 @item ^-nD^/NAME_CASING=AS_DECLARED^
16150 Name casing for defining occurrences are as they appear in the source file
16151 (this is the default)
16152
16153 @item ^-nU^/NAME_CASING=UPPER_CASE^
16154 Names are in upper case
16155
16156 @item ^-nL^/NAME_CASING=LOWER_CASE^
16157 Names are in lower case
16158
16159 @item ^-nM^/NAME_CASING=MIXED_CASE^
16160 Names are in mixed case
16161
16162 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16163 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16164 Pragma names are lower case
16165
16166 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16167 Pragma names are upper case
16168
16169 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16170 Pragma names are mixed case (this is the default)
16171
16172 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16173 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16174 Use @var{file} as a @emph{dictionary file} that defines
16175 the casing for a set of specified names,
16176 thereby overriding the effect on these names by
16177 any explicit or implicit
16178 ^-n^/NAME_CASING^ switch.
16179 To supply more than one dictionary file,
16180 use ^several @option{-D} switches^a list of files as options^.
16181
16182 @noindent
16183 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16184 to define the casing for the Ada predefined names and
16185 the names declared in the GNAT libraries.
16186
16187 @item ^-D-^/SPECIFIC_CASING^
16188 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16189 Do not use the default dictionary file;
16190 instead, use the casing
16191 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16192 dictionary file(s)
16193 @end table
16194
16195 @noindent
16196 The structure of a dictionary file, and details on the conventions
16197 used in the default dictionary file, are defined in @ref{Name Casing}.
16198
16199 The @option{^-D-^/SPECIFIC_CASING^} and
16200 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16201 compatible.
16202
16203 @node Construct Layout Control
16204 @subsection Construct Layout Control
16205 @cindex Layout control in @command{gnatpp}
16206
16207 @noindent
16208 This group of @command{gnatpp} switches controls the layout of comments and
16209 complex syntactic constructs.  See @ref{Formatting Comments} for details
16210 on their effect.
16211
16212 @table @option
16213 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16214 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16215 All the comments remain unchanged
16216
16217 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16218 GNAT-style comment line indentation (this is the default).
16219
16220 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16221 Reference-manual comment line indentation.
16222
16223 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16224 GNAT-style comment beginning
16225
16226 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16227 Reformat comment blocks
16228
16229 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16230 Keep unchanged special form comments
16231
16232 Reformat comment blocks
16233
16234 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16235 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16236 GNAT-style layout (this is the default)
16237
16238 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16239 Compact layout
16240
16241 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16242 Uncompact layout
16243
16244 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16245 @item ^-N^/NOTABS^
16246 All the VT characters are removed from the comment text. All the HT characters
16247 are expanded with the sequences of space characters to get to the next tab
16248 stops.
16249
16250 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16251 @item ^--no-separate-is^/NO_SEPARATE_IS^
16252 Do not place the keyword @code{is} on a separate line in a subprogram body in
16253 case if the spec occupies more then one line.
16254
16255 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16256 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16257 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16258 keyword @code{then} in IF statements on a separate line.
16259
16260 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16261 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16262 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16263 keyword @code{then} in IF statements on a separate line. This option is
16264 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16265
16266 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16267 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16268 Start each USE clause in a context clause from a separate line.
16269
16270 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16271 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16272 Use a separate line for a loop or block statement name, but do not use an extra
16273 indentation level for the statement itself.
16274
16275 @end table
16276
16277 @ifclear vms
16278 @noindent
16279 The @option{-c1} and @option{-c2} switches are incompatible.
16280 The @option{-c3} and @option{-c4} switches are compatible with each other and
16281 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16282 the other comment formatting switches.
16283
16284 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16285 @end ifclear
16286
16287 @ifset vms
16288 @noindent
16289 For the @option{/COMMENTS_LAYOUT} qualifier:
16290 @itemize @bullet
16291 @item
16292 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16293 @item
16294 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16295 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16296 @end itemize
16297
16298 @noindent
16299 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16300 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16301 @end ifset
16302
16303 @node General Text Layout Control
16304 @subsection General Text Layout Control
16305
16306 @noindent
16307 These switches allow control over line length and indentation.
16308
16309 @table @option
16310 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16311 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16312 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16313
16314 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16315 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16316 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16317
16318 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16319 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16320 Indentation level for continuation lines (relative to the line being
16321 continued), @var{nnn} from 1@dots{}9.
16322 The default
16323 value is one less then the (normal) indentation level, unless the
16324 indentation is set to 1 (in which case the default value for continuation
16325 line indentation is also 1)
16326 @end table
16327
16328 @node Other Formatting Options
16329 @subsection Other Formatting Options
16330
16331 @noindent
16332 These switches control the inclusion of missing end/exit labels, and
16333 the indentation level in @b{case} statements.
16334
16335 @table @option
16336 @item ^-e^/NO_MISSED_LABELS^
16337 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16338 Do not insert missing end/exit labels. An end label is the name of
16339 a construct that may optionally be repeated at the end of the
16340 construct's declaration;
16341 e.g., the names of packages, subprograms, and tasks.
16342 An exit label is the name of a loop that may appear as target
16343 of an exit statement within the loop.
16344 By default, @command{gnatpp} inserts these end/exit labels when
16345 they are absent from the original source. This option suppresses such
16346 insertion, so that the formatted source reflects the original.
16347
16348 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16349 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16350 Insert a Form Feed character after a pragma Page.
16351
16352 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16353 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16354 Do not use an additional indentation level for @b{case} alternatives
16355 and variants if there are @var{nnn} or more (the default
16356 value is 10).
16357 If @var{nnn} is 0, an additional indentation level is
16358 used for @b{case} alternatives and variants regardless of their number.
16359 @end table
16360
16361 @node Setting the Source Search Path
16362 @subsection Setting the Source Search Path
16363
16364 @noindent
16365 To define the search path for the input source file, @command{gnatpp}
16366 uses the same switches as the GNAT compiler, with the same effects.
16367
16368 @table @option
16369 @item ^-I^/SEARCH=^@var{dir}
16370 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16371 The same as the corresponding gcc switch
16372
16373 @item ^-I-^/NOCURRENT_DIRECTORY^
16374 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16375 The same as the corresponding gcc switch
16376
16377 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16378 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16379 The same as the corresponding gcc switch
16380
16381 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16382 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16383 The same as the corresponding gcc switch
16384
16385 @end table
16386
16387 @node Output File Control
16388 @subsection Output File Control
16389
16390 @noindent
16391 By default the output is sent to the file whose name is obtained by appending
16392 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16393 (if the file with this name already exists, it is unconditionally overwritten).
16394 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16395 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16396 as output file.
16397 The output may be redirected by the following switches:
16398
16399 @table @option
16400 @item ^-pipe^/STANDARD_OUTPUT^
16401 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16402 Send the output to @code{Standard_Output}
16403
16404 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16405 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16406 Write the output into @var{output_file}.
16407 If @var{output_file} already exists, @command{gnatpp} terminates without
16408 reading or processing the input file.
16409
16410 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16411 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16412 Write the output into @var{output_file}, overwriting the existing file
16413 (if one is present).
16414
16415 @item ^-r^/REPLACE^
16416 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16417 Replace the input source file with the reformatted output, and copy the
16418 original input source into the file whose name is obtained by appending the
16419 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16420 If a file with this name already exists, @command{gnatpp} terminates without
16421 reading or processing the input file.
16422
16423 @item ^-rf^/OVERRIDING_REPLACE^
16424 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16425 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16426 already exists, it is overwritten.
16427
16428 @item ^-rnb^/REPLACE_NO_BACKUP^
16429 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16430 Replace the input source file with the reformatted output without
16431 creating any backup copy of the input source.
16432
16433 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16434 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16435 Specifies the format of the reformatted output file. The @var{xxx}
16436 ^string specified with the switch^option^ may be either
16437 @itemize @bullet
16438 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16439 @item ``@option{^crlf^CRLF^}''
16440 the same as @option{^crlf^CRLF^}
16441 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16442 @item ``@option{^lf^LF^}''
16443 the same as @option{^unix^UNIX^}
16444 @end itemize
16445
16446 @item ^-W^/RESULT_ENCODING=^@var{e}
16447 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16448 Specify the wide character encoding method used to write the code in the
16449 result file
16450 @var{e} is one of the following:
16451
16452 @itemize @bullet
16453
16454 @item ^h^HEX^
16455 Hex encoding
16456
16457 @item ^u^UPPER^
16458 Upper half encoding
16459
16460 @item ^s^SHIFT_JIS^
16461 Shift/JIS encoding
16462
16463 @item ^e^EUC^
16464 EUC encoding
16465
16466 @item ^8^UTF8^
16467 UTF-8 encoding
16468
16469 @item ^b^BRACKETS^
16470 Brackets encoding (default value)
16471 @end itemize
16472
16473 @end table
16474
16475 @noindent
16476 Options @option{^-pipe^/STANDARD_OUTPUT^},
16477 @option{^-o^/OUTPUT^} and
16478 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16479 contains only one file to reformat.
16480 Option
16481 @option{^--eol^/END_OF_LINE^}
16482 and
16483 @option{^-W^/RESULT_ENCODING^}
16484 cannot be used together
16485 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16486
16487 @node Other gnatpp Switches
16488 @subsection Other @code{gnatpp} Switches
16489
16490 @noindent
16491 The additional @command{gnatpp} switches are defined in this subsection.
16492
16493 @table @option
16494 @item ^-files @var{filename}^/FILES=@var{output_file}^
16495 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16496 Take the argument source files from the specified file. This file should be an
16497 ordinary textual file containing file names separated by spaces or
16498 line breaks. You can use this switch more then once in the same call to
16499 @command{gnatpp}. You also can combine this switch with explicit list of
16500 files.
16501
16502 @item ^-v^/VERBOSE^
16503 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16504 Verbose mode;
16505 @command{gnatpp} generates version information and then
16506 a trace of the actions it takes to produce or obtain the ASIS tree.
16507
16508 @item ^-w^/WARNINGS^
16509 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16510 Warning mode;
16511 @command{gnatpp} generates a warning whenever it cannot provide
16512 a required layout in the result source.
16513 @end table
16514
16515 @node Formatting Rules
16516 @section Formatting Rules
16517
16518 @noindent
16519 The following subsections show how @command{gnatpp} treats ``white space'',
16520 comments, program layout, and name casing.
16521 They provide the detailed descriptions of the switches shown above.
16522
16523 @menu
16524 * White Space and Empty Lines::
16525 * Formatting Comments::
16526 * Construct Layout::
16527 * Name Casing::
16528 @end menu
16529
16530 @node White Space and Empty Lines
16531 @subsection White Space and Empty Lines
16532
16533 @noindent
16534 @command{gnatpp} does not have an option to control space characters.
16535 It will add or remove spaces according to the style illustrated by the
16536 examples in the @cite{Ada Reference Manual}.
16537
16538 The only format effectors
16539 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16540 that will appear in the output file are platform-specific line breaks,
16541 and also format effectors within (but not at the end of) comments.
16542 In particular, each horizontal tab character that is not inside
16543 a comment will be treated as a space and thus will appear in the
16544 output file as zero or more spaces depending on
16545 the reformatting of the line in which it appears.
16546 The only exception is a Form Feed character, which is inserted after a
16547 pragma @code{Page} when @option{-ff} is set.
16548
16549 The output file will contain no lines with trailing ``white space'' (spaces,
16550 format effectors).
16551
16552 Empty lines in the original source are preserved
16553 only if they separate declarations or statements.
16554 In such contexts, a
16555 sequence of two or more empty lines is replaced by exactly one empty line.
16556 Note that a blank line will be removed if it separates two ``comment blocks''
16557 (a comment block is a sequence of whole-line comments).
16558 In order to preserve a visual separation between comment blocks, use an
16559 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16560 Likewise, if for some reason you wish to have a sequence of empty lines,
16561 use a sequence of empty comments instead.
16562
16563 @node Formatting Comments
16564 @subsection Formatting Comments
16565
16566 @noindent
16567 Comments in Ada code are of two kinds:
16568 @itemize @bullet
16569 @item
16570 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16571 ``white space'') on a line
16572
16573 @item
16574 an @emph{end-of-line comment}, which follows some other Ada lexical element
16575 on the same line.
16576 @end itemize
16577
16578 @noindent
16579 The indentation of a whole-line comment is that of either
16580 the preceding or following line in
16581 the formatted source, depending on switch settings as will be described below.
16582
16583 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16584 between the end of the preceding Ada lexical element and the beginning
16585 of the comment as appear in the original source,
16586 unless either the comment has to be split to
16587 satisfy the line length limitation, or else the next line contains a
16588 whole line comment that is considered a continuation of this end-of-line
16589 comment (because it starts at the same position).
16590 In the latter two
16591 cases, the start of the end-of-line comment is moved right to the nearest
16592 multiple of the indentation level.
16593 This may result in a ``line overflow'' (the right-shifted comment extending
16594 beyond the maximum line length), in which case the comment is split as
16595 described below.
16596
16597 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16598 (GNAT-style comment line indentation)
16599 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16600 (reference-manual comment line indentation).
16601 With reference-manual style, a whole-line comment is indented as if it
16602 were a declaration or statement at the same place
16603 (i.e., according to the indentation of the preceding line(s)).
16604 With GNAT style, a whole-line comment that is immediately followed by an
16605 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16606 word @b{begin}, is indented based on the construct that follows it.
16607
16608 For example:
16609 @smallexample @c ada
16610 @cartouche
16611 if A then
16612     null;
16613        -- some comment
16614 else
16615    null;
16616 end if;
16617 @end cartouche
16618 @end smallexample
16619
16620 @noindent
16621 Reference-manual indentation produces:
16622
16623 @smallexample @c ada
16624 @cartouche
16625 if A then
16626    null;
16627    --  some comment
16628 else
16629    null;
16630 end if;
16631 @end cartouche
16632 @end smallexample
16633
16634 @noindent
16635 while GNAT-style indentation produces:
16636
16637 @smallexample @c ada
16638 @cartouche
16639 if A then
16640    null;
16641 --  some comment
16642 else
16643    null;
16644 end if;
16645 @end cartouche
16646 @end smallexample
16647
16648 @noindent
16649 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16650 (GNAT style comment beginning) has the following
16651 effect:
16652
16653 @itemize @bullet
16654 @item
16655 For each whole-line comment that does not end with two hyphens,
16656 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16657 to ensure that there are at least two spaces between these hyphens and the
16658 first non-blank character of the comment.
16659 @end itemize
16660
16661 @noindent
16662 For an end-of-line comment, if in the original source the next line is a
16663 whole-line comment that starts at the same position
16664 as the end-of-line comment,
16665 then the whole-line comment (and all whole-line comments
16666 that follow it and that start at the same position)
16667 will start at this position in the output file.
16668
16669 @noindent
16670 That is, if in the original source we have:
16671
16672 @smallexample @c ada
16673 @cartouche
16674 begin
16675 A := B + C;            --  B must be in the range Low1..High1
16676                        --  C must be in the range Low2..High2
16677              --B+C will be in the range Low1+Low2..High1+High2
16678 X := X + 1;
16679 @end cartouche
16680 @end smallexample
16681
16682 @noindent
16683 Then in the formatted source we get
16684
16685 @smallexample @c ada
16686 @cartouche
16687 begin
16688    A := B + C;            --  B must be in the range Low1..High1
16689                           --  C must be in the range Low2..High2
16690    --  B+C will be in the range Low1+Low2..High1+High2
16691    X := X + 1;
16692 @end cartouche
16693 @end smallexample
16694
16695 @noindent
16696 A comment that exceeds the line length limit will be split.
16697 Unless switch
16698 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16699 the line belongs to a reformattable block, splitting the line generates a
16700 @command{gnatpp} warning.
16701 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16702 comments may be reformatted in typical
16703 word processor style (that is, moving words between lines and putting as
16704 many words in a line as possible).
16705
16706 @noindent
16707 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16708 that has a special format (that is, a character that is neither a letter nor digit
16709 not white space nor line break immediately following the leading @code{--} of
16710 the comment) should be without any change moved from the argument source
16711 into reformatted source. This switch allows to preserve comments that are used
16712 as a special marks in the code (e.g.@: SPARK annotation).
16713
16714 @node Construct Layout
16715 @subsection Construct Layout
16716
16717 @noindent
16718 In several cases the suggested layout in the Ada Reference Manual includes
16719 an extra level of indentation that many programmers prefer to avoid. The
16720 affected cases include:
16721
16722 @itemize @bullet
16723
16724 @item Record type declaration (RM 3.8)
16725
16726 @item Record representation clause (RM 13.5.1)
16727
16728 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16729
16730 @item Block statement in case if a block has a statement identifier (RM 5.6)
16731 @end itemize
16732
16733 @noindent
16734 In compact mode (when GNAT style layout or compact layout is set),
16735 the pretty printer uses one level of indentation instead
16736 of two. This is achieved in the record definition and record representation
16737 clause cases by putting the @code{record} keyword on the same line as the
16738 start of the declaration or representation clause, and in the block and loop
16739 case by putting the block or loop header on the same line as the statement
16740 identifier.
16741
16742 @noindent
16743 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16744 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16745 layout on the one hand, and uncompact layout
16746 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16747 can be illustrated by the following examples:
16748
16749 @iftex
16750 @cartouche
16751 @multitable @columnfractions .5 .5
16752 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16753
16754 @item
16755 @smallexample @c ada
16756 type q is record
16757    a : integer;
16758    b : integer;
16759 end record;
16760 @end smallexample
16761 @tab
16762 @smallexample @c ada
16763 type q is
16764    record
16765       a : integer;
16766       b : integer;
16767    end record;
16768 @end smallexample
16769
16770 @item
16771 @smallexample @c ada
16772 for q use record
16773    a at 0 range  0 .. 31;
16774    b at 4 range  0 .. 31;
16775 end record;
16776 @end smallexample
16777 @tab
16778 @smallexample @c ada
16779 for q use
16780    record
16781       a at 0 range  0 .. 31;
16782       b at 4 range  0 .. 31;
16783    end record;
16784 @end smallexample
16785
16786 @item
16787 @smallexample @c ada
16788 Block : declare
16789    A : Integer := 3;
16790 begin
16791    Proc (A, A);
16792 end Block;
16793 @end smallexample
16794 @tab
16795 @smallexample @c ada
16796 Block :
16797    declare
16798       A : Integer := 3;
16799    begin
16800       Proc (A, A);
16801    end Block;
16802 @end smallexample
16803
16804 @item
16805 @smallexample @c ada
16806 Clear : for J in 1 .. 10 loop
16807    A (J) := 0;
16808 end loop Clear;
16809 @end smallexample
16810 @tab
16811 @smallexample @c ada
16812 Clear :
16813    for J in 1 .. 10 loop
16814       A (J) := 0;
16815    end loop Clear;
16816 @end smallexample
16817 @end multitable
16818 @end cartouche
16819 @end iftex
16820
16821 @ifnottex
16822 @smallexample
16823 @cartouche
16824 GNAT style, compact layout              Uncompact layout
16825
16826 type q is record                        type q is
16827    a : integer;                            record
16828    b : integer;                               a : integer;
16829 end record;                                   b : integer;
16830                                            end record;
16831
16832 for q use record                        for q use
16833    a at 0 range  0 .. 31;                  record
16834    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16835 end record;                                   b at 4 range  0 .. 31;
16836                                            end record;
16837
16838 Block : declare                         Block :
16839    A : Integer := 3;                       declare
16840 begin                                         A : Integer := 3;
16841    Proc (A, A);                            begin
16842 end Block;                                    Proc (A, A);
16843                                            end Block;
16844
16845 Clear : for J in 1 .. 10 loop           Clear :
16846    A (J) := 0;                             for J in 1 .. 10 loop
16847 end loop Clear;                               A (J) := 0;
16848                                            end loop Clear;
16849 @end cartouche
16850 @end smallexample
16851 @end ifnottex
16852
16853 @noindent
16854 A further difference between GNAT style layout and compact layout is that
16855 GNAT style layout inserts empty lines as separation for
16856 compound statements, return statements and bodies.
16857
16858 Note that the layout specified by
16859 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16860 for named block and loop statements overrides the layout defined by these
16861 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16862 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16863 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16864
16865 @node Name Casing
16866 @subsection Name Casing
16867
16868 @noindent
16869 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16870 the same casing as the corresponding defining identifier.
16871
16872 You control the casing for defining occurrences via the
16873 @option{^-n^/NAME_CASING^} switch.
16874 @ifclear vms
16875 With @option{-nD} (``as declared'', which is the default),
16876 @end ifclear
16877 @ifset vms
16878 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16879 @end ifset
16880 defining occurrences appear exactly as in the source file
16881 where they are declared.
16882 The other ^values for this switch^options for this qualifier^ ---
16883 @option{^-nU^UPPER_CASE^},
16884 @option{^-nL^LOWER_CASE^},
16885 @option{^-nM^MIXED_CASE^} ---
16886 result in
16887 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16888 If @command{gnatpp} changes the casing of a defining
16889 occurrence, it analogously changes the casing of all the
16890 usage occurrences of this name.
16891
16892 If the defining occurrence of a name is not in the source compilation unit
16893 currently being processed by @command{gnatpp}, the casing of each reference to
16894 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16895 switch (subject to the dictionary file mechanism described below).
16896 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16897 had affected the
16898 casing for the defining occurrence of the name.
16899
16900 Some names may need to be spelled with casing conventions that are not
16901 covered by the upper-, lower-, and mixed-case transformations.
16902 You can arrange correct casing by placing such names in a
16903 @emph{dictionary file},
16904 and then supplying a @option{^-D^/DICTIONARY^} switch.
16905 The casing of names from dictionary files overrides
16906 any @option{^-n^/NAME_CASING^} switch.
16907
16908 To handle the casing of Ada predefined names and the names from GNAT libraries,
16909 @command{gnatpp} assumes a default dictionary file.
16910 The name of each predefined entity is spelled with the same casing as is used
16911 for the entity in the @cite{Ada Reference Manual}.
16912 The name of each entity in the GNAT libraries is spelled with the same casing
16913 as is used in the declaration of that entity.
16914
16915 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16916 default dictionary file.
16917 Instead, the casing for predefined and GNAT-defined names will be established
16918 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16919 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16920 will appear as just shown,
16921 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16922 To ensure that even such names are rendered in uppercase,
16923 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16924 (or else, less conveniently, place these names in upper case in a dictionary
16925 file).
16926
16927 A dictionary file is
16928 a plain text file; each line in this file can be either a blank line
16929 (containing only space characters and ASCII.HT characters), an Ada comment
16930 line, or the specification of exactly one @emph{casing schema}.
16931
16932 A casing schema is a string that has the following syntax:
16933
16934 @smallexample
16935 @cartouche
16936   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16937
16938   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16939 @end cartouche
16940 @end smallexample
16941
16942 @noindent
16943 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16944 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16945
16946 The casing schema string can be followed by white space and/or an Ada-style
16947 comment; any amount of white space is allowed before the string.
16948
16949 If a dictionary file is passed as
16950 @ifclear vms
16951 the value of a @option{-D@var{file}} switch
16952 @end ifclear
16953 @ifset vms
16954 an option to the @option{/DICTIONARY} qualifier
16955 @end ifset
16956 then for every
16957 simple name and every identifier, @command{gnatpp} checks if the dictionary
16958 defines the casing for the name or for some of its parts (the term ``subword''
16959 is used below to denote the part of a name which is delimited by ``_'' or by
16960 the beginning or end of the word and which does not contain any ``_'' inside):
16961
16962 @itemize @bullet
16963 @item
16964 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16965 the casing defined by the dictionary; no subwords are checked for this word
16966
16967 @item
16968 for every subword @command{gnatpp} checks if the dictionary contains the
16969 corresponding string of the form @code{*@var{simple_identifier}*},
16970 and if it does, the casing of this @var{simple_identifier} is used
16971 for this subword
16972
16973 @item
16974 if the whole name does not contain any ``_'' inside, and if for this name
16975 the dictionary contains two entries - one of the form @var{identifier},
16976 and another - of the form *@var{simple_identifier}*, then the first one
16977 is applied to define the casing of this name
16978
16979 @item
16980 if more than one dictionary file is passed as @command{gnatpp} switches, each
16981 dictionary adds new casing exceptions and overrides all the existing casing
16982 exceptions set by the previous dictionaries
16983
16984 @item
16985 when @command{gnatpp} checks if the word or subword is in the dictionary,
16986 this check is not case sensitive
16987 @end itemize
16988
16989 @noindent
16990 For example, suppose we have the following source to reformat:
16991
16992 @smallexample @c ada
16993 @cartouche
16994 procedure test is
16995    name1 : integer := 1;
16996    name4_name3_name2 : integer := 2;
16997    name2_name3_name4 : Boolean;
16998    name1_var : Float;
16999 begin
17000    name2_name3_name4 := name4_name3_name2 > name1;
17001 end;
17002 @end cartouche
17003 @end smallexample
17004
17005 @noindent
17006 And suppose we have two dictionaries:
17007
17008 @smallexample
17009 @cartouche
17010 @i{dict1:}
17011    NAME1
17012    *NaMe3*
17013    *Name1*
17014 @end cartouche
17015
17016 @cartouche
17017 @i{dict2:}
17018   *NAME3*
17019 @end cartouche
17020 @end smallexample
17021
17022 @noindent
17023 If @command{gnatpp} is called with the following switches:
17024
17025 @smallexample
17026 @ifclear vms
17027 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17028 @end ifclear
17029 @ifset vms
17030 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17031 @end ifset
17032 @end smallexample
17033
17034 @noindent
17035 then we will get the following name casing in the @command{gnatpp} output:
17036
17037 @smallexample @c ada
17038 @cartouche
17039 procedure Test is
17040    NAME1             : Integer := 1;
17041    Name4_NAME3_Name2 : Integer := 2;
17042    Name2_NAME3_Name4 : Boolean;
17043    Name1_Var         : Float;
17044 begin
17045    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17046 end Test;
17047 @end cartouche
17048 @end smallexample
17049
17050 @c *********************************
17051 @node The GNAT Metric Tool gnatmetric
17052 @chapter The GNAT Metric Tool @command{gnatmetric}
17053 @findex gnatmetric
17054 @cindex Metric tool
17055
17056 @noindent
17057 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17058 for computing various program metrics.
17059 It takes an Ada source file as input and generates a file containing the
17060 metrics data as output. Various switches control which
17061 metrics are computed and output.
17062
17063 @command{gnatmetric} generates and uses the ASIS
17064 tree for the input source and thus requires the input to be syntactically and
17065 semantically legal.
17066 If this condition is not met, @command{gnatmetric} will generate
17067 an error message; no metric information for this file will be
17068 computed and reported.
17069
17070 If the compilation unit contained in the input source depends semantically
17071 upon units in files located outside the current directory, you have to provide
17072 the source search path when invoking @command{gnatmetric}.
17073 If it depends semantically upon units that are contained
17074 in files with names that do not follow the GNAT file naming rules, you have to
17075 provide the configuration file describing the corresponding naming scheme (see
17076 the description of the @command{gnatmetric} switches below.)
17077 Alternatively, you may use a project file and invoke @command{gnatmetric}
17078 through the @command{gnat} driver.
17079
17080 The @command{gnatmetric} command has the form
17081
17082 @smallexample
17083 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17084 @end smallexample
17085
17086 @noindent
17087 where
17088 @itemize @bullet
17089 @item
17090 @var{switches} specify the metrics to compute and define the destination for
17091 the output
17092
17093 @item
17094 Each @var{filename} is the name (including the extension) of a source
17095 file to process. ``Wildcards'' are allowed, and
17096 the file name may contain path information.
17097 If no @var{filename} is supplied, then the @var{switches} list must contain
17098 at least one
17099 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17100 Including both a @option{-files} switch and one or more
17101 @var{filename} arguments is permitted.
17102
17103 @item
17104 @samp{-cargs @var{gcc_switches}} is a list of switches for
17105 @command{gcc}. They will be passed on to all compiler invocations made by
17106 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17107 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17108 and use the @option{-gnatec} switch to set the configuration file.
17109 @end itemize
17110
17111 @menu
17112 * Switches for gnatmetric::
17113 @end menu
17114
17115 @node Switches for gnatmetric
17116 @section Switches for @command{gnatmetric}
17117
17118 @noindent
17119 The following subsections describe the various switches accepted by
17120 @command{gnatmetric}, organized by category.
17121
17122 @menu
17123 * Output Files Control::
17124 * Disable Metrics For Local Units::
17125 * Specifying a set of metrics to compute::
17126 * Other gnatmetric Switches::
17127 * Generate project-wide metrics::
17128 @end menu
17129
17130 @node Output Files Control
17131 @subsection Output File Control
17132 @cindex Output file control in @command{gnatmetric}
17133
17134 @noindent
17135 @command{gnatmetric} has two output formats. It can generate a
17136 textual (human-readable) form, and also XML. By default only textual
17137 output is generated.
17138
17139 When generating the output in textual form, @command{gnatmetric} creates
17140 for each Ada source file a corresponding text file
17141 containing the computed metrics, except for the case when the set of metrics
17142 specified by gnatmetric parameters consists only of metrics that are computed
17143 for the whole set of analyzed sources, but not for each Ada source.
17144 By default, this file is placed in the same directory as where the source
17145 file is located, and its name is obtained
17146 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17147 input file.
17148
17149 All the output information generated in XML format is placed in a single
17150 file. By default this file is placed in the current directory and has the
17151 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17152
17153 Some of the computed metrics are summed over the units passed to
17154 @command{gnatmetric}; for example, the total number of lines of code.
17155 By default this information is sent to @file{stdout}, but a file
17156 can be specified with the @option{-og} switch.
17157
17158 The following switches control the @command{gnatmetric} output:
17159
17160 @table @option
17161 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17162 @item ^-x^/XML^
17163 Generate the XML output
17164
17165 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17166 @item ^-nt^/NO_TEXT^
17167 Do not generate the output in text form (implies @option{^-x^/XML^})
17168
17169 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17170 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17171 Put textual files with detailed metrics into @var{output_dir}
17172
17173 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17174 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17175 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17176 in the name of the output file.
17177
17178 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17179 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17180 Put global metrics into @var{file_name}
17181
17182 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17183 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17184 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17185
17186 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17187 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17188 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17189 output includes the name(s) of the Ada source file(s) from which the metrics
17190 are computed.  By default each name includes the absolute path. The
17191 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17192 to exclude all directory information from the file names that are output.)
17193
17194 @end table
17195
17196 @node Disable Metrics For Local Units
17197 @subsection Disable Metrics For Local Units
17198 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17199
17200 @noindent
17201 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17202 one compilation
17203 unit per one source file. It computes line metrics for the whole source
17204 file, and it also computes syntax
17205 and complexity metrics for the file's outermost unit.
17206
17207 By default, @command{gnatmetric} will also compute all metrics for certain
17208 kinds of locally declared program units:
17209
17210 @itemize @bullet
17211 @item
17212 subprogram (and generic subprogram) bodies;
17213
17214 @item
17215 package (and generic package) specs and bodies;
17216
17217 @item
17218 task object and type specifications and bodies;
17219
17220 @item
17221 protected object and type specifications and bodies.
17222 @end itemize
17223
17224 @noindent
17225 These kinds of entities will be referred to as
17226 @emph{eligible local program units}, or simply @emph{eligible local units},
17227 @cindex Eligible local unit (for @command{gnatmetric})
17228 in the discussion below.
17229
17230 Note that a subprogram declaration, generic instantiation,
17231 or renaming declaration only receives metrics
17232 computation when it appear as the outermost entity
17233 in a source file.
17234
17235 Suppression of metrics computation for eligible local units can be
17236 obtained via the following switch:
17237
17238 @table @option
17239 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17240 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17241 Do not compute detailed metrics for eligible local program units
17242
17243 @end table
17244
17245 @node Specifying a set of metrics to compute
17246 @subsection Specifying a set of metrics to compute
17247
17248 @noindent
17249 By default all the metrics are computed and reported. The switches
17250 described in this subsection allow you to control, on an individual
17251 basis, whether metrics are computed and
17252 reported. If at least one positive metric
17253 switch is specified (that is, a switch that defines that a given
17254 metric or set of metrics is to be computed), then only
17255 explicitly specified metrics are reported.
17256
17257 @menu
17258 * Line Metrics Control::
17259 * Syntax Metrics Control::
17260 * Complexity Metrics Control::
17261 * Object-Oriented Metrics Control::
17262 @end menu
17263
17264 @node Line Metrics Control
17265 @subsubsection Line Metrics Control
17266 @cindex Line metrics control in @command{gnatmetric}
17267
17268 @noindent
17269 For any (legal) source file, and for each of its
17270 eligible local program units, @command{gnatmetric} computes the following
17271 metrics:
17272
17273 @itemize @bullet
17274 @item
17275 the total number of lines;
17276
17277 @item
17278 the total number of code lines (i.e., non-blank lines that are not comments)
17279
17280 @item
17281 the number of comment lines
17282
17283 @item
17284 the number of code lines containing end-of-line comments;
17285
17286 @item
17287 the comment percentage: the ratio between the number of lines that contain
17288 comments and the number of all non-blank lines, expressed as a percentage;
17289
17290 @item
17291 the number of empty lines and lines containing only space characters and/or
17292 format effectors (blank lines)
17293
17294 @item
17295 the average number of code lines in subprogram bodies, task bodies, entry
17296 bodies and statement sequences in package bodies (this metric is only computed
17297 across the whole set of the analyzed units)
17298
17299 @end itemize
17300
17301 @noindent
17302 @command{gnatmetric} sums the values of the line metrics for all the
17303 files being processed and then generates the cumulative results. The tool
17304 also computes for all the files being processed the average number of code
17305 lines in bodies.
17306
17307 You can use the following switches to select the specific line metrics
17308 to be computed and reported.
17309
17310 @table @option
17311 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17312
17313 @ifclear vms
17314 @cindex @option{--no-lines@var{x}}
17315 @end ifclear
17316
17317 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
17318 Report all the line metrics
17319
17320 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
17321 Do not report any of line metrics
17322
17323 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
17324 Report the number of all lines
17325
17326 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
17327 Do not report the number of all lines
17328
17329 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
17330 Report the number of code lines
17331
17332 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
17333 Do not report the number of code lines
17334
17335 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
17336 Report the number of comment lines
17337
17338 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
17339 Do not report the number of comment lines
17340
17341 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
17342 Report the number of code lines containing
17343 end-of-line comments
17344
17345 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
17346 Do not report the number of code lines containing
17347 end-of-line comments
17348
17349 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
17350 Report the comment percentage in the program text
17351
17352 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
17353 Do not report the comment percentage in the program text
17354
17355 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
17356 Report the number of blank lines
17357
17358 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
17359 Do not report the number of blank lines
17360
17361 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
17362 Report the average number of code lines in subprogram bodies, task bodies,
17363 entry bodies and statement sequences in package bodies. The metric is computed
17364 and reported for the whole set of processed Ada sources only.
17365
17366 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
17367 Do not report the average number of code lines in subprogram bodies,
17368 task bodies, entry bodies and statement sequences in package bodies.
17369
17370 @end table
17371
17372 @node Syntax Metrics Control
17373 @subsubsection Syntax Metrics Control
17374 @cindex Syntax metrics control in @command{gnatmetric}
17375
17376 @noindent
17377 @command{gnatmetric} computes various syntactic metrics for the
17378 outermost unit and for each eligible local unit:
17379
17380 @table @emph
17381 @item LSLOC (``Logical Source Lines Of Code'')
17382 The total number of declarations and the total number of statements
17383
17384 @item Maximal static nesting level of inner program units
17385 According to
17386 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17387 package, a task unit, a protected unit, a
17388 protected entry, a generic unit, or an explicitly declared subprogram other
17389 than an enumeration literal.''
17390
17391 @item Maximal nesting level of composite syntactic constructs
17392 This corresponds to the notion of the
17393 maximum nesting level in the GNAT built-in style checks
17394 (@pxref{Style Checking})
17395 @end table
17396
17397 @noindent
17398 For the outermost unit in the file, @command{gnatmetric} additionally computes
17399 the following metrics:
17400
17401 @table @emph
17402 @item Public subprograms
17403 This metric is computed for package specs. It is the
17404 number of subprograms and generic subprograms declared in the visible
17405 part (including the visible part of nested packages, protected objects, and
17406 protected types).
17407
17408 @item All subprograms
17409 This metric is computed for bodies and subunits. The
17410 metric is equal to a total number of subprogram bodies in the compilation
17411 unit.
17412 Neither generic instantiations nor renamings-as-a-body nor body stubs
17413 are counted. Any subprogram body is counted, independently of its nesting
17414 level and enclosing constructs. Generic bodies and bodies of protected
17415 subprograms are counted in the same way as ``usual'' subprogram bodies.
17416
17417 @item Public types
17418 This metric is computed for package specs and
17419 generic package declarations. It is the total number of types
17420 that can be referenced from outside this compilation unit, plus the
17421 number of types from all the visible parts of all the visible generic
17422 packages. Generic formal types are not counted.  Only types, not subtypes,
17423 are included.
17424
17425 @noindent
17426 Along with the total number of public types, the following
17427 types are counted and reported separately:
17428
17429 @itemize @bullet
17430 @item
17431 Abstract types
17432
17433 @item
17434 Root tagged types (abstract, non-abstract, private, non-private). Type
17435 extensions are @emph{not} counted
17436
17437 @item
17438 Private types (including private extensions)
17439
17440 @item
17441 Task types
17442
17443 @item
17444 Protected types
17445
17446 @end itemize
17447
17448 @item All types
17449 This metric is computed for any compilation unit. It is equal to the total
17450 number of the declarations of different types given in the compilation unit.
17451 The private and the corresponding full type declaration are counted as one
17452 type declaration. Incomplete type declarations and generic formal types
17453 are not counted.
17454 No distinction is made among different kinds of types (abstract,
17455 private etc.); the total number of types is computed and reported.
17456
17457 @end table
17458
17459 @noindent
17460 By default, all the syntax metrics are computed and reported. You can use the
17461 following switches to select specific syntax metrics.
17462
17463 @table @option
17464
17465 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17466
17467 @ifclear vms
17468 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17469 @end ifclear
17470
17471 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17472 Report all the syntax metrics
17473
17474 @item ^--no-syntax-all^/ALL_OFF^
17475 Do not report any of syntax metrics
17476
17477 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17478 Report the total number of declarations
17479
17480 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17481 Do not report the total number of declarations
17482
17483 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17484 Report the total number of statements
17485
17486 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17487 Do not report the total number of statements
17488
17489 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17490 Report the number of public subprograms in a compilation unit
17491
17492 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17493 Do not report the number of public subprograms in a compilation unit
17494
17495 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17496 Report the number of all the subprograms in a compilation unit
17497
17498 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17499 Do not report the number of all the subprograms in a compilation unit
17500
17501 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17502 Report the number of public types in a compilation unit
17503
17504 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17505 Do not report the number of public types in a compilation unit
17506
17507 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17508 Report the number of all the types in a compilation unit
17509
17510 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17511 Do not report the number of all the types in a compilation unit
17512
17513 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17514 Report the maximal program unit nesting level
17515
17516 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17517 Do not report the maximal program unit nesting level
17518
17519 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17520 Report the maximal construct nesting level
17521
17522 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17523 Do not report the maximal construct nesting level
17524
17525 @end table
17526
17527 @node Complexity Metrics Control
17528 @subsubsection Complexity Metrics Control
17529 @cindex Complexity metrics control in @command{gnatmetric}
17530
17531 @noindent
17532 For a program unit that is an executable body (a subprogram body (including
17533 generic bodies), task body, entry body or a package body containing
17534 its own statement sequence) @command{gnatmetric} computes the following
17535 complexity metrics:
17536
17537 @itemize @bullet
17538 @item
17539 McCabe cyclomatic complexity;
17540
17541 @item
17542 McCabe essential complexity;
17543
17544 @item
17545 maximal loop nesting level
17546
17547 @end itemize
17548
17549 @noindent
17550 The McCabe complexity metrics are defined
17551 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17552
17553 According to McCabe, both control statements and short-circuit control forms
17554 should be taken into account when computing cyclomatic complexity. For each
17555 body, we compute three metric values:
17556
17557 @itemize @bullet
17558 @item
17559 the complexity introduced by control
17560 statements only, without taking into account short-circuit forms,
17561
17562 @item
17563 the complexity introduced by short-circuit control forms only, and
17564
17565 @item
17566 the total
17567 cyclomatic complexity, which is the sum of these two values.
17568 @end itemize
17569
17570 @noindent
17571 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17572 the code in the exception handlers and in all the nested program units.
17573
17574 By default, all the complexity metrics are computed and reported.
17575 For more fine-grained control you can use
17576 the following switches:
17577
17578 @table @option
17579 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17580
17581 @ifclear vms
17582 @cindex @option{--no-complexity@var{x}}
17583 @end ifclear
17584
17585 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17586 Report all the complexity metrics
17587
17588 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17589 Do not report any of complexity metrics
17590
17591 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17592 Report the McCabe Cyclomatic Complexity
17593
17594 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17595 Do not report the McCabe Cyclomatic Complexity
17596
17597 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17598 Report the Essential Complexity
17599
17600 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17601 Do not report the Essential Complexity
17602
17603 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17604 Report maximal loop nesting level
17605
17606 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17607 Do not report maximal loop nesting level
17608
17609 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17610 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17611 task bodies, entry bodies and statement sequences in package bodies.
17612 The metric is computed and reported for whole set of processed Ada sources
17613 only.
17614
17615 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17616 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17617 bodies, task bodies, entry bodies and statement sequences in package bodies
17618
17619 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17620 @item ^-ne^/NO_EXITS_AS_GOTOS^
17621 Do not consider @code{exit} statements as @code{goto}s when
17622 computing Essential Complexity
17623
17624 @end table
17625
17626
17627 @node Object-Oriented Metrics Control
17628 @subsubsection Object-Oriented Metrics Control
17629 @cindex Object-Oriented metrics control in @command{gnatmetric}
17630
17631 @noindent
17632 @cindex Coupling metrics (in in @command{gnatmetric})
17633 Coupling metrics are object-oriented metrics that measure the
17634 dependencies between a given class (or a group of classes) and the
17635 ``external world'' (that is, the other classes in the program). In this
17636 subsection the term ``class'' is used in its
17637 traditional object-oriented programming sense
17638 (an instantiable module that contains data and/or method members).
17639 A @emph{category} (of classes)
17640 is a group of closely related classes that are reused and/or
17641 modified together.
17642
17643 A class @code{K}'s @emph{efferent coupling} is the number of classes
17644 that @code{K} depends upon.
17645 A category's efferent coupling is the number of classes outside the
17646 category that the classes inside the category depend upon.
17647
17648 A class @code{K}'s @emph{afferent coupling} is the number of classes
17649 that depend upon @code{K}.
17650 A category's afferent coupling is the number of classes outside the
17651 category that depend on classes belonging to the category.
17652
17653 Ada's implementation of the object-oriented paradigm does not use the
17654 traditional class notion, so the definition of the coupling
17655 metrics for Ada maps the class and class category notions
17656 onto Ada constructs.
17657
17658 For the coupling metrics, several kinds of modules -- a library package,
17659 a library generic package, and a library generic package instantiation --
17660 that define a tagged type or an interface type are
17661 considered to be a class. A category consists of a library package (or
17662 a library generic package) that defines a tagged or an interface type,
17663 together with all its descendant (generic) packages that define tagged
17664 or interface types. For any package counted as a class,
17665 its body (if any) is considered
17666 together with its spec when counting the dependencies. For dependencies
17667 between classes, the Ada semantic dependencies are considered.
17668 For coupling metrics, only dependencies on units that are considered as
17669 classes, are considered.
17670
17671 When computing coupling metrics, @command{gnatmetric} counts only
17672 dependencies between units that are arguments of the gnatmetric call.
17673 Coupling metrics are program-wide (or project-wide) metrics, so to
17674 get a valid result, you should call @command{gnatmetric} for
17675 the whole set of sources that make up your program. It can be done
17676 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17677 option (see See @ref{The GNAT Driver and Project Files} for details.
17678
17679 By default, all the coupling metrics are disabled. You can use the following
17680 switches to specify the coupling metrics to be computed and reported:
17681
17682 @table @option
17683
17684 @ifclear vms
17685 @cindex @option{--package@var{x}} (@command{gnatmetric})
17686 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17687 @cindex @option{--category@var{x}} (@command{gnatmetric})
17688 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17689 @end ifclear
17690
17691 @ifset vms
17692 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17693 @end ifset
17694
17695 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17696 Report all the coupling metrics
17697
17698 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17699 Do not report any of  metrics
17700
17701 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17702 Report package efferent coupling
17703
17704 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17705 Do not report package efferent coupling
17706
17707 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17708 Report package afferent coupling
17709
17710 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17711 Do not report package afferent coupling
17712
17713 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17714 Report category efferent coupling
17715
17716 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17717 Do not report category efferent coupling
17718
17719 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17720 Report category afferent coupling
17721
17722 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17723 Do not report category afferent coupling
17724
17725 @end table
17726
17727 @node Other gnatmetric Switches
17728 @subsection Other @code{gnatmetric} Switches
17729
17730 @noindent
17731 Additional @command{gnatmetric} switches are as follows:
17732
17733 @table @option
17734 @item ^-files @var{filename}^/FILES=@var{filename}^
17735 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17736 Take the argument source files from the specified file. This file should be an
17737 ordinary text file containing file names separated by spaces or
17738 line breaks. You can use this switch more then once in the same call to
17739 @command{gnatmetric}. You also can combine this switch with
17740 an explicit list of files.
17741
17742 @item ^-v^/VERBOSE^
17743 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17744 Verbose mode;
17745 @command{gnatmetric} generates version information and then
17746 a trace of sources being processed.
17747
17748 @item ^-dv^/DEBUG_OUTPUT^
17749 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17750 Debug mode;
17751 @command{gnatmetric} generates various messages useful to understand what
17752 happens during the metrics computation
17753
17754 @item ^-q^/QUIET^
17755 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17756 Quiet mode.
17757 @end table
17758
17759 @node Generate project-wide metrics
17760 @subsection Generate project-wide metrics
17761
17762 In order to compute metrics on all units of a given project, you can use
17763 the @command{gnat} driver along with the @option{-P} option:
17764 @smallexample
17765    gnat metric -Pproj
17766 @end smallexample
17767
17768 @noindent
17769 If the project @code{proj} depends upon other projects, you can compute
17770 the metrics on the project closure using the @option{-U} option:
17771 @smallexample
17772    gnat metric -Pproj -U
17773 @end smallexample
17774
17775 @noindent
17776 Finally, if not all the units are relevant to a particular main
17777 program in the project closure, you can generate metrics for the set
17778 of units needed to create a given main program (unit closure) using
17779 the @option{-U} option followed by the name of the main unit:
17780 @smallexample
17781    gnat metric -Pproj -U main
17782 @end smallexample
17783
17784
17785 @c ***********************************
17786 @node File Name Krunching Using gnatkr
17787 @chapter File Name Krunching Using @code{gnatkr}
17788 @findex gnatkr
17789
17790 @noindent
17791 This chapter discusses the method used by the compiler to shorten
17792 the default file names chosen for Ada units so that they do not
17793 exceed the maximum length permitted. It also describes the
17794 @code{gnatkr} utility that can be used to determine the result of
17795 applying this shortening.
17796 @menu
17797 * About gnatkr::
17798 * Using gnatkr::
17799 * Krunching Method::
17800 * Examples of gnatkr Usage::
17801 @end menu
17802
17803 @node About gnatkr
17804 @section About @code{gnatkr}
17805
17806 @noindent
17807 The default file naming rule in GNAT
17808 is that the file name must be derived from
17809 the unit name. The exact default rule is as follows:
17810 @itemize @bullet
17811 @item
17812 Take the unit name and replace all dots by hyphens.
17813 @item
17814 If such a replacement occurs in the
17815 second character position of a name, and the first character is
17816 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17817 then replace the dot by the character
17818 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17819 instead of a minus.
17820 @end itemize
17821 The reason for this exception is to avoid clashes
17822 with the standard names for children of System, Ada, Interfaces,
17823 and GNAT, which use the prefixes
17824 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17825 respectively.
17826
17827 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17828 switch of the compiler activates a ``krunching''
17829 circuit that limits file names to nn characters (where nn is a decimal
17830 integer). For example, using OpenVMS,
17831 where the maximum file name length is
17832 39, the value of nn is usually set to 39, but if you want to generate
17833 a set of files that would be usable if ported to a system with some
17834 different maximum file length, then a different value can be specified.
17835 The default value of 39 for OpenVMS need not be specified.
17836
17837 The @code{gnatkr} utility can be used to determine the krunched name for
17838 a given file, when krunched to a specified maximum length.
17839
17840 @node Using gnatkr
17841 @section Using @code{gnatkr}
17842
17843 @noindent
17844 The @code{gnatkr} command has the form
17845
17846 @ifclear vms
17847 @smallexample
17848 $ gnatkr @var{name} @ovar{length}
17849 @end smallexample
17850 @end ifclear
17851
17852 @ifset vms
17853 @smallexample
17854 $ gnatkr @var{name} /COUNT=nn
17855 @end smallexample
17856 @end ifset
17857
17858 @noindent
17859 @var{name} is the uncrunched file name, derived from the name of the unit
17860 in the standard manner described in the previous section (i.e., in particular
17861 all dots are replaced by hyphens). The file name may or may not have an
17862 extension (defined as a suffix of the form period followed by arbitrary
17863 characters other than period). If an extension is present then it will
17864 be preserved in the output. For example, when krunching @file{hellofile.ads}
17865 to eight characters, the result will be hellofil.ads.
17866
17867 Note: for compatibility with previous versions of @code{gnatkr} dots may
17868 appear in the name instead of hyphens, but the last dot will always be
17869 taken as the start of an extension. So if @code{gnatkr} is given an argument
17870 such as @file{Hello.World.adb} it will be treated exactly as if the first
17871 period had been a hyphen, and for example krunching to eight characters
17872 gives the result @file{hellworl.adb}.
17873
17874 Note that the result is always all lower case (except on OpenVMS where it is
17875 all upper case). Characters of the other case are folded as required.
17876
17877 @var{length} represents the length of the krunched name. The default
17878 when no argument is given is ^8^39^ characters. A length of zero stands for
17879 unlimited, in other words do not chop except for system files where the
17880 implied crunching length is always eight characters.
17881
17882 @noindent
17883 The output is the krunched name. The output has an extension only if the
17884 original argument was a file name with an extension.
17885
17886 @node Krunching Method
17887 @section Krunching Method
17888
17889 @noindent
17890 The initial file name is determined by the name of the unit that the file
17891 contains. The name is formed by taking the full expanded name of the
17892 unit and replacing the separating dots with hyphens and
17893 using ^lowercase^uppercase^
17894 for all letters, except that a hyphen in the second character position is
17895 replaced by a ^tilde^dollar sign^ if the first character is
17896 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17897 The extension is @code{.ads} for a
17898 spec and @code{.adb} for a body.
17899 Krunching does not affect the extension, but the file name is shortened to
17900 the specified length by following these rules:
17901
17902 @itemize @bullet
17903 @item
17904 The name is divided into segments separated by hyphens, tildes or
17905 underscores and all hyphens, tildes, and underscores are
17906 eliminated. If this leaves the name short enough, we are done.
17907
17908 @item
17909 If the name is too long, the longest segment is located (left-most
17910 if there are two of equal length), and shortened by dropping
17911 its last character. This is repeated until the name is short enough.
17912
17913 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17914 to fit the name into 8 characters as required by some operating systems.
17915
17916 @smallexample
17917 our-strings-wide_fixed 22
17918 our strings wide fixed 19
17919 our string  wide fixed 18
17920 our strin   wide fixed 17
17921 our stri    wide fixed 16
17922 our stri    wide fixe  15
17923 our str     wide fixe  14
17924 our str     wid  fixe  13
17925 our str     wid  fix   12
17926 ou  str     wid  fix   11
17927 ou  st      wid  fix   10
17928 ou  st      wi   fix   9
17929 ou  st      wi   fi    8
17930 Final file name: oustwifi.adb
17931 @end smallexample
17932
17933 @item
17934 The file names for all predefined units are always krunched to eight
17935 characters. The krunching of these predefined units uses the following
17936 special prefix replacements:
17937
17938 @table @file
17939 @item ada-
17940 replaced by @file{^a^A^-}
17941
17942 @item gnat-
17943 replaced by @file{^g^G^-}
17944
17945 @item interfaces-
17946 replaced by @file{^i^I^-}
17947
17948 @item system-
17949 replaced by @file{^s^S^-}
17950 @end table
17951
17952 These system files have a hyphen in the second character position. That
17953 is why normal user files replace such a character with a
17954 ^tilde^dollar sign^, to
17955 avoid confusion with system file names.
17956
17957 As an example of this special rule, consider
17958 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17959
17960 @smallexample
17961 ada-strings-wide_fixed 22
17962 a-  strings wide fixed 18
17963 a-  string  wide fixed 17
17964 a-  strin   wide fixed 16
17965 a-  stri    wide fixed 15
17966 a-  stri    wide fixe  14
17967 a-  str     wide fixe  13
17968 a-  str     wid  fixe  12
17969 a-  str     wid  fix   11
17970 a-  st      wid  fix   10
17971 a-  st      wi   fix   9
17972 a-  st      wi   fi    8
17973 Final file name: a-stwifi.adb
17974 @end smallexample
17975 @end itemize
17976
17977 Of course no file shortening algorithm can guarantee uniqueness over all
17978 possible unit names, and if file name krunching is used then it is your
17979 responsibility to ensure that no name clashes occur. The utility
17980 program @code{gnatkr} is supplied for conveniently determining the
17981 krunched name of a file.
17982
17983 @node Examples of gnatkr Usage
17984 @section Examples of @code{gnatkr} Usage
17985
17986 @smallexample
17987 @iftex
17988 @leftskip=0cm
17989 @end iftex
17990 @ifclear vms
17991 $ gnatkr very_long_unit_name.ads      --> velounna.ads
17992 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17993 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17994 $ gnatkr grandparent-parent-child     --> grparchi
17995 @end ifclear
17996 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17997 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17998 @end smallexample
17999
18000 @node Preprocessing Using gnatprep
18001 @chapter Preprocessing Using @code{gnatprep}
18002 @findex gnatprep
18003
18004 @noindent
18005 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18006 preprocessing.
18007 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18008 special GNAT features.
18009 For further discussion of conditional compilation in general, see
18010 @ref{Conditional Compilation}.
18011
18012 @menu
18013 * Preprocessing Symbols::
18014 * Using gnatprep::
18015 * Switches for gnatprep::
18016 * Form of Definitions File::
18017 * Form of Input Text for gnatprep::
18018 @end menu
18019
18020 @node Preprocessing Symbols
18021 @section Preprocessing Symbols
18022
18023 @noindent
18024 Preprocessing symbols are defined in definition files and referred to in
18025 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18026 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18027 all characters need to be in the ASCII set (no accented letters).
18028
18029 @node Using gnatprep
18030 @section Using @code{gnatprep}
18031
18032 @noindent
18033 To call @code{gnatprep} use
18034
18035 @smallexample
18036 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18037 @end smallexample
18038
18039 @noindent
18040 where
18041 @table @var
18042 @item switches
18043 is an optional sequence of switches as described in the next section.
18044
18045 @item infile
18046 is the full name of the input file, which is an Ada source
18047 file containing preprocessor directives.
18048
18049 @item outfile
18050 is the full name of the output file, which is an Ada source
18051 in standard Ada form. When used with GNAT, this file name will
18052 normally have an ads or adb suffix.
18053
18054 @item deffile
18055 is the full name of a text file containing definitions of
18056 preprocessing symbols to be referenced by the preprocessor. This argument is
18057 optional, and can be replaced by the use of the @option{-D} switch.
18058
18059 @end table
18060
18061 @node Switches for gnatprep
18062 @section Switches for @code{gnatprep}
18063
18064 @table @option
18065 @c !sort!
18066
18067 @item ^-b^/BLANK_LINES^
18068 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18069 Causes both preprocessor lines and the lines deleted by
18070 preprocessing to be replaced by blank lines in the output source file,
18071 preserving line numbers in the output file.
18072
18073 @item ^-c^/COMMENTS^
18074 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18075 Causes both preprocessor lines and the lines deleted
18076 by preprocessing to be retained in the output source as comments marked
18077 with the special string @code{"--! "}. This option will result in line numbers
18078 being preserved in the output file.
18079
18080 @item ^-C^/REPLACE_IN_COMMENTS^
18081 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18082 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18083 If this option is specified, then comments are scanned and any $symbol
18084 substitutions performed as in program text. This is particularly useful
18085 when structured comments are used (e.g., when writing programs in the
18086 SPARK dialect of Ada). Note that this switch is not available when
18087 doing integrated preprocessing (it would be useless in this context
18088 since comments are ignored by the compiler in any case).
18089
18090 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18091 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18092 Defines a new preprocessing symbol, associated with value. If no value is given
18093 on the command line, then symbol is considered to be @code{True}. This switch
18094 can be used in place of a definition file.
18095
18096 @ifset vms
18097 @item /REMOVE
18098 @cindex @option{/REMOVE} (@command{gnatprep})
18099 This is the default setting which causes lines deleted by preprocessing
18100 to be entirely removed from the output file.
18101 @end ifset
18102
18103 @item ^-r^/REFERENCE^
18104 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18105 Causes a @code{Source_Reference} pragma to be generated that
18106 references the original input file, so that error messages will use
18107 the file name of this original file. The use of this switch implies
18108 that preprocessor lines are not to be removed from the file, so its
18109 use will force @option{^-b^/BLANK_LINES^} mode if
18110 @option{^-c^/COMMENTS^}
18111 has not been specified explicitly.
18112
18113 Note that if the file to be preprocessed contains multiple units, then
18114 it will be necessary to @code{gnatchop} the output file from
18115 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18116 in the preprocessed file, it will be respected by
18117 @code{gnatchop ^-r^/REFERENCE^}
18118 so that the final chopped files will correctly refer to the original
18119 input source file for @code{gnatprep}.
18120
18121 @item ^-s^/SYMBOLS^
18122 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18123 Causes a sorted list of symbol names and values to be
18124 listed on the standard output file.
18125
18126 @item ^-u^/UNDEFINED^
18127 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18128 Causes undefined symbols to be treated as having the value FALSE in the context
18129 of a preprocessor test. In the absence of this option, an undefined symbol in
18130 a @code{#if} or @code{#elsif} test will be treated as an error.
18131
18132 @end table
18133
18134 @ifclear vms
18135 @noindent
18136 Note: if neither @option{-b} nor @option{-c} is present,
18137 then preprocessor lines and
18138 deleted lines are completely removed from the output, unless -r is
18139 specified, in which case -b is assumed.
18140 @end ifclear
18141
18142 @node Form of Definitions File
18143 @section Form of Definitions File
18144
18145 @noindent
18146 The definitions file contains lines of the form
18147
18148 @smallexample
18149 symbol := value
18150 @end smallexample
18151
18152 @noindent
18153 where symbol is a preprocessing symbol, and value is one of the following:
18154
18155 @itemize @bullet
18156 @item
18157 Empty, corresponding to a null substitution
18158 @item
18159 A string literal using normal Ada syntax
18160 @item
18161 Any sequence of characters from the set
18162 (letters, digits, period, underline).
18163 @end itemize
18164
18165 @noindent
18166 Comment lines may also appear in the definitions file, starting with
18167 the usual @code{--},
18168 and comments may be added to the definitions lines.
18169
18170 @node Form of Input Text for gnatprep
18171 @section Form of Input Text for @code{gnatprep}
18172
18173 @noindent
18174 The input text may contain preprocessor conditional inclusion lines,
18175 as well as general symbol substitution sequences.
18176
18177 The preprocessor conditional inclusion commands have the form
18178
18179 @smallexample
18180 @group
18181 @cartouche
18182 #if @i{expression} @r{[}then@r{]}
18183    lines
18184 #elsif @i{expression} @r{[}then@r{]}
18185    lines
18186 #elsif @i{expression} @r{[}then@r{]}
18187    lines
18188 @dots{}
18189 #else
18190    lines
18191 #end if;
18192 @end cartouche
18193 @end group
18194 @end smallexample
18195
18196 @noindent
18197 In this example, @i{expression} is defined by the following grammar:
18198 @smallexample
18199 @i{expression} ::=  <symbol>
18200 @i{expression} ::=  <symbol> = "<value>"
18201 @i{expression} ::=  <symbol> = <symbol>
18202 @i{expression} ::=  <symbol> 'Defined
18203 @i{expression} ::=  not @i{expression}
18204 @i{expression} ::=  @i{expression} and @i{expression}
18205 @i{expression} ::=  @i{expression} or @i{expression}
18206 @i{expression} ::=  @i{expression} and then @i{expression}
18207 @i{expression} ::=  @i{expression} or else @i{expression}
18208 @i{expression} ::=  ( @i{expression} )
18209 @end smallexample
18210
18211 The following restriction exists: it is not allowed to have "and" or "or"
18212 following "not" in the same expression without parentheses. For example, this
18213 is not allowed:
18214
18215 @smallexample
18216    not X or Y
18217 @end smallexample
18218
18219 This should be one of the following:
18220
18221 @smallexample
18222    (not X) or Y
18223    not (X or Y)
18224 @end smallexample
18225
18226 @noindent
18227 For the first test (@i{expression} ::= <symbol>) the symbol must have
18228 either the value true or false, that is to say the right-hand of the
18229 symbol definition must be one of the (case-insensitive) literals
18230 @code{True} or @code{False}. If the value is true, then the
18231 corresponding lines are included, and if the value is false, they are
18232 excluded.
18233
18234 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18235 the symbol has been defined in the definition file or by a @option{-D}
18236 switch on the command line. Otherwise, the test is false.
18237
18238 The equality tests are case insensitive, as are all the preprocessor lines.
18239
18240 If the symbol referenced is not defined in the symbol definitions file,
18241 then the effect depends on whether or not switch @option{-u}
18242 is specified. If so, then the symbol is treated as if it had the value
18243 false and the test fails. If this switch is not specified, then
18244 it is an error to reference an undefined symbol. It is also an error to
18245 reference a symbol that is defined with a value other than @code{True}
18246 or @code{False}.
18247
18248 The use of the @code{not} operator inverts the sense of this logical test.
18249 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18250 operators, without parentheses. For example, "if not X or Y then" is not
18251 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18252
18253 The @code{then} keyword is optional as shown
18254
18255 The @code{#} must be the first non-blank character on a line, but
18256 otherwise the format is free form. Spaces or tabs may appear between
18257 the @code{#} and the keyword. The keywords and the symbols are case
18258 insensitive as in normal Ada code. Comments may be used on a
18259 preprocessor line, but other than that, no other tokens may appear on a
18260 preprocessor line. Any number of @code{elsif} clauses can be present,
18261 including none at all. The @code{else} is optional, as in Ada.
18262
18263 The @code{#} marking the start of a preprocessor line must be the first
18264 non-blank character on the line, i.e., it must be preceded only by
18265 spaces or horizontal tabs.
18266
18267 Symbol substitution outside of preprocessor lines is obtained by using
18268 the sequence
18269
18270 @smallexample
18271 $symbol
18272 @end smallexample
18273
18274 @noindent
18275 anywhere within a source line, except in a comment or within a
18276 string literal. The identifier
18277 following the @code{$} must match one of the symbols defined in the symbol
18278 definition file, and the result is to substitute the value of the
18279 symbol in place of @code{$symbol} in the output file.
18280
18281 Note that although the substitution of strings within a string literal
18282 is not possible, it is possible to have a symbol whose defined value is
18283 a string literal. So instead of setting XYZ to @code{hello} and writing:
18284
18285 @smallexample
18286 Header : String := "$XYZ";
18287 @end smallexample
18288
18289 @noindent
18290 you should set XYZ to @code{"hello"} and write:
18291
18292 @smallexample
18293 Header : String := $XYZ;
18294 @end smallexample
18295
18296 @noindent
18297 and then the substitution will occur as desired.
18298
18299 @ifset vms
18300 @node The GNAT Run-Time Library Builder gnatlbr
18301 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18302 @findex gnatlbr
18303 @cindex Library builder
18304
18305 @noindent
18306 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18307 supplied configuration pragmas.
18308
18309 @menu
18310 * Running gnatlbr::
18311 * Switches for gnatlbr::
18312 * Examples of gnatlbr Usage::
18313 @end menu
18314
18315 @node Running gnatlbr
18316 @section Running @code{gnatlbr}
18317
18318 @noindent
18319 The @code{gnatlbr} command has the form
18320
18321 @smallexample
18322 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18323 @end smallexample
18324
18325 @node Switches for gnatlbr
18326 @section Switches for @code{gnatlbr}
18327
18328 @noindent
18329 @code{gnatlbr} recognizes the following switches:
18330
18331 @table @option
18332 @c !sort!
18333 @item /CREATE=directory
18334 @cindex @code{/CREATE} (@code{gnatlbr})
18335 Create the new run-time library in the specified directory.
18336
18337 @item /SET=directory
18338 @cindex @code{/SET} (@code{gnatlbr})
18339 Make the library in the specified directory the current run-time library.
18340
18341 @item /DELETE=directory
18342 @cindex @code{/DELETE} (@code{gnatlbr})
18343 Delete the run-time library in the specified directory.
18344
18345 @item /CONFIG=file
18346 @cindex @code{/CONFIG} (@code{gnatlbr})
18347 With /CREATE: Use the configuration pragmas in the specified file when
18348 building the library.
18349
18350 With /SET: Use the configuration pragmas in the specified file when
18351 compiling.
18352
18353 @end table
18354
18355 @node Examples of gnatlbr Usage
18356 @section Example of @code{gnatlbr} Usage
18357
18358 @smallexample
18359 Contents of VAXFLOAT.ADC:
18360 pragma Float_Representation (VAX_Float);
18361
18362 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18363
18364 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18365
18366 @end smallexample
18367 @end ifset
18368
18369 @node The GNAT Library Browser gnatls
18370 @chapter The GNAT Library Browser @code{gnatls}
18371 @findex gnatls
18372 @cindex Library browser
18373
18374 @noindent
18375 @code{gnatls} is a tool that outputs information about compiled
18376 units. It gives the relationship between objects, unit names and source
18377 files. It can also be used to check the source dependencies of a unit
18378 as well as various characteristics.
18379
18380 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18381 driver (see @ref{The GNAT Driver and Project Files}).
18382
18383 @menu
18384 * Running gnatls::
18385 * Switches for gnatls::
18386 * Examples of gnatls Usage::
18387 @end menu
18388
18389 @node Running gnatls
18390 @section Running @code{gnatls}
18391
18392 @noindent
18393 The @code{gnatls} command has the form
18394
18395 @smallexample
18396 $ gnatls switches @var{object_or_ali_file}
18397 @end smallexample
18398
18399 @noindent
18400 The main argument is the list of object or @file{ali} files
18401 (@pxref{The Ada Library Information Files})
18402 for which information is requested.
18403
18404 In normal mode, without additional option, @code{gnatls} produces a
18405 four-column listing. Each line represents information for a specific
18406 object. The first column gives the full path of the object, the second
18407 column gives the name of the principal unit in this object, the third
18408 column gives the status of the source and the fourth column gives the
18409 full path of the source representing this unit.
18410 Here is a simple example of use:
18411
18412 @smallexample
18413 $ gnatls *.o
18414 ^./^[]^demo1.o            demo1            DIF demo1.adb
18415 ^./^[]^demo2.o            demo2             OK demo2.adb
18416 ^./^[]^hello.o            h1                OK hello.adb
18417 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18418 ^./^[]^instr.o            instr             OK instr.adb
18419 ^./^[]^tef.o              tef              DIF tef.adb
18420 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18421 ^./^[]^tgef.o             tgef             DIF tgef.adb
18422 @end smallexample
18423
18424 @noindent
18425 The first line can be interpreted as follows: the main unit which is
18426 contained in
18427 object file @file{demo1.o} is demo1, whose main source is in
18428 @file{demo1.adb}. Furthermore, the version of the source used for the
18429 compilation of demo1 has been modified (DIF). Each source file has a status
18430 qualifier which can be:
18431
18432 @table @code
18433 @item OK (unchanged)
18434 The version of the source file used for the compilation of the
18435 specified unit corresponds exactly to the actual source file.
18436
18437 @item MOK (slightly modified)
18438 The version of the source file used for the compilation of the
18439 specified unit differs from the actual source file but not enough to
18440 require recompilation. If you use gnatmake with the qualifier
18441 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18442 MOK will not be recompiled.
18443
18444 @item DIF (modified)
18445 No version of the source found on the path corresponds to the source
18446 used to build this object.
18447
18448 @item ??? (file not found)
18449 No source file was found for this unit.
18450
18451 @item HID (hidden,  unchanged version not first on PATH)
18452 The version of the source that corresponds exactly to the source used
18453 for compilation has been found on the path but it is hidden by another
18454 version of the same source that has been modified.
18455
18456 @end table
18457
18458 @node Switches for gnatls
18459 @section Switches for @code{gnatls}
18460
18461 @noindent
18462 @code{gnatls} recognizes the following switches:
18463
18464 @table @option
18465 @c !sort!
18466 @cindex @option{--version} @command{gnatls}
18467 Display Copyright and version, then exit disregarding all other options.
18468
18469 @item --help
18470 @cindex @option{--help} @command{gnatls}
18471 If @option{--version} was not used, display usage, then exit disregarding
18472 all other options.
18473
18474 @item ^-a^/ALL_UNITS^
18475 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18476 Consider all units, including those of the predefined Ada library.
18477 Especially useful with @option{^-d^/DEPENDENCIES^}.
18478
18479 @item ^-d^/DEPENDENCIES^
18480 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18481 List sources from which specified units depend on.
18482
18483 @item ^-h^/OUTPUT=OPTIONS^
18484 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18485 Output the list of options.
18486
18487 @item ^-o^/OUTPUT=OBJECTS^
18488 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18489 Only output information about object files.
18490
18491 @item ^-s^/OUTPUT=SOURCES^
18492 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18493 Only output information about source files.
18494
18495 @item ^-u^/OUTPUT=UNITS^
18496 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18497 Only output information about compilation units.
18498
18499 @item ^-files^/FILES^=@var{file}
18500 @cindex @option{^-files^/FILES^} (@code{gnatls})
18501 Take as arguments the files listed in text file @var{file}.
18502 Text file @var{file} may contain empty lines that are ignored.
18503 Each nonempty line should contain the name of an existing file.
18504 Several such switches may be specified simultaneously.
18505
18506 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18507 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18508 @itemx ^-I^/SEARCH=^@var{dir}
18509 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18510 @itemx -nostdinc
18511 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18512 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18513 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18514 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18515 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18516 flags (@pxref{Switches for gnatmake}).
18517
18518 @item --RTS=@var{rts-path}
18519 @cindex @option{--RTS} (@code{gnatls})
18520 Specifies the default location of the runtime library. Same meaning as the
18521 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18522
18523 @item ^-v^/OUTPUT=VERBOSE^
18524 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18525 Verbose mode. Output the complete source, object and project paths. Do not use
18526 the default column layout but instead use long format giving as much as
18527 information possible on each requested units, including special
18528 characteristics such as:
18529
18530 @table @code
18531 @item  Preelaborable
18532 The unit is preelaborable in the Ada sense.
18533
18534 @item No_Elab_Code
18535 No elaboration code has been produced by the compiler for this unit.
18536
18537 @item Pure
18538 The unit is pure in the Ada sense.
18539
18540 @item Elaborate_Body
18541 The unit contains a pragma Elaborate_Body.
18542
18543 @item Remote_Types
18544 The unit contains a pragma Remote_Types.
18545
18546 @item Shared_Passive
18547 The unit contains a pragma Shared_Passive.
18548
18549 @item Predefined
18550 This unit is part of the predefined environment and cannot be modified
18551 by the user.
18552
18553 @item Remote_Call_Interface
18554 The unit contains a pragma Remote_Call_Interface.
18555
18556 @end table
18557
18558 @end table
18559
18560 @node Examples of gnatls Usage
18561 @section Example of @code{gnatls} Usage
18562 @ifclear vms
18563
18564 @noindent
18565 Example of using the verbose switch. Note how the source and
18566 object paths are affected by the -I switch.
18567
18568 @smallexample
18569 $ gnatls -v -I.. demo1.o
18570
18571 GNATLS 5.03w (20041123-34)
18572 Copyright 1997-2004 Free Software Foundation, Inc.
18573
18574 Source Search Path:
18575    <Current_Directory>
18576    ../
18577    /home/comar/local/adainclude/
18578
18579 Object Search Path:
18580    <Current_Directory>
18581    ../
18582    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18583
18584 Project Search Path:
18585    <Current_Directory>
18586    /home/comar/local/lib/gnat/
18587
18588 ./demo1.o
18589    Unit =>
18590      Name   => demo1
18591      Kind   => subprogram body
18592      Flags  => No_Elab_Code
18593      Source => demo1.adb    modified
18594 @end smallexample
18595
18596 @noindent
18597 The following is an example of use of the dependency list.
18598 Note the use of the -s switch
18599 which gives a straight list of source files. This can be useful for
18600 building specialized scripts.
18601
18602 @smallexample
18603 $ gnatls -d demo2.o
18604 ./demo2.o   demo2        OK demo2.adb
18605                          OK gen_list.ads
18606                          OK gen_list.adb
18607                          OK instr.ads
18608                          OK instr-child.ads
18609
18610 $ gnatls -d -s -a demo1.o
18611 demo1.adb
18612 /home/comar/local/adainclude/ada.ads
18613 /home/comar/local/adainclude/a-finali.ads
18614 /home/comar/local/adainclude/a-filico.ads
18615 /home/comar/local/adainclude/a-stream.ads
18616 /home/comar/local/adainclude/a-tags.ads
18617 gen_list.ads
18618 gen_list.adb
18619 /home/comar/local/adainclude/gnat.ads
18620 /home/comar/local/adainclude/g-io.ads
18621 instr.ads
18622 /home/comar/local/adainclude/system.ads
18623 /home/comar/local/adainclude/s-exctab.ads
18624 /home/comar/local/adainclude/s-finimp.ads
18625 /home/comar/local/adainclude/s-finroo.ads
18626 /home/comar/local/adainclude/s-secsta.ads
18627 /home/comar/local/adainclude/s-stalib.ads
18628 /home/comar/local/adainclude/s-stoele.ads
18629 /home/comar/local/adainclude/s-stratt.ads
18630 /home/comar/local/adainclude/s-tasoli.ads
18631 /home/comar/local/adainclude/s-unstyp.ads
18632 /home/comar/local/adainclude/unchconv.ads
18633 @end smallexample
18634 @end ifclear
18635
18636 @ifset vms
18637 @smallexample
18638 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18639
18640 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18641 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18642 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18643 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18644 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18645 demo1.adb
18646 gen_list.ads
18647 gen_list.adb
18648 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18649 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18650 instr.ads
18651 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18652 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18653 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18654 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18655 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18656 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18657 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18658 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18659 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18660 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18661 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18662 @end smallexample
18663 @end ifset
18664
18665 @node Cleaning Up Using gnatclean
18666 @chapter Cleaning Up Using @code{gnatclean}
18667 @findex gnatclean
18668 @cindex Cleaning tool
18669
18670 @noindent
18671 @code{gnatclean} is a tool that allows the deletion of files produced by the
18672 compiler, binder and linker, including ALI files, object files, tree files,
18673 expanded source files, library files, interface copy source files, binder
18674 generated files and executable files.
18675
18676 @menu
18677 * Running gnatclean::
18678 * Switches for gnatclean::
18679 @c * Examples of gnatclean Usage::
18680 @end menu
18681
18682 @node Running gnatclean
18683 @section Running @code{gnatclean}
18684
18685 @noindent
18686 The @code{gnatclean} command has the form:
18687
18688 @smallexample
18689 $ gnatclean switches @var{names}
18690 @end smallexample
18691
18692 @noindent
18693 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18694 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18695 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18696
18697 @noindent
18698 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18699 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18700 the linker. In informative-only mode, specified by switch
18701 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18702 normal mode is listed, but no file is actually deleted.
18703
18704 @node Switches for gnatclean
18705 @section Switches for @code{gnatclean}
18706
18707 @noindent
18708 @code{gnatclean} recognizes the following switches:
18709
18710 @table @option
18711 @c !sort!
18712 @cindex @option{--version} @command{gnatclean}
18713 Display Copyright and version, then exit disregarding all other options.
18714
18715 @item --help
18716 @cindex @option{--help} @command{gnatclean}
18717 If @option{--version} was not used, display usage, then exit disregarding
18718 all other options.
18719
18720 @item ^-c^/COMPILER_FILES_ONLY^
18721 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18722 Only attempt to delete the files produced by the compiler, not those produced
18723 by the binder or the linker. The files that are not to be deleted are library
18724 files, interface copy files, binder generated files and executable files.
18725
18726 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18727 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18728 Indicate that ALI and object files should normally be found in directory
18729 @var{dir}.
18730
18731 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18732 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18733 When using project files, if some errors or warnings are detected during
18734 parsing and verbose mode is not in effect (no use of switch
18735 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18736 file, rather than its simple file name.
18737
18738 @item ^-h^/HELP^
18739 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18740 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18741
18742 @item ^-n^/NODELETE^
18743 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18744 Informative-only mode. Do not delete any files. Output the list of the files
18745 that would have been deleted if this switch was not specified.
18746
18747 @item ^-P^/PROJECT_FILE=^@var{project}
18748 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18749 Use project file @var{project}. Only one such switch can be used.
18750 When cleaning a project file, the files produced by the compilation of the
18751 immediate sources or inherited sources of the project files are to be
18752 deleted. This is not depending on the presence or not of executable names
18753 on the command line.
18754
18755 @item ^-q^/QUIET^
18756 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18757 Quiet output. If there are no errors, do not output anything, except in
18758 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18759 (switch ^-n^/NODELETE^).
18760
18761 @item ^-r^/RECURSIVE^
18762 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18763 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18764 clean all imported and extended project files, recursively. If this switch
18765 is not specified, only the files related to the main project file are to be
18766 deleted. This switch has no effect if no project file is specified.
18767
18768 @item ^-v^/VERBOSE^
18769 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18770 Verbose mode.
18771
18772 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18773 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18774 Indicates the verbosity of the parsing of GNAT project files.
18775 @xref{Switches Related to Project Files}.
18776
18777 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18778 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18779 Indicates that external variable @var{name} has the value @var{value}.
18780 The Project Manager will use this value for occurrences of
18781 @code{external(name)} when parsing the project file.
18782 @xref{Switches Related to Project Files}.
18783
18784 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18785 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18786 When searching for ALI and object files, look in directory
18787 @var{dir}.
18788
18789 @item ^-I^/SEARCH=^@var{dir}
18790 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18791 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18792
18793 @item ^-I-^/NOCURRENT_DIRECTORY^
18794 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18795 @cindex Source files, suppressing search
18796 Do not look for ALI or object files in the directory
18797 where @code{gnatclean} was invoked.
18798
18799 @end table
18800
18801 @c @node Examples of gnatclean Usage
18802 @c @section Examples of @code{gnatclean} Usage
18803
18804 @ifclear vms
18805 @node GNAT and Libraries
18806 @chapter GNAT and Libraries
18807 @cindex Library, building, installing, using
18808
18809 @noindent
18810 This chapter describes how to build and use libraries with GNAT, and also shows
18811 how to recompile the GNAT run-time library. You should be familiar with the
18812 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18813 chapter.
18814
18815 @menu
18816 * Introduction to Libraries in GNAT::
18817 * General Ada Libraries::
18818 * Stand-alone Ada Libraries::
18819 * Rebuilding the GNAT Run-Time Library::
18820 @end menu
18821
18822 @node Introduction to Libraries in GNAT
18823 @section Introduction to Libraries in GNAT
18824
18825 @noindent
18826 A library is, conceptually, a collection of objects which does not have its
18827 own main thread of execution, but rather provides certain services to the
18828 applications that use it. A library can be either statically linked with the
18829 application, in which case its code is directly included in the application,
18830 or, on platforms that support it, be dynamically linked, in which case
18831 its code is shared by all applications making use of this library.
18832
18833 GNAT supports both types of libraries.
18834 In the static case, the compiled code can be provided in different ways. The
18835 simplest approach is to provide directly the set of objects resulting from
18836 compilation of the library source files. Alternatively, you can group the
18837 objects into an archive using whatever commands are provided by the operating
18838 system. For the latter case, the objects are grouped into a shared library.
18839
18840 In the GNAT environment, a library has three types of components:
18841 @itemize @bullet
18842 @item
18843 Source files.
18844 @item
18845 @file{ALI} files.
18846 @xref{The Ada Library Information Files}.
18847 @item
18848 Object files, an archive or a shared library.
18849 @end itemize
18850
18851 @noindent
18852 A GNAT library may expose all its source files, which is useful for
18853 documentation purposes. Alternatively, it may expose only the units needed by
18854 an external user to make use of the library. That is to say, the specs
18855 reflecting the library services along with all the units needed to compile
18856 those specs, which can include generic bodies or any body implementing an
18857 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18858 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18859
18860 All compilation units comprising an application, including those in a library,
18861 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18862 computes the elaboration order from the @file{ALI} files and this is why they
18863 constitute a mandatory part of GNAT libraries. Except in the case of
18864 @emph{stand-alone libraries}, where a specific library elaboration routine is
18865 produced independently of the application(s) using the library.
18866
18867 @node General Ada Libraries
18868 @section General Ada Libraries
18869
18870 @menu
18871 * Building a library::
18872 * Installing a library::
18873 * Using a library::
18874 @end menu
18875
18876 @node Building a library
18877 @subsection Building a library
18878
18879 @noindent
18880 The easiest way to build a library is to use the Project Manager,
18881 which supports a special type of project called a @emph{Library Project}
18882 (@pxref{Library Projects}).
18883
18884 A project is considered a library project, when two project-level attributes
18885 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18886 control different aspects of library configuration, additional optional
18887 project-level attributes can be specified:
18888 @table @code
18889 @item Library_Kind
18890 This attribute controls whether the library is to be static or dynamic
18891
18892 @item Library_Version
18893 This attribute specifies the library version; this value is used
18894 during dynamic linking of shared libraries to determine if the currently
18895 installed versions of the binaries are compatible.
18896
18897 @item Library_Options
18898 @item Library_GCC
18899 These attributes specify additional low-level options to be used during
18900 library generation, and redefine the actual application used to generate
18901 library.
18902 @end table
18903
18904 @noindent
18905 The GNAT Project Manager takes full care of the library maintenance task,
18906 including recompilation of the source files for which objects do not exist
18907 or are not up to date, assembly of the library archive, and installation of
18908 the library (i.e., copying associated source, object and @file{ALI} files
18909 to the specified location).
18910
18911 Here is a simple library project file:
18912 @smallexample @c ada
18913 project My_Lib is
18914    for Source_Dirs use ("src1", "src2");
18915    for Object_Dir use "obj";
18916    for Library_Name use "mylib";
18917    for Library_Dir use "lib";
18918    for Library_Kind use "dynamic";
18919 end My_lib;
18920 @end smallexample
18921
18922 @noindent
18923 and the compilation command to build and install the library:
18924
18925 @smallexample @c ada
18926   $ gnatmake -Pmy_lib
18927 @end smallexample
18928
18929 @noindent
18930 It is not entirely trivial to perform manually all the steps required to
18931 produce a library. We recommend that you use the GNAT Project Manager
18932 for this task. In special cases where this is not desired, the necessary
18933 steps are discussed below.
18934
18935 There are various possibilities for compiling the units that make up the
18936 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18937 with a conventional script. For simple libraries, it is also possible to create
18938 a dummy main program which depends upon all the packages that comprise the
18939 interface of the library. This dummy main program can then be given to
18940 @command{gnatmake}, which will ensure that all necessary objects are built.
18941
18942 After this task is accomplished, you should follow the standard procedure
18943 of the underlying operating system to produce the static or shared library.
18944
18945 Here is an example of such a dummy program:
18946 @smallexample @c ada
18947 @group
18948 with My_Lib.Service1;
18949 with My_Lib.Service2;
18950 with My_Lib.Service3;
18951 procedure My_Lib_Dummy is
18952 begin
18953    null;
18954 end;
18955 @end group
18956 @end smallexample
18957
18958 @noindent
18959 Here are the generic commands that will build an archive or a shared library.
18960
18961 @smallexample
18962 # compiling the library
18963 $ gnatmake -c my_lib_dummy.adb
18964
18965 # we don't need the dummy object itself
18966 $ rm my_lib_dummy.o my_lib_dummy.ali
18967
18968 # create an archive with the remaining objects
18969 $ ar rc libmy_lib.a *.o
18970 # some systems may require "ranlib" to be run as well
18971
18972 # or create a shared library
18973 $ gcc -shared -o libmy_lib.so *.o
18974 # some systems may require the code to have been compiled with -fPIC
18975
18976 # remove the object files that are now in the library
18977 $ rm *.o
18978
18979 # Make the ALI files read-only so that gnatmake will not try to
18980 # regenerate the objects that are in the library
18981 $ chmod -w *.ali
18982 @end smallexample
18983
18984 @noindent
18985 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
18986 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
18987 be accessed by the directive @option{-l@var{xxx}} at link time.
18988
18989 @node Installing a library
18990 @subsection Installing a library
18991 @cindex @code{ADA_PROJECT_PATH}
18992
18993 @noindent
18994 If you use project files, library installation is part of the library build
18995 process. Thus no further action is needed in order to make use of the
18996 libraries that are built as part of the general application build. A usable
18997 version of the library is installed in the directory specified by the
18998 @code{Library_Dir} attribute of the library project file.
18999
19000 You may want to install a library in a context different from where the library
19001 is built. This situation arises with third party suppliers, who may want
19002 to distribute a library in binary form where the user is not expected to be
19003 able to recompile the library. The simplest option in this case is to provide
19004 a project file slightly different from the one used to build the library, by
19005 using the @code{externally_built} attribute. For instance, the project
19006 file used to build the library in the previous section can be changed into the
19007 following one when the library is installed:
19008
19009 @smallexample @c projectfile
19010 project My_Lib is
19011    for Source_Dirs use ("src1", "src2");
19012    for Library_Name use "mylib";
19013    for Library_Dir use "lib";
19014    for Library_Kind use "dynamic";
19015    for Externally_Built use "true";
19016 end My_lib;
19017 @end smallexample
19018
19019 @noindent
19020 This project file assumes that the directories @file{src1},
19021 @file{src2}, and @file{lib} exist in
19022 the directory containing the project file. The @code{externally_built}
19023 attribute makes it clear to the GNAT builder that it should not attempt to
19024 recompile any of the units from this library. It allows the library provider to
19025 restrict the source set to the minimum necessary for clients to make use of the
19026 library as described in the first section of this chapter. It is the
19027 responsibility of the library provider to install the necessary sources, ALI
19028 files and libraries in the directories mentioned in the project file. For
19029 convenience, the user's library project file should be installed in a location
19030 that will be searched automatically by the GNAT
19031 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
19032 environment variable (@pxref{Importing Projects}), and also the default GNAT
19033 library location that can be queried with @command{gnatls -v} and is usually of
19034 the form $gnat_install_root/lib/gnat.
19035
19036 When project files are not an option, it is also possible, but not recommended,
19037 to install the library so that the sources needed to use the library are on the
19038 Ada source path and the ALI files & libraries be on the Ada Object path (see
19039 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19040 administrator can place general-purpose libraries in the default compiler
19041 paths, by specifying the libraries' location in the configuration files
19042 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19043 must be located in the GNAT installation tree at the same place as the gcc spec
19044 file. The location of the gcc spec file can be determined as follows:
19045 @smallexample
19046 $ gcc -v
19047 @end smallexample
19048
19049 @noindent
19050 The configuration files mentioned above have a simple format: each line
19051 must contain one unique directory name.
19052 Those names are added to the corresponding path
19053 in their order of appearance in the file. The names can be either absolute
19054 or relative; in the latter case, they are relative to where theses files
19055 are located.
19056
19057 The files @file{ada_source_path} and @file{ada_object_path} might not be
19058 present in a
19059 GNAT installation, in which case, GNAT will look for its run-time library in
19060 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19061 objects and @file{ALI} files). When the files exist, the compiler does not
19062 look in @file{adainclude} and @file{adalib}, and thus the
19063 @file{ada_source_path} file
19064 must contain the location for the GNAT run-time sources (which can simply
19065 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19066 contain the location for the GNAT run-time objects (which can simply
19067 be @file{adalib}).
19068
19069 You can also specify a new default path to the run-time library at compilation
19070 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19071 the run-time library you want your program to be compiled with. This switch is
19072 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19073 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19074
19075 It is possible to install a library before or after the standard GNAT
19076 library, by reordering the lines in the configuration files. In general, a
19077 library must be installed before the GNAT library if it redefines
19078 any part of it.
19079
19080 @node Using a library
19081 @subsection Using a library
19082
19083 @noindent Once again, the project facility greatly simplifies the use of
19084 libraries. In this context, using a library is just a matter of adding a
19085 @code{with} clause in the user project. For instance, to make use of the
19086 library @code{My_Lib} shown in examples in earlier sections, you can
19087 write:
19088
19089 @smallexample @c projectfile
19090 with "my_lib";
19091 project My_Proj is
19092   @dots{}
19093 end My_Proj;
19094 @end smallexample
19095
19096 Even if you have a third-party, non-Ada library, you can still use GNAT's
19097 Project Manager facility to provide a wrapper for it. For example, the
19098 following project, when @code{with}ed by your main project, will link with the
19099 third-party library @file{liba.a}:
19100
19101 @smallexample @c projectfile
19102 @group
19103 project Liba is
19104    for Externally_Built use "true";
19105    for Source_Files use ();
19106    for Library_Dir use "lib";
19107    for Library_Name use "a";
19108    for Library_Kind use "static";
19109 end Liba;
19110 @end group
19111 @end smallexample
19112 This is an alternative to the use of @code{pragma Linker_Options}. It is
19113 especially interesting in the context of systems with several interdependent
19114 static libraries where finding a proper linker order is not easy and best be
19115 left to the tools having visibility over project dependence information.
19116
19117 @noindent
19118 In order to use an Ada library manually, you need to make sure that this
19119 library is on both your source and object path
19120 (see @ref{Search Paths and the Run-Time Library (RTL)}
19121 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19122 in an archive or a shared library, you need to specify the desired
19123 library at link time.
19124
19125 For example, you can use the library @file{mylib} installed in
19126 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19127
19128 @smallexample
19129 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19130   -largs -lmy_lib
19131 @end smallexample
19132
19133 @noindent
19134 This can be expressed more simply:
19135 @smallexample
19136 $ gnatmake my_appl
19137 @end smallexample
19138 @noindent
19139 when the following conditions are met:
19140 @itemize @bullet
19141 @item
19142 @file{/dir/my_lib_src} has been added by the user to the environment
19143 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19144 @file{ada_source_path}
19145 @item
19146 @file{/dir/my_lib_obj} has been added by the user to the environment
19147 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19148 @file{ada_object_path}
19149 @item
19150 a pragma @code{Linker_Options} has been added to one of the sources.
19151 For example:
19152
19153 @smallexample @c ada
19154 pragma Linker_Options ("-lmy_lib");
19155 @end smallexample
19156 @end itemize
19157
19158 @node Stand-alone Ada Libraries
19159 @section Stand-alone Ada Libraries
19160 @cindex Stand-alone library, building, using
19161
19162 @menu
19163 * Introduction to Stand-alone Libraries::
19164 * Building a Stand-alone Library::
19165 * Creating a Stand-alone Library to be used in a non-Ada context::
19166 * Restrictions in Stand-alone Libraries::
19167 @end menu
19168
19169 @node Introduction to Stand-alone Libraries
19170 @subsection Introduction to Stand-alone Libraries
19171
19172 @noindent
19173 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19174 necessary code to
19175 elaborate the Ada units that are included in the library. In contrast with
19176 an ordinary library, which consists of all sources, objects and @file{ALI}
19177 files of the
19178 library, a SAL may specify a restricted subset of compilation units
19179 to serve as a library interface. In this case, the fully
19180 self-sufficient set of files will normally consist of an objects
19181 archive, the sources of interface units' specs, and the @file{ALI}
19182 files of interface units.
19183 If an interface spec contains a generic unit or an inlined subprogram,
19184 the body's
19185 source must also be provided; if the units that must be provided in the source
19186 form depend on other units, the source and @file{ALI} files of those must
19187 also be provided.
19188
19189 The main purpose of a SAL is to minimize the recompilation overhead of client
19190 applications when a new version of the library is installed. Specifically,
19191 if the interface sources have not changed, client applications do not need to
19192 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19193 version, controlled by @code{Library_Version} attribute, is not changed,
19194 then the clients do not need to be relinked.
19195
19196 SALs also allow the library providers to minimize the amount of library source
19197 text exposed to the clients.  Such ``information hiding'' might be useful or
19198 necessary for various reasons.
19199
19200 Stand-alone libraries are also well suited to be used in an executable whose
19201 main routine is not written in Ada.
19202
19203 @node Building a Stand-alone Library
19204 @subsection Building a Stand-alone Library
19205
19206 @noindent
19207 GNAT's Project facility provides a simple way of building and installing
19208 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19209 To be a Stand-alone Library Project, in addition to the two attributes
19210 that make a project a Library Project (@code{Library_Name} and
19211 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19212 @code{Library_Interface} must be defined.  For example:
19213
19214 @smallexample @c projectfile
19215 @group
19216    for Library_Dir use "lib_dir";
19217    for Library_Name use "dummy";
19218    for Library_Interface use ("int1", "int1.child");
19219 @end group
19220 @end smallexample
19221
19222 @noindent
19223 Attribute @code{Library_Interface} has a non-empty string list value,
19224 each string in the list designating a unit contained in an immediate source
19225 of the project file.
19226
19227 When a Stand-alone Library is built, first the binder is invoked to build
19228 a package whose name depends on the library name
19229 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19230 This binder-generated package includes initialization and
19231 finalization procedures whose
19232 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19233 in the example
19234 above). The object corresponding to this package is included in the library.
19235
19236 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19237 calling of these procedures if a static SAL is built, or if a shared SAL
19238 is built
19239 with the project-level attribute @code{Library_Auto_Init} set to
19240 @code{"false"}.
19241
19242 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19243 (those that are listed in attribute @code{Library_Interface}) are copied to
19244 the Library Directory. As a consequence, only the Interface Units may be
19245 imported from Ada units outside of the library. If other units are imported,
19246 the binding phase will fail.
19247
19248 The attribute @code{Library_Src_Dir} may be specified for a
19249 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19250 single string value. Its value must be the path (absolute or relative to the
19251 project directory) of an existing directory. This directory cannot be the
19252 object directory or one of the source directories, but it can be the same as
19253 the library directory. The sources of the Interface
19254 Units of the library that are needed by an Ada client of the library will be
19255 copied to the designated directory, called the Interface Copy directory.
19256 These sources include the specs of the Interface Units, but they may also
19257 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19258 are used, or when there is a generic unit in the spec. Before the sources
19259 are copied to the Interface Copy directory, an attempt is made to delete all
19260 files in the Interface Copy directory.
19261
19262 Building stand-alone libraries by hand is somewhat tedious, but for those
19263 occasions when it is necessary here are the steps that you need to perform:
19264 @itemize @bullet
19265 @item
19266 Compile all library sources.
19267
19268 @item
19269 Invoke the binder with the switch @option{-n} (No Ada main program),
19270 with all the @file{ALI} files of the interfaces, and
19271 with the switch @option{-L} to give specific names to the @code{init}
19272 and @code{final} procedures.  For example:
19273 @smallexample
19274   gnatbind -n int1.ali int2.ali -Lsal1
19275 @end smallexample
19276
19277 @item
19278 Compile the binder generated file:
19279 @smallexample
19280   gcc -c b~int2.adb
19281 @end smallexample
19282
19283 @item
19284 Link the dynamic library with all the necessary object files,
19285 indicating to the linker the names of the @code{init} (and possibly
19286 @code{final}) procedures for automatic initialization (and finalization).
19287 The built library should be placed in a directory different from
19288 the object directory.
19289
19290 @item
19291 Copy the @code{ALI} files of the interface to the library directory,
19292 add in this copy an indication that it is an interface to a SAL
19293 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19294 with letter ``P'') and make the modified copy of the @file{ALI} file
19295 read-only.
19296 @end itemize
19297
19298 @noindent
19299 Using SALs is not different from using other libraries
19300 (see @ref{Using a library}).
19301
19302 @node Creating a Stand-alone Library to be used in a non-Ada context
19303 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19304
19305 @noindent
19306 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19307 a non-Ada context.
19308
19309 The only extra step required is to ensure that library interface subprograms
19310 are compatible with the main program, by means of @code{pragma Export}
19311 or @code{pragma Convention}.
19312
19313 Here is an example of simple library interface for use with C main program:
19314
19315 @smallexample @c ada
19316 package Interface is
19317
19318    procedure Do_Something;
19319    pragma Export (C, Do_Something, "do_something");
19320
19321    procedure Do_Something_Else;
19322    pragma Export (C, Do_Something_Else, "do_something_else");
19323
19324 end Interface;
19325 @end smallexample
19326
19327 @noindent
19328 On the foreign language side, you must provide a ``foreign'' view of the
19329 library interface; remember that it should contain elaboration routines in
19330 addition to interface subprograms.
19331
19332 The example below shows the content of @code{mylib_interface.h} (note
19333 that there is no rule for the naming of this file, any name can be used)
19334 @smallexample
19335 /* the library elaboration procedure */
19336 extern void mylibinit (void);
19337
19338 /* the library finalization procedure */
19339 extern void mylibfinal (void);
19340
19341 /* the interface exported by the library */
19342 extern void do_something (void);
19343 extern void do_something_else (void);
19344 @end smallexample
19345
19346 @noindent
19347 Libraries built as explained above can be used from any program, provided
19348 that the elaboration procedures (named @code{mylibinit} in the previous
19349 example) are called before the library services are used. Any number of
19350 libraries can be used simultaneously, as long as the elaboration
19351 procedure of each library is called.
19352
19353 Below is an example of a C program that uses the @code{mylib} library.
19354
19355 @smallexample
19356 #include "mylib_interface.h"
19357
19358 int
19359 main (void)
19360 @{
19361    /* First, elaborate the library before using it */
19362    mylibinit ();
19363
19364    /* Main program, using the library exported entities */
19365    do_something ();
19366    do_something_else ();
19367
19368    /* Library finalization at the end of the program */
19369    mylibfinal ();
19370    return 0;
19371 @}
19372 @end smallexample
19373
19374 @noindent
19375 Note that invoking any library finalization procedure generated by
19376 @code{gnatbind} shuts down the Ada run-time environment.
19377 Consequently, the
19378 finalization of all Ada libraries must be performed at the end of the program.
19379 No call to these libraries or to the Ada run-time library should be made
19380 after the finalization phase.
19381
19382 @node Restrictions in Stand-alone Libraries
19383 @subsection Restrictions in Stand-alone Libraries
19384
19385 @noindent
19386 The pragmas listed below should be used with caution inside libraries,
19387 as they can create incompatibilities with other Ada libraries:
19388 @itemize @bullet
19389 @item pragma @code{Locking_Policy}
19390 @item pragma @code{Queuing_Policy}
19391 @item pragma @code{Task_Dispatching_Policy}
19392 @item pragma @code{Unreserve_All_Interrupts}
19393 @end itemize
19394
19395 @noindent
19396 When using a library that contains such pragmas, the user must make sure
19397 that all libraries use the same pragmas with the same values. Otherwise,
19398 @code{Program_Error} will
19399 be raised during the elaboration of the conflicting
19400 libraries. The usage of these pragmas and its consequences for the user
19401 should therefore be well documented.
19402
19403 Similarly, the traceback in the exception occurrence mechanism should be
19404 enabled or disabled in a consistent manner across all libraries.
19405 Otherwise, Program_Error will be raised during the elaboration of the
19406 conflicting libraries.
19407
19408 If the @code{Version} or @code{Body_Version}
19409 attributes are used inside a library, then you need to
19410 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19411 libraries, so that version identifiers can be properly computed.
19412 In practice these attributes are rarely used, so this is unlikely
19413 to be a consideration.
19414
19415 @node  Rebuilding the GNAT Run-Time Library
19416 @section Rebuilding the GNAT Run-Time Library
19417 @cindex GNAT Run-Time Library, rebuilding
19418 @cindex Building the GNAT Run-Time Library
19419 @cindex Rebuilding the GNAT Run-Time Library
19420 @cindex Run-Time Library, rebuilding
19421
19422 @noindent
19423 It may be useful to recompile the GNAT library in various contexts, the
19424 most important one being the use of partition-wide configuration pragmas
19425 such as @code{Normalize_Scalars}. A special Makefile called
19426 @code{Makefile.adalib} is provided to that effect and can be found in
19427 the directory containing the GNAT library. The location of this
19428 directory depends on the way the GNAT environment has been installed and can
19429 be determined by means of the command:
19430
19431 @smallexample
19432 $ gnatls -v
19433 @end smallexample
19434
19435 @noindent
19436 The last entry in the object search path usually contains the
19437 gnat library. This Makefile contains its own documentation and in
19438 particular the set of instructions needed to rebuild a new library and
19439 to use it.
19440
19441 @node Using the GNU make Utility
19442 @chapter Using the GNU @code{make} Utility
19443 @findex make
19444
19445 @noindent
19446 This chapter offers some examples of makefiles that solve specific
19447 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19448 make, make, GNU @code{make}}), nor does it try to replace the
19449 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19450
19451 All the examples in this section are specific to the GNU version of
19452 make. Although @command{make} is a standard utility, and the basic language
19453 is the same, these examples use some advanced features found only in
19454 @code{GNU make}.
19455
19456 @menu
19457 * Using gnatmake in a Makefile::
19458 * Automatically Creating a List of Directories::
19459 * Generating the Command Line Switches::
19460 * Overcoming Command Line Length Limits::
19461 @end menu
19462
19463 @node Using gnatmake in a Makefile
19464 @section Using gnatmake in a Makefile
19465 @findex makefile
19466 @cindex GNU make
19467
19468 @noindent
19469 Complex project organizations can be handled in a very powerful way by
19470 using GNU make combined with gnatmake. For instance, here is a Makefile
19471 which allows you to build each subsystem of a big project into a separate
19472 shared library. Such a makefile allows you to significantly reduce the link
19473 time of very big applications while maintaining full coherence at
19474 each step of the build process.
19475
19476 The list of dependencies are handled automatically by
19477 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19478 the appropriate directories.
19479
19480 Note that you should also read the example on how to automatically
19481 create the list of directories
19482 (@pxref{Automatically Creating a List of Directories})
19483 which might help you in case your project has a lot of subdirectories.
19484
19485 @smallexample
19486 @iftex
19487 @leftskip=0cm
19488 @font@heightrm=cmr8
19489 @heightrm
19490 @end iftex
19491 ## This Makefile is intended to be used with the following directory
19492 ## configuration:
19493 ##  - The sources are split into a series of csc (computer software components)
19494 ##    Each of these csc is put in its own directory.
19495 ##    Their name are referenced by the directory names.
19496 ##    They will be compiled into shared library (although this would also work
19497 ##    with static libraries
19498 ##  - The main program (and possibly other packages that do not belong to any
19499 ##    csc is put in the top level directory (where the Makefile is).
19500 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19501 ##                    \_ second_csc (sources) __ lib (will contain the library)
19502 ##                    \_ @dots{}
19503 ## Although this Makefile is build for shared library, it is easy to modify
19504 ## to build partial link objects instead (modify the lines with -shared and
19505 ## gnatlink below)
19506 ##
19507 ## With this makefile, you can change any file in the system or add any new
19508 ## file, and everything will be recompiled correctly (only the relevant shared
19509 ## objects will be recompiled, and the main program will be re-linked).
19510
19511 # The list of computer software component for your project. This might be
19512 # generated automatically.
19513 CSC_LIST=aa bb cc
19514
19515 # Name of the main program (no extension)
19516 MAIN=main
19517
19518 # If we need to build objects with -fPIC, uncomment the following line
19519 #NEED_FPIC=-fPIC
19520
19521 # The following variable should give the directory containing libgnat.so
19522 # You can get this directory through 'gnatls -v'. This is usually the last
19523 # directory in the Object_Path.
19524 GLIB=@dots{}
19525
19526 # The directories for the libraries
19527 # (This macro expands the list of CSC to the list of shared libraries, you
19528 # could simply use the expanded form:
19529 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19530 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19531
19532 $@{MAIN@}: objects $@{LIB_DIR@}
19533     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19534     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19535
19536 objects::
19537     # recompile the sources
19538     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19539
19540 # Note: In a future version of GNAT, the following commands will be simplified
19541 # by a new tool, gnatmlib
19542 $@{LIB_DIR@}:
19543     mkdir -p $@{dir $@@ @}
19544     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19545     cd $@{dir $@@ @} && cp -f ../*.ali .
19546
19547 # The dependencies for the modules
19548 # Note that we have to force the expansion of *.o, since in some cases
19549 # make won't be able to do it itself.
19550 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19551 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19552 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19553
19554 # Make sure all of the shared libraries are in the path before starting the
19555 # program
19556 run::
19557     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19558
19559 clean::
19560     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19561     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19562     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19563     $@{RM@} *.o *.ali $@{MAIN@}
19564 @end smallexample
19565
19566 @node Automatically Creating a List of Directories
19567 @section Automatically Creating a List of Directories
19568
19569 @noindent
19570 In most makefiles, you will have to specify a list of directories, and
19571 store it in a variable. For small projects, it is often easier to
19572 specify each of them by hand, since you then have full control over what
19573 is the proper order for these directories, which ones should be
19574 included.
19575
19576 However, in larger projects, which might involve hundreds of
19577 subdirectories, it might be more convenient to generate this list
19578 automatically.
19579
19580 The example below presents two methods. The first one, although less
19581 general, gives you more control over the list. It involves wildcard
19582 characters, that are automatically expanded by @command{make}. Its
19583 shortcoming is that you need to explicitly specify some of the
19584 organization of your project, such as for instance the directory tree
19585 depth, whether some directories are found in a separate tree, @enddots{}
19586
19587 The second method is the most general one. It requires an external
19588 program, called @command{find}, which is standard on all Unix systems. All
19589 the directories found under a given root directory will be added to the
19590 list.
19591
19592 @smallexample
19593 @iftex
19594 @leftskip=0cm
19595 @font@heightrm=cmr8
19596 @heightrm
19597 @end iftex
19598 # The examples below are based on the following directory hierarchy:
19599 # All the directories can contain any number of files
19600 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19601 #                       ->  ab
19602 #                       ->  ac
19603 #                ->  b  ->  ba  ->  baa
19604 #                       ->  bb
19605 #                       ->  bc
19606 # This Makefile creates a variable called DIRS, that can be reused any time
19607 # you need this list (see the other examples in this section)
19608
19609 # The root of your project's directory hierarchy
19610 ROOT_DIRECTORY=.
19611
19612 ####
19613 # First method: specify explicitly the list of directories
19614 # This allows you to specify any subset of all the directories you need.
19615 ####
19616
19617 DIRS := a/aa/ a/ab/ b/ba/
19618
19619 ####
19620 # Second method: use wildcards
19621 # Note that the argument(s) to wildcard below should end with a '/'.
19622 # Since wildcards also return file names, we have to filter them out
19623 # to avoid duplicate directory names.
19624 # We thus use make's @code{dir} and @code{sort} functions.
19625 # It sets DIRs to the following value (note that the directories aaa and baa
19626 # are not given, unless you change the arguments to wildcard).
19627 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19628 ####
19629
19630 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19631                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19632
19633 ####
19634 # Third method: use an external program
19635 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19636 # This is the most complete command: it sets DIRs to the following value:
19637 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19638 ####
19639
19640 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19641
19642 @end smallexample
19643
19644 @node Generating the Command Line Switches
19645 @section Generating the Command Line Switches
19646
19647 @noindent
19648 Once you have created the list of directories as explained in the
19649 previous section (@pxref{Automatically Creating a List of Directories}),
19650 you can easily generate the command line arguments to pass to gnatmake.
19651
19652 For the sake of completeness, this example assumes that the source path
19653 is not the same as the object path, and that you have two separate lists
19654 of directories.
19655
19656 @smallexample
19657 # see "Automatically creating a list of directories" to create
19658 # these variables
19659 SOURCE_DIRS=
19660 OBJECT_DIRS=
19661
19662 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19663 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19664
19665 all:
19666         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19667 @end smallexample
19668
19669 @node Overcoming Command Line Length Limits
19670 @section Overcoming Command Line Length Limits
19671
19672 @noindent
19673 One problem that might be encountered on big projects is that many
19674 operating systems limit the length of the command line. It is thus hard to give
19675 gnatmake the list of source and object directories.
19676
19677 This example shows how you can set up environment variables, which will
19678 make @command{gnatmake} behave exactly as if the directories had been
19679 specified on the command line, but have a much higher length limit (or
19680 even none on most systems).
19681
19682 It assumes that you have created a list of directories in your Makefile,
19683 using one of the methods presented in
19684 @ref{Automatically Creating a List of Directories}.
19685 For the sake of completeness, we assume that the object
19686 path (where the ALI files are found) is different from the sources patch.
19687
19688 Note a small trick in the Makefile below: for efficiency reasons, we
19689 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19690 expanded immediately by @code{make}. This way we overcome the standard
19691 make behavior which is to expand the variables only when they are
19692 actually used.
19693
19694 On Windows, if you are using the standard Windows command shell, you must
19695 replace colons with semicolons in the assignments to these variables.
19696
19697 @smallexample
19698 @iftex
19699 @leftskip=0cm
19700 @font@heightrm=cmr8
19701 @heightrm
19702 @end iftex
19703 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19704 # This is the same thing as putting the -I arguments on the command line.
19705 # (the equivalent of using -aI on the command line would be to define
19706 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19707 # You can of course have different values for these variables.
19708 #
19709 # Note also that we need to keep the previous values of these variables, since
19710 # they might have been set before running 'make' to specify where the GNAT
19711 # library is installed.
19712
19713 # see "Automatically creating a list of directories" to create these
19714 # variables
19715 SOURCE_DIRS=
19716 OBJECT_DIRS=
19717
19718 empty:=
19719 space:=$@{empty@} $@{empty@}
19720 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19721 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19722 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19723 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19724 export ADA_INCLUDE_PATH
19725 export ADA_OBJECT_PATH
19726
19727 all:
19728         gnatmake main_unit
19729 @end smallexample
19730 @end ifclear
19731
19732 @node Memory Management Issues
19733 @chapter Memory Management Issues
19734
19735 @noindent
19736 This chapter describes some useful memory pools provided in the GNAT library
19737 and in particular the GNAT Debug Pool facility, which can be used to detect
19738 incorrect uses of access values (including ``dangling references'').
19739 @ifclear vms
19740 It also describes the @command{gnatmem} tool, which can be used to track down
19741 ``memory leaks''.
19742 @end ifclear
19743
19744 @menu
19745 * Some Useful Memory Pools::
19746 * The GNAT Debug Pool Facility::
19747 @ifclear vms
19748 * The gnatmem Tool::
19749 @end ifclear
19750 @end menu
19751
19752 @node Some Useful Memory Pools
19753 @section Some Useful Memory Pools
19754 @findex Memory Pool
19755 @cindex storage, pool
19756
19757 @noindent
19758 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19759 storage pool. Allocations use the standard system call @code{malloc} while
19760 deallocations use the standard system call @code{free}. No reclamation is
19761 performed when the pool goes out of scope. For performance reasons, the
19762 standard default Ada allocators/deallocators do not use any explicit storage
19763 pools but if they did, they could use this storage pool without any change in
19764 behavior. That is why this storage pool is used  when the user
19765 manages to make the default implicit allocator explicit as in this example:
19766 @smallexample @c ada
19767    type T1 is access Something;
19768     -- no Storage pool is defined for T2
19769    type T2 is access Something_Else;
19770    for T2'Storage_Pool use T1'Storage_Pool;
19771    -- the above is equivalent to
19772    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19773 @end smallexample
19774
19775 @noindent
19776 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19777 pool. The allocation strategy is similar to @code{Pool_Local}'s
19778 except that the all
19779 storage allocated with this pool is reclaimed when the pool object goes out of
19780 scope. This pool provides a explicit mechanism similar to the implicit one
19781 provided by several Ada 83 compilers for allocations performed through a local
19782 access type and whose purpose was to reclaim memory when exiting the
19783 scope of a given local access. As an example, the following program does not
19784 leak memory even though it does not perform explicit deallocation:
19785
19786 @smallexample @c ada
19787 with System.Pool_Local;
19788 procedure Pooloc1 is
19789    procedure Internal is
19790       type A is access Integer;
19791       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19792       for A'Storage_Pool use X;
19793       v : A;
19794    begin
19795       for I in  1 .. 50 loop
19796          v := new Integer;
19797       end loop;
19798    end Internal;
19799 begin
19800    for I in  1 .. 100 loop
19801       Internal;
19802    end loop;
19803 end Pooloc1;
19804 @end smallexample
19805
19806 @noindent
19807 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19808 @code{Storage_Size} is specified for an access type.
19809 The whole storage for the pool is
19810 allocated at once, usually on the stack at the point where the access type is
19811 elaborated. It is automatically reclaimed when exiting the scope where the
19812 access type is defined. This package is not intended to be used directly by the
19813 user and it is implicitly used for each such declaration:
19814
19815 @smallexample @c ada
19816    type T1 is access Something;
19817    for T1'Storage_Size use 10_000;
19818 @end smallexample
19819
19820 @node The GNAT Debug Pool Facility
19821 @section The GNAT Debug Pool Facility
19822 @findex Debug Pool
19823 @cindex storage, pool, memory corruption
19824
19825 @noindent
19826 The use of unchecked deallocation and unchecked conversion can easily
19827 lead to incorrect memory references. The problems generated by such
19828 references are usually difficult to tackle because the symptoms can be
19829 very remote from the origin of the problem. In such cases, it is
19830 very helpful to detect the problem as early as possible. This is the
19831 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19832
19833 In order to use the GNAT specific debugging pool, the user must
19834 associate a debug pool object with each of the access types that may be
19835 related to suspected memory problems. See Ada Reference Manual 13.11.
19836 @smallexample @c ada
19837 type Ptr is access Some_Type;
19838 Pool : GNAT.Debug_Pools.Debug_Pool;
19839 for Ptr'Storage_Pool use Pool;
19840 @end smallexample
19841
19842 @noindent
19843 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19844 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19845 allow the user to redefine allocation and deallocation strategies. They
19846 also provide a checkpoint for each dereference, through the use of
19847 the primitive operation @code{Dereference} which is implicitly called at
19848 each dereference of an access value.
19849
19850 Once an access type has been associated with a debug pool, operations on
19851 values of the type may raise four distinct exceptions,
19852 which correspond to four potential kinds of memory corruption:
19853 @itemize @bullet
19854 @item
19855 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19856 @item
19857 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19858 @item
19859 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19860 @item
19861 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19862 @end itemize
19863
19864 @noindent
19865 For types associated with a Debug_Pool, dynamic allocation is performed using
19866 the standard GNAT allocation routine. References to all allocated chunks of
19867 memory are kept in an internal dictionary. Several deallocation strategies are
19868 provided, whereupon the user can choose to release the memory to the system,
19869 keep it allocated for further invalid access checks, or fill it with an easily
19870 recognizable pattern for debug sessions. The memory pattern is the old IBM
19871 hexadecimal convention: @code{16#DEADBEEF#}.
19872
19873 See the documentation in the file g-debpoo.ads for more information on the
19874 various strategies.
19875
19876 Upon each dereference, a check is made that the access value denotes a
19877 properly allocated memory location. Here is a complete example of use of
19878 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19879 @smallexample @c ada
19880 @iftex
19881 @leftskip=0cm
19882 @end iftex
19883 with Gnat.Io; use Gnat.Io;
19884 with Unchecked_Deallocation;
19885 with Unchecked_Conversion;
19886 with GNAT.Debug_Pools;
19887 with System.Storage_Elements;
19888 with Ada.Exceptions; use Ada.Exceptions;
19889 procedure Debug_Pool_Test is
19890
19891    type T is access Integer;
19892    type U is access all T;
19893
19894    P : GNAT.Debug_Pools.Debug_Pool;
19895    for T'Storage_Pool use P;
19896
19897    procedure Free is new Unchecked_Deallocation (Integer, T);
19898    function UC is new Unchecked_Conversion (U, T);
19899    A, B : aliased T;
19900
19901    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19902
19903 begin
19904    Info (P);
19905    A := new Integer;
19906    B := new Integer;
19907    B := A;
19908    Info (P);
19909    Free (A);
19910    begin
19911       Put_Line (Integer'Image(B.all));
19912    exception
19913       when E : others => Put_Line ("raised: " & Exception_Name (E));
19914    end;
19915    begin
19916       Free (B);
19917    exception
19918       when E : others => Put_Line ("raised: " & Exception_Name (E));
19919    end;
19920    B := UC(A'Access);
19921    begin
19922       Put_Line (Integer'Image(B.all));
19923    exception
19924       when E : others => Put_Line ("raised: " & Exception_Name (E));
19925    end;
19926    begin
19927       Free (B);
19928    exception
19929       when E : others => Put_Line ("raised: " & Exception_Name (E));
19930    end;
19931    Info (P);
19932 end Debug_Pool_Test;
19933 @end smallexample
19934
19935 @noindent
19936 The debug pool mechanism provides the following precise diagnostics on the
19937 execution of this erroneous program:
19938 @smallexample
19939 Debug Pool info:
19940   Total allocated bytes :  0
19941   Total deallocated bytes :  0
19942   Current Water Mark:  0
19943   High Water Mark:  0
19944
19945 Debug Pool info:
19946   Total allocated bytes :  8
19947   Total deallocated bytes :  0
19948   Current Water Mark:  8
19949   High Water Mark:  8
19950
19951 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19952 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19953 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19954 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19955 Debug Pool info:
19956   Total allocated bytes :  8
19957   Total deallocated bytes :  4
19958   Current Water Mark:  4
19959   High Water Mark:  8
19960 @end smallexample
19961
19962 @ifclear vms
19963 @node The gnatmem Tool
19964 @section The @command{gnatmem} Tool
19965 @findex gnatmem
19966
19967 @noindent
19968 The @code{gnatmem} utility monitors dynamic allocation and
19969 deallocation activity in a program, and displays information about
19970 incorrect deallocations and possible sources of memory leaks.
19971 It is designed to work in association with a static runtime library
19972 only and in this context provides three types of information:
19973 @itemize @bullet
19974 @item
19975 General information concerning memory management, such as the total
19976 number of allocations and deallocations, the amount of allocated
19977 memory and the high water mark, i.e.@: the largest amount of allocated
19978 memory in the course of program execution.
19979
19980 @item
19981 Backtraces for all incorrect deallocations, that is to say deallocations
19982 which do not correspond to a valid allocation.
19983
19984 @item
19985 Information on each allocation that is potentially the origin of a memory
19986 leak.
19987 @end itemize
19988
19989 @menu
19990 * Running gnatmem::
19991 * Switches for gnatmem::
19992 * Example of gnatmem Usage::
19993 @end menu
19994
19995 @node Running gnatmem
19996 @subsection Running @code{gnatmem}
19997
19998 @noindent
19999 @code{gnatmem} makes use of the output created by the special version of
20000 allocation and deallocation routines that record call information. This
20001 allows to obtain accurate dynamic memory usage history at a minimal cost to
20002 the execution speed. Note however, that @code{gnatmem} is not supported on
20003 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20004 Solaris and Windows NT/2000/XP (x86).
20005
20006 @noindent
20007 The @code{gnatmem} command has the form
20008
20009 @smallexample
20010    $ gnatmem @ovar{switches} user_program
20011 @end smallexample
20012
20013 @noindent
20014 The program must have been linked with the instrumented version of the
20015 allocation and deallocation routines. This is done by linking with the
20016 @file{libgmem.a} library. For correct symbolic backtrace information,
20017 the user program should be compiled with debugging options
20018 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20019
20020 @smallexample
20021 $ gnatmake -g my_program -largs -lgmem
20022 @end smallexample
20023
20024 @noindent
20025 As library @file{libgmem.a} contains an alternate body for package
20026 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20027 when an executable is linked with library @file{libgmem.a}. It is then not
20028 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20029
20030 @noindent
20031 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20032 This file contains information about all allocations and deallocations
20033 performed by the program. It is produced by the instrumented allocations and
20034 deallocations routines and will be used by @code{gnatmem}.
20035
20036 In order to produce symbolic backtrace information for allocations and
20037 deallocations performed by the GNAT run-time library, you need to use a
20038 version of that library that has been compiled with the @option{-g} switch
20039 (see @ref{Rebuilding the GNAT Run-Time Library}).
20040
20041 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20042 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20043 @option{-i} switch, gnatmem will assume that this file can be found in the
20044 current directory. For example, after you have executed @file{my_program},
20045 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20046
20047 @smallexample
20048 $ gnatmem my_program
20049 @end smallexample
20050
20051 @noindent
20052 This will produce the output with the following format:
20053
20054 *************** debut cc
20055 @smallexample
20056 $ gnatmem my_program
20057
20058 Global information
20059 ------------------
20060    Total number of allocations        :  45
20061    Total number of deallocations      :   6
20062    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20063    High Water Mark                    :  11.40 Kilobytes
20064
20065 .
20066 .
20067 .
20068 Allocation Root # 2
20069 -------------------
20070  Number of non freed allocations    :  11
20071  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20072  High Water Mark                    :   1.27 Kilobytes
20073  Backtrace                          :
20074    my_program.adb:23 my_program.alloc
20075 .
20076 .
20077 .
20078 @end smallexample
20079
20080 The first block of output gives general information. In this case, the
20081 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20082 Unchecked_Deallocation routine occurred.
20083
20084 @noindent
20085 Subsequent paragraphs display  information on all allocation roots.
20086 An allocation root is a specific point in the execution of the program
20087 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20088 construct. This root is represented by an execution backtrace (or subprogram
20089 call stack). By default the backtrace depth for allocations roots is 1, so
20090 that a root corresponds exactly to a source location. The backtrace can
20091 be made deeper, to make the root more specific.
20092
20093 @node Switches for gnatmem
20094 @subsection Switches for @code{gnatmem}
20095
20096 @noindent
20097 @code{gnatmem} recognizes the following switches:
20098
20099 @table @option
20100
20101 @item -q
20102 @cindex @option{-q} (@code{gnatmem})
20103 Quiet. Gives the minimum output needed to identify the origin of the
20104 memory leaks. Omits statistical information.
20105
20106 @item @var{N}
20107 @cindex @var{N} (@code{gnatmem})
20108 N is an integer literal (usually between 1 and 10) which controls the
20109 depth of the backtraces defining allocation root. The default value for
20110 N is 1. The deeper the backtrace, the more precise the localization of
20111 the root. Note that the total number of roots can depend on this
20112 parameter. This parameter must be specified @emph{before} the name of the
20113 executable to be analyzed, to avoid ambiguity.
20114
20115 @item -b n
20116 @cindex @option{-b} (@code{gnatmem})
20117 This switch has the same effect as just depth parameter.
20118
20119 @item -i @var{file}
20120 @cindex @option{-i} (@code{gnatmem})
20121 Do the @code{gnatmem} processing starting from @file{file}, rather than
20122 @file{gmem.out} in the current directory.
20123
20124 @item -m n
20125 @cindex @option{-m} (@code{gnatmem})
20126 This switch causes @code{gnatmem} to mask the allocation roots that have less
20127 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20128 examine even the roots that didn't result in leaks.
20129
20130 @item -s order
20131 @cindex @option{-s} (@code{gnatmem})
20132 This switch causes @code{gnatmem} to sort the allocation roots according to the
20133 specified order of sort criteria, each identified by a single letter. The
20134 currently supported criteria are @code{n, h, w} standing respectively for
20135 number of unfreed allocations, high watermark, and final watermark
20136 corresponding to a specific root. The default order is @code{nwh}.
20137
20138 @end table
20139
20140 @node Example of gnatmem Usage
20141 @subsection Example of @code{gnatmem} Usage
20142
20143 @noindent
20144 The following example shows the use of @code{gnatmem}
20145 on a simple memory-leaking program.
20146 Suppose that we have the following Ada program:
20147
20148 @smallexample @c ada
20149 @group
20150 @cartouche
20151 with Unchecked_Deallocation;
20152 procedure Test_Gm is
20153
20154    type T is array (1..1000) of Integer;
20155    type Ptr is access T;
20156    procedure Free is new Unchecked_Deallocation (T, Ptr);
20157    A : Ptr;
20158
20159    procedure My_Alloc is
20160    begin
20161       A := new T;
20162    end My_Alloc;
20163
20164    procedure My_DeAlloc is
20165       B : Ptr := A;
20166    begin
20167       Free (B);
20168    end My_DeAlloc;
20169
20170 begin
20171    My_Alloc;
20172    for I in 1 .. 5 loop
20173       for J in I .. 5 loop
20174          My_Alloc;
20175       end loop;
20176       My_Dealloc;
20177    end loop;
20178 end;
20179 @end cartouche
20180 @end group
20181 @end smallexample
20182
20183 @noindent
20184 The program needs to be compiled with debugging option and linked with
20185 @code{gmem} library:
20186
20187 @smallexample
20188 $ gnatmake -g test_gm -largs -lgmem
20189 @end smallexample
20190
20191 @noindent
20192 Then we execute the program as usual:
20193
20194 @smallexample
20195 $ test_gm
20196 @end smallexample
20197
20198 @noindent
20199 Then @code{gnatmem} is invoked simply with
20200 @smallexample
20201 $ gnatmem test_gm
20202 @end smallexample
20203
20204 @noindent
20205 which produces the following output (result may vary on different platforms):
20206
20207 @smallexample
20208 Global information
20209 ------------------
20210    Total number of allocations        :  18
20211    Total number of deallocations      :   5
20212    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20213    High Water Mark                    :  56.90 Kilobytes
20214
20215 Allocation Root # 1
20216 -------------------
20217  Number of non freed allocations    :  11
20218  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20219  High Water Mark                    :  46.88 Kilobytes
20220  Backtrace                          :
20221    test_gm.adb:11 test_gm.my_alloc
20222
20223 Allocation Root # 2
20224 -------------------
20225  Number of non freed allocations    :   1
20226  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20227  High Water Mark                    :  10.02 Kilobytes
20228  Backtrace                          :
20229    s-secsta.adb:81 system.secondary_stack.ss_init
20230
20231 Allocation Root # 3
20232 -------------------
20233  Number of non freed allocations    :   1
20234  Final Water Mark (non freed mem)   :  12 Bytes
20235  High Water Mark                    :  12 Bytes
20236  Backtrace                          :
20237    s-secsta.adb:181 system.secondary_stack.ss_init
20238 @end smallexample
20239
20240 @noindent
20241 Note that the GNAT run time contains itself a certain number of
20242 allocations that have no  corresponding deallocation,
20243 as shown here for root #2 and root
20244 #3. This is a normal behavior when the number of non-freed allocations
20245 is one, it allocates dynamic data structures that the run time needs for
20246 the complete lifetime of the program. Note also that there is only one
20247 allocation root in the user program with a single line back trace:
20248 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20249 program shows that 'My_Alloc' is called at 2 different points in the
20250 source (line 21 and line 24). If those two allocation roots need to be
20251 distinguished, the backtrace depth parameter can be used:
20252
20253 @smallexample
20254 $ gnatmem 3 test_gm
20255 @end smallexample
20256
20257 @noindent
20258 which will give the following output:
20259
20260 @smallexample
20261 Global information
20262 ------------------
20263    Total number of allocations        :  18
20264    Total number of deallocations      :   5
20265    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20266    High Water Mark                    :  56.90 Kilobytes
20267
20268 Allocation Root # 1
20269 -------------------
20270  Number of non freed allocations    :  10
20271  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20272  High Water Mark                    :  42.97 Kilobytes
20273  Backtrace                          :
20274    test_gm.adb:11 test_gm.my_alloc
20275    test_gm.adb:24 test_gm
20276    b_test_gm.c:52 main
20277
20278 Allocation Root # 2
20279 -------------------
20280  Number of non freed allocations    :   1
20281  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20282  High Water Mark                    :  10.02 Kilobytes
20283  Backtrace                          :
20284    s-secsta.adb:81  system.secondary_stack.ss_init
20285    s-secsta.adb:283 <system__secondary_stack___elabb>
20286    b_test_gm.c:33   adainit
20287
20288 Allocation Root # 3
20289 -------------------
20290  Number of non freed allocations    :   1
20291  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20292  High Water Mark                    :   3.91 Kilobytes
20293  Backtrace                          :
20294    test_gm.adb:11 test_gm.my_alloc
20295    test_gm.adb:21 test_gm
20296    b_test_gm.c:52 main
20297
20298 Allocation Root # 4
20299 -------------------
20300  Number of non freed allocations    :   1
20301  Final Water Mark (non freed mem)   :  12 Bytes
20302  High Water Mark                    :  12 Bytes
20303  Backtrace                          :
20304    s-secsta.adb:181 system.secondary_stack.ss_init
20305    s-secsta.adb:283 <system__secondary_stack___elabb>
20306    b_test_gm.c:33   adainit
20307 @end smallexample
20308
20309 @noindent
20310 The allocation root #1 of the first example has been split in 2 roots #1
20311 and #3 thanks to the more precise associated backtrace.
20312
20313 @end ifclear
20314
20315 @node Stack Related Facilities
20316 @chapter Stack Related Facilities
20317
20318 @noindent
20319 This chapter describes some useful tools associated with stack
20320 checking and analysis. In
20321 particular, it deals with dynamic and static stack usage measurements.
20322
20323 @menu
20324 * Stack Overflow Checking::
20325 * Static Stack Usage Analysis::
20326 * Dynamic Stack Usage Analysis::
20327 @end menu
20328
20329 @node Stack Overflow Checking
20330 @section Stack Overflow Checking
20331 @cindex Stack Overflow Checking
20332 @cindex -fstack-check
20333
20334 @noindent
20335 For most operating systems, @command{gcc} does not perform stack overflow
20336 checking by default. This means that if the main environment task or
20337 some other task exceeds the available stack space, then unpredictable
20338 behavior will occur. Most native systems offer some level of protection by
20339 adding a guard page at the end of each task stack. This mechanism is usually
20340 not enough for dealing properly with stack overflow situations because
20341 a large local variable could ``jump'' above the guard page.
20342 Furthermore, when the
20343 guard page is hit, there may not be any space left on the stack for executing
20344 the exception propagation code. Enabling stack checking avoids
20345 such situations.
20346
20347 To activate stack checking, compile all units with the gcc option
20348 @option{-fstack-check}. For example:
20349
20350 @smallexample
20351 gcc -c -fstack-check package1.adb
20352 @end smallexample
20353
20354 @noindent
20355 Units compiled with this option will generate extra instructions to check
20356 that any use of the stack (for procedure calls or for declaring local
20357 variables in declare blocks) does not exceed the available stack space.
20358 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20359
20360 For declared tasks, the stack size is controlled by the size
20361 given in an applicable @code{Storage_Size} pragma or by the value specified
20362 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20363 the default size as defined in the GNAT runtime otherwise.
20364
20365 For the environment task, the stack size depends on
20366 system defaults and is unknown to the compiler. Stack checking
20367 may still work correctly if a fixed
20368 size stack is allocated, but this cannot be guaranteed.
20369 @ifclear vms
20370 To ensure that a clean exception is signalled for stack
20371 overflow, set the environment variable
20372 @env{GNAT_STACK_LIMIT} to indicate the maximum
20373 stack area that can be used, as in:
20374 @cindex GNAT_STACK_LIMIT
20375
20376 @smallexample
20377 SET GNAT_STACK_LIMIT 1600
20378 @end smallexample
20379
20380 @noindent
20381 The limit is given in kilobytes, so the above declaration would
20382 set the stack limit of the environment task to 1.6 megabytes.
20383 Note that the only purpose of this usage is to limit the amount
20384 of stack used by the environment task. If it is necessary to
20385 increase the amount of stack for the environment task, then this
20386 is an operating systems issue, and must be addressed with the
20387 appropriate operating systems commands.
20388 @end ifclear
20389 @ifset vms
20390 To have a fixed size stack in the environment task, the stack must be put
20391 in the P0 address space and its size specified.  Use these switches to
20392 create a p0 image:
20393
20394 @smallexample
20395 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20396 @end smallexample
20397
20398 @noindent
20399 The quotes are required to keep case.  The number after @samp{STACK=} is the
20400 size of the environmental task stack in pagelets (512 bytes).  In this example
20401 the stack size is about 2 megabytes.
20402
20403 @noindent
20404 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20405 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20406 more details about the @option{/p0image} qualifier and the @option{stack}
20407 option.
20408 @end ifset
20409
20410 @node Static Stack Usage Analysis
20411 @section Static Stack Usage Analysis
20412 @cindex Static Stack Usage Analysis
20413 @cindex -fstack-usage
20414
20415 @noindent
20416 A unit compiled with @option{-fstack-usage} will generate an extra file
20417 that specifies
20418 the maximum amount of stack used, on a per-function basis.
20419 The file has the same
20420 basename as the target object file with a @file{.su} extension.
20421 Each line of this file is made up of three fields:
20422
20423 @itemize
20424 @item
20425 The name of the function.
20426 @item
20427 A number of bytes.
20428 @item
20429 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20430 @end itemize
20431
20432 The second field corresponds to the size of the known part of the function
20433 frame.
20434
20435 The qualifier @code{static} means that the function frame size
20436 is purely static.
20437 It usually means that all local variables have a static size.
20438 In this case, the second field is a reliable measure of the function stack
20439 utilization.
20440
20441 The qualifier @code{dynamic} means that the function frame size is not static.
20442 It happens mainly when some local variables have a dynamic size. When this
20443 qualifier appears alone, the second field is not a reliable measure
20444 of the function stack analysis. When it is qualified with  @code{bounded}, it
20445 means that the second field is a reliable maximum of the function stack
20446 utilization.
20447
20448 @node Dynamic Stack Usage Analysis
20449 @section Dynamic Stack Usage Analysis
20450
20451 @noindent
20452 It is possible to measure the maximum amount of stack used by a task, by
20453 adding a switch to @command{gnatbind}, as:
20454
20455 @smallexample
20456 $ gnatbind -u0 file
20457 @end smallexample
20458
20459 @noindent
20460 With this option, at each task termination, its stack usage is  output on
20461 @file{stderr}.
20462 It is not always convenient to output the stack usage when the program
20463 is still running. Hence, it is possible to delay this output until program
20464 termination. for a given number of tasks specified as the argument of the
20465 @option{-u} option. For instance:
20466
20467 @smallexample
20468 $ gnatbind -u100 file
20469 @end smallexample
20470
20471 @noindent
20472 will buffer the stack usage information of the first 100 tasks to terminate and
20473 output this info at program termination. Results are displayed in four
20474 columns:
20475
20476 @noindent
20477 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20478
20479 @noindent
20480 where:
20481
20482 @table @emph
20483 @item Index
20484 is a number associated with each task.
20485
20486 @item Task Name
20487 is the name of the task analyzed.
20488
20489 @item Stack Size
20490 is the maximum size for the stack.
20491
20492 @item Stack Usage
20493 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20494 is not entirely analyzed, and it's not possible to know exactly how
20495 much has actually been used. The report thus contains the theoretical stack usage
20496 (Value) and the possible variation (Variation) around this value.
20497
20498 @end table
20499
20500 @noindent
20501 The environment task stack, e.g., the stack that contains the main unit, is
20502 only processed when the environment variable GNAT_STACK_LIMIT is set.
20503
20504
20505 @c *********************************
20506 @c *            GNATCHECK          *
20507 @c *********************************
20508 @node Verifying Properties Using gnatcheck
20509 @chapter Verifying Properties Using @command{gnatcheck}
20510 @findex gnatcheck
20511 @cindex @command{gnatcheck}
20512
20513 @noindent
20514 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20515 of Ada source files according to a given set of semantic rules.
20516 @cindex ASIS
20517
20518 In order to check compliance with a given rule, @command{gnatcheck} has to
20519 semantically analyze the Ada sources.
20520 Therefore, checks can only be performed on
20521 legal Ada units. Moreover, when a unit depends semantically upon units located
20522 outside the current directory, the source search path has to be provided when
20523 calling @command{gnatcheck}, either through a specified project file or
20524 through @command{gnatcheck} switches as described below.
20525
20526 A number of rules are predefined in @command{gnatcheck} and are described
20527 later in this chapter.
20528 You can also add new rules, by modifying the @command{gnatcheck} code and
20529 rebuilding the tool. In order to add a simple rule making some local checks,
20530 a small amount of straightforward ASIS-based programming is usually needed.
20531
20532 Project support for @command{gnatcheck} is provided by the GNAT
20533 driver (see @ref{The GNAT Driver and Project Files}).
20534
20535 Invoking @command{gnatcheck} on the command line has the form:
20536
20537 @smallexample
20538 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20539       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20540       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20541 @end smallexample
20542
20543 @noindent
20544 where
20545 @itemize @bullet
20546 @item
20547 @var{switches} specify the general tool options
20548
20549 @item
20550 Each @var{filename} is the name (including the extension) of a source
20551 file to process. ``Wildcards'' are allowed, and
20552 the file name may contain path information.
20553
20554 @item
20555 Each @var{arg_list_filename} is the name (including the extension) of a text
20556 file containing the names of the source files to process, separated by spaces
20557 or line breaks.
20558
20559 @item
20560 @var{gcc_switches} is a list of switches for
20561 @command{gcc}. They will be passed on to all compiler invocations made by
20562 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20563 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20564 and use the @option{-gnatec} switch to set the configuration file.
20565
20566 @item
20567 @var{rule_options} is a list of options for controlling a set of
20568 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20569 @end itemize
20570
20571 @noindent
20572 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20573
20574 @menu
20575 * Format of the Report File::
20576 * General gnatcheck Switches::
20577 * gnatcheck Rule Options::
20578 * Adding the Results of Compiler Checks to gnatcheck Output::
20579 * Project-Wide Checks::
20580 * Predefined Rules::
20581 @end menu
20582
20583 @node Format of the Report File
20584 @section Format of the Report File
20585 @cindex Report file (for @code{gnatcheck})
20586
20587 @noindent
20588 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20589 rule violations.
20590 It also creates a text file  that
20591 contains the complete report of the last gnatcheck run. By default this file is
20592 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20593 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20594 location of the report file. This report contains:
20595 @itemize @bullet
20596 @item a list of the Ada source files being checked,
20597 @item a list of enabled and disabled rules,
20598 @item a list of the diagnostic messages, ordered in three different ways
20599 and collected in three separate
20600 sections. Section 1 contains the raw list of diagnostic messages. It
20601 corresponds to the output going to @file{stdout}. Section 2 contains
20602 messages ordered by rules.
20603 Section 3 contains messages ordered by source files.
20604 @end itemize
20605
20606 @node General gnatcheck Switches
20607 @section General @command{gnatcheck} Switches
20608
20609 @noindent
20610 The following switches control the general @command{gnatcheck} behavior
20611
20612 @table @option
20613 @c !sort!
20614 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20615 @item ^-a^/ALL^
20616 Process all units including those with read-only ALI files such as
20617 those from GNAT Run-Time library.
20618
20619 @ifclear vms
20620 @ignore
20621 @cindex @option{-d} (@command{gnatcheck})
20622 @item -d
20623 Debug mode
20624 @end ignore
20625
20626 @cindex @option{-dd} (@command{gnatcheck})
20627 @item -dd
20628 Progress indicator mode (for use in GPS)
20629 @end ifclear
20630
20631 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20632 @item ^-h^/HELP^
20633 List the predefined and user-defined rules. For more details see
20634 @ref{Predefined Rules}.
20635
20636 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20637 @item ^-l^/LOCS^
20638 Use full source locations references in the report file. For a construct from
20639 a generic instantiation a full source location is a chain from the location
20640 of this construct in the generic unit to the place where this unit is
20641 instantiated.
20642
20643 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20644 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20645 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20646 the default value is 500. Zero means that there is no limitation on
20647 the number of diagnostic messages to be printed into Stdout.
20648
20649 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20650 @item ^-q^/QUIET^
20651 Quiet mode. All the diagnoses about rule violations are placed in the
20652 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20653
20654 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20655 @item ^-s^/SHORT^
20656 Short format of the report file (no version information, no list of applied
20657 rules, no list of checked sources is included)
20658
20659 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20660 @item ^-s1^/COMPILER_STYLE^
20661 Include the compiler-style section in the report file
20662
20663 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20664 @item ^-s2^/BY_RULES^
20665 Include the section containing diagnoses ordered by rules in the report file
20666
20667 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20668 @item ^-s3^/BY_FILES_BY_RULES^
20669 Include the section containing diagnoses ordered by files and then by rules
20670 in the report file
20671
20672 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20673 @item ^-v^/VERBOSE^
20674 Verbose mode; @command{gnatcheck} generates version information and then
20675 a trace of sources being processed.
20676
20677
20678 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20679 @item ^-o ^/OUTPUT=^@var{report_file}
20680 Set name of report file file to @var{report_file} .
20681
20682 @end table
20683
20684 @noindent
20685 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20686 @option{^-s2^/BY_RULES^} or
20687 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20688 then the  @command{gnatcheck} report file will only contain sections
20689 explicitly denoted by these options.
20690
20691 @node gnatcheck Rule Options
20692 @section @command{gnatcheck} Rule Options
20693
20694 @noindent
20695 The following options control the processing performed by
20696 @command{gnatcheck}.
20697
20698 @table @option
20699 @cindex @option{+ALL} (@command{gnatcheck})
20700 @item +ALL
20701 Turn all the rule checks ON.
20702
20703 @cindex @option{-ALL} (@command{gnatcheck})
20704 @item -ALL
20705 Turn all the rule checks OFF.
20706
20707 @cindex @option{+R} (@command{gnatcheck})
20708 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20709 Turn on the check for a specified rule with the specified parameter, if any.
20710 @var{rule_id} must be the identifier of one of the currently implemented rules
20711 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20712 are not case-sensitive. The @var{param} item must
20713 be a string representing a valid parameter(s) for the specified rule.
20714 If it contains any space characters then this string must be enclosed in
20715 quotation marks.
20716
20717 @cindex @option{-R} (@command{gnatcheck})
20718 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20719 Turn off the check for a specified rule with the specified parameter, if any.
20720
20721 @cindex @option{-from} (@command{gnatcheck})
20722 @item -from=@var{rule_option_filename}
20723 Read the rule options from the text file @var{rule_option_filename}, referred as
20724 ``rule file'' below.
20725
20726 @end table
20727
20728 @noindent
20729 The default behavior is that all the rule checks are disabled.
20730
20731 A rule file is a text file containing a set of rule options.
20732 @cindex Rule file (for @code{gnatcheck})
20733 The file may contain empty lines and Ada-style comments (comment
20734 lines and end-of-line comments). The rule file has free format; that is,
20735 you do not have to start a new rule option on a new line.
20736
20737 A rule file may contain other @option{-from=@var{rule_option_filename}}
20738 options, each such option being replaced with the content of the
20739 corresponding rule file during the rule files processing. In case a
20740 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20741 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20742 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20743 the processing of rule files is interrupted and a part of their content
20744 is ignored.
20745
20746
20747 @node Adding the Results of Compiler Checks to gnatcheck Output
20748 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20749
20750 @noindent
20751 The @command{gnatcheck} tool can include in the generated diagnostic messages
20752 and in
20753 the report file the results of the checks performed by the compiler. Though
20754 disabled by default, this effect may be obtained by using @option{+R} with
20755 the following rule identifiers and parameters:
20756
20757 @table @option
20758 @item Restrictions
20759 To record restrictions violations (that are performed by the compiler if the
20760 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20761 use the rule named
20762 @code{Restrictions} with the same parameters as pragma
20763 @code{Restrictions} or @code{Restriction_Warnings}.
20764
20765 @item Style_Checks
20766 To record compiler style checks(@pxref{Style Checking}), use the rule named
20767 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20768 which enables all the standard style checks that corresponds to @option{-gnatyy}
20769 GNAT style check option, or a string that has exactly the same
20770 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20771 @code{Style_Checks} (for further information about this pragma,
20772 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20773
20774 @item Warnings
20775 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20776 named @code{Warnings} with a parameter that is a valid
20777 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20778 (for further information about this pragma, @pxref{Pragma Warnings,,,
20779 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20780 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20781 all the specific warnings, but not suppresses the warning mode,
20782 and 'e' parameter, corresponding to @option{-gnatwe} that means
20783 "treat warnings as errors", does not have any effect.
20784
20785 @end table
20786
20787 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20788 option with the corresponding restriction name as a parameter. @code{-R} is
20789 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20790 warnings and style checks, use the corresponding warning and style options.
20791
20792 @node Project-Wide Checks
20793 @section Project-Wide Checks
20794 @cindex Project-wide checks (for @command{gnatcheck})
20795
20796 @noindent
20797 In order to perform checks on all units of a given project, you can use
20798 the GNAT driver along with the @option{-P} option:
20799 @smallexample
20800    gnat check -Pproj -rules -from=my_rules
20801 @end smallexample
20802
20803 @noindent
20804 If the project @code{proj} depends upon other projects, you can perform
20805 checks on the project closure using the @option{-U} option:
20806 @smallexample
20807    gnat check -Pproj -U -rules -from=my_rules
20808 @end smallexample
20809
20810 @noindent
20811 Finally, if not all the units are relevant to a particular main
20812 program in the project closure, you can perform checks for the set
20813 of units needed to create a given main program (unit closure) using
20814 the @option{-U} option followed by the name of the main unit:
20815 @smallexample
20816    gnat check -Pproj -U main -rules -from=my_rules
20817 @end smallexample
20818
20819
20820 @node Predefined Rules
20821 @section Predefined Rules
20822 @cindex Predefined rules (for @command{gnatcheck})
20823
20824 @ignore
20825 @c (Jan 2007) Since the global rules are still under development and are not
20826 @c documented, there is no point in explaining the difference between
20827 @c global and local rules
20828 @noindent
20829 A rule in @command{gnatcheck} is either local or global.
20830 A @emph{local rule} is a rule that applies to a well-defined section
20831 of a program and that can be checked by analyzing only this section.
20832 A @emph{global rule} requires analysis of some global properties of the
20833 whole program (mostly related to the program call graph).
20834 As of @value{NOW}, the implementation of global rules should be
20835 considered to be at a preliminary stage. You can use the
20836 @option{+GLOBAL} option to enable all the global rules, and the
20837 @option{-GLOBAL} rule option to disable all the global rules.
20838
20839 All the global rules in the list below are
20840 so indicated by marking them ``GLOBAL''.
20841 This +GLOBAL and -GLOBAL options are not
20842 included in the list of gnatcheck options above, because at the moment they
20843 are considered as a temporary debug options.
20844
20845 @command{gnatcheck} performs rule checks for generic
20846 instances only for global rules.  This limitation may be relaxed in a later
20847 release.
20848 @end ignore
20849
20850 @noindent
20851 The following subsections document the rules implemented in
20852 @command{gnatcheck}.
20853 The subsection title is the same as the rule identifier, which may be
20854 used as a parameter of the @option{+R} or @option{-R} options.
20855
20856
20857 @menu
20858 * Abstract_Type_Declarations::
20859 * Anonymous_Arrays::
20860 * Anonymous_Subtypes::
20861 * Blocks::
20862 * Boolean_Relational_Operators::
20863 @ignore
20864 * Ceiling_Violations::
20865 @end ignore
20866 * Controlled_Type_Declarations::
20867 * Declarations_In_Blocks::
20868 * Default_Parameters::
20869 * Discriminated_Records::
20870 * Enumeration_Ranges_In_CASE_Statements::
20871 * Exceptions_As_Control_Flow::
20872 * EXIT_Statements_With_No_Loop_Name::
20873 * Expanded_Loop_Exit_Names::
20874 * Explicit_Full_Discrete_Ranges::
20875 * Float_Equality_Checks::
20876 * Forbidden_Pragmas::
20877 * Function_Style_Procedures::
20878 * Generics_In_Subprograms::
20879 * GOTO_Statements::
20880 * Implicit_IN_Mode_Parameters::
20881 * Implicit_SMALL_For_Fixed_Point_Types::
20882 * Improperly_Located_Instantiations::
20883 * Improper_Returns::
20884 * Library_Level_Subprograms::
20885 * Local_Packages::
20886 @ignore
20887 * Improperly_Called_Protected_Entries::
20888 @end ignore
20889 * Metrics::
20890 * Misnamed_Identifiers::
20891 * Multiple_Entries_In_Protected_Definitions::
20892 * Name_Clashes::
20893 * Non_Qualified_Aggregates::
20894 * Non_Short_Circuit_Operators::
20895 * Non_SPARK_Attributes::
20896 * Non_Tagged_Derived_Types::
20897 * Non_Visible_Exceptions::
20898 * Numeric_Literals::
20899 * OTHERS_In_Aggregates::
20900 * OTHERS_In_CASE_Statements::
20901 * OTHERS_In_Exception_Handlers::
20902 * Outer_Loop_Exits::
20903 * Overloaded_Operators::
20904 * Overly_Nested_Control_Structures::
20905 * Parameters_Out_Of_Order::
20906 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20907 * Positional_Actuals_For_Defaulted_Parameters::
20908 * Positional_Components::
20909 * Positional_Generic_Parameters::
20910 * Positional_Parameters::
20911 * Predefined_Numeric_Types::
20912 * Raising_External_Exceptions::
20913 * Raising_Predefined_Exceptions::
20914 * Separate_Numeric_Error_Handlers::
20915 @ignore
20916 * Recursion::
20917 * Side_Effect_Functions::
20918 @end ignore
20919 * Slices::
20920 * Unassigned_OUT_Parameters::
20921 * Uncommented_BEGIN_In_Package_Bodies::
20922 * Unconstrained_Array_Returns::
20923 * Universal_Ranges::
20924 * Unnamed_Blocks_And_Loops::
20925 @ignore
20926 * Unused_Subprograms::
20927 @end ignore
20928 * USE_PACKAGE_Clauses::
20929 * Volatile_Objects_Without_Address_Clauses::
20930 @end menu
20931
20932
20933 @node Abstract_Type_Declarations
20934 @subsection @code{Abstract_Type_Declarations}
20935 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20936
20937 @noindent
20938 Flag all declarations of abstract types. For an abstract private
20939 type, both the private and full type declarations are flagged.
20940
20941 This rule has no parameters.
20942
20943
20944 @node Anonymous_Arrays
20945 @subsection @code{Anonymous_Arrays}
20946 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20947
20948 @noindent
20949 Flag all anonymous array type definitions (by Ada semantics these can only
20950 occur in object declarations).
20951
20952 This rule has no parameters.
20953
20954 @node Anonymous_Subtypes
20955 @subsection @code{Anonymous_Subtypes}
20956 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20957
20958 @noindent
20959 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20960 any instance of a subtype indication with a constraint, other than one
20961 that occurs immediately within a subtype declaration. Any use of a range
20962 other than as a constraint used immediately within a subtype declaration
20963 is considered as an anonymous subtype.
20964
20965 An effect of this rule is that @code{for} loops such as the following are
20966 flagged (since @code{1..N} is formally a ``range''):
20967
20968 @smallexample @c ada
20969 for I in 1 .. N loop
20970    @dots{}
20971 end loop;
20972 @end smallexample
20973
20974 @noindent
20975 Declaring an explicit subtype solves the problem:
20976
20977 @smallexample @c ada
20978 subtype S is Integer range 1..N;
20979 @dots{}
20980 for I in S loop
20981    @dots{}
20982 end loop;
20983 @end smallexample
20984
20985 @noindent
20986 This rule has no parameters.
20987
20988 @node Blocks
20989 @subsection @code{Blocks}
20990 @cindex @code{Blocks} rule (for @command{gnatcheck})
20991
20992 @noindent
20993 Flag each block statement.
20994
20995 This rule has no parameters.
20996
20997 @node Boolean_Relational_Operators
20998 @subsection @code{Boolean_Relational_Operators}
20999 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21000
21001 @noindent
21002 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21003 ``>='', ``='' and ``/='') for the predefined Boolean type.
21004 (This rule is useful in enforcing the SPARK language restrictions.)
21005
21006 Calls to predefined relational operators of any type derived from
21007 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21008 with these designators, and uses of operators that are renamings
21009 of the predefined relational operators for @code{Standard.Boolean},
21010 are likewise not detected.
21011
21012 This rule has no parameters.
21013
21014 @ignore
21015 @node Ceiling_Violations
21016 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
21017 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21018
21019 @noindent
21020 Flag invocations of a protected operation by a task whose priority exceeds
21021 the protected object's ceiling.
21022
21023 As of @value{NOW}, this rule has the following limitations:
21024
21025 @itemize @bullet
21026
21027 @item
21028  We consider only pragmas Priority and Interrupt_Priority as means to define
21029   a task/protected operation priority. We do not consider the effect of using
21030   Ada.Dynamic_Priorities.Set_Priority procedure;
21031
21032 @item
21033  We consider only base task priorities, and no priority inheritance. That is,
21034   we do not make a difference between calls issued during task activation and
21035   execution of the sequence of statements from task body;
21036
21037 @item
21038  Any situation when the priority of protected operation caller is set by a
21039   dynamic expression (that is, the corresponding Priority or
21040   Interrupt_Priority pragma has a non-static expression as an argument) we
21041   treat as a priority inconsistency (and, therefore, detect this situation).
21042 @end itemize
21043
21044 @noindent
21045 At the moment the notion of the main subprogram is not implemented in
21046 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21047 if this subprogram can be a main subprogram of a partition) changes the
21048 priority of an environment task. So if we have more then one such pragma in
21049 the set of processed sources, the pragma that is processed last, defines the
21050 priority of an environment task.
21051
21052 This rule has no parameters.
21053 @end ignore
21054
21055 @node Controlled_Type_Declarations
21056 @subsection @code{Controlled_Type_Declarations}
21057 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21058
21059 @noindent
21060 Flag all declarations of controlled types. A declaration of a private type
21061 is flagged if its full declaration declares a controlled type. A declaration
21062 of a derived type is flagged if its ancestor type is controlled. Subtype
21063 declarations are not checked. A declaration of a type that itself is not a
21064 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21065 component is not checked.
21066
21067 This rule has no parameters.
21068
21069
21070
21071 @node Declarations_In_Blocks
21072 @subsection @code{Declarations_In_Blocks}
21073 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21074
21075 @noindent
21076 Flag all block statements containing local declarations. A @code{declare}
21077 block with an empty @i{declarative_part} or with a @i{declarative part}
21078 containing only pragmas and/or @code{use} clauses is not flagged.
21079
21080 This rule has no parameters.
21081
21082
21083 @node Default_Parameters
21084 @subsection @code{Default_Parameters}
21085 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21086
21087 @noindent
21088 Flag all default expressions for subprogram parameters. Parameter
21089 declarations of formal and generic subprograms are also checked.
21090
21091 This rule has no parameters.
21092
21093
21094 @node Discriminated_Records
21095 @subsection @code{Discriminated_Records}
21096 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21097
21098 @noindent
21099 Flag all declarations of record types with discriminants. Only the
21100 declarations of record and record extension types are checked. Incomplete,
21101 formal, private, derived and private extension type declarations are not
21102 checked. Task and protected type declarations also are not checked.
21103
21104 This rule has no parameters.
21105
21106
21107 @node Enumeration_Ranges_In_CASE_Statements
21108 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21109 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21110
21111 @noindent
21112 Flag each use of a range of enumeration literals as a choice in a
21113 @code{case} statement.
21114 All forms for specifying a range (explicit ranges
21115 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21116 An enumeration range is
21117 flagged even if contains exactly one enumeration value or no values at all. A
21118 type derived from an enumeration type is considered as an enumeration type.
21119
21120 This rule helps prevent maintenance problems arising from adding an
21121 enumeration value to a type and having it implicitly handled by an existing
21122 @code{case} statement with an enumeration range that includes the new literal.
21123
21124 This rule has no parameters.
21125
21126
21127 @node Exceptions_As_Control_Flow
21128 @subsection @code{Exceptions_As_Control_Flow}
21129 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21130
21131 @noindent
21132 Flag each place where an exception is explicitly raised and handled in the
21133 same subprogram body. A @code{raise} statement in an exception handler,
21134 package body, task body or entry body is not flagged.
21135
21136 The rule has no parameters.
21137
21138 @node EXIT_Statements_With_No_Loop_Name
21139 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21140 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21141
21142 @noindent
21143 Flag each @code{exit} statement that does not specify the name of the loop
21144 being exited.
21145
21146 The rule has no parameters.
21147
21148
21149 @node Expanded_Loop_Exit_Names
21150 @subsection @code{Expanded_Loop_Exit_Names}
21151 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21152
21153 @noindent
21154 Flag all expanded loop names in @code{exit} statements.
21155
21156 This rule has no parameters.
21157
21158 @node Explicit_Full_Discrete_Ranges
21159 @subsection @code{Explicit_Full_Discrete_Ranges}
21160 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21161
21162 @noindent
21163 Flag each discrete range that has the form @code{A'First .. A'Last}.
21164
21165 This rule has no parameters.
21166
21167 @node Float_Equality_Checks
21168 @subsection @code{Float_Equality_Checks}
21169 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21170
21171 @noindent
21172 Flag all calls to the predefined equality operations for floating-point types.
21173 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21174 User-defined equality operations are not flagged, nor are ``@code{=}''
21175 and ``@code{/=}'' operations for fixed-point types.
21176
21177 This rule has no parameters.
21178
21179
21180 @node Forbidden_Pragmas
21181 @subsection @code{Forbidden_Pragmas}
21182 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21183
21184 @noindent
21185 Flag each use of the specified pragmas.  The pragmas to be detected
21186 are named in the rule's  parameters.
21187
21188 This rule has the following parameters:
21189
21190 @itemize @bullet
21191 @item For the @option{+R} option
21192
21193 @table @asis
21194 @item @emph{Pragma_Name}
21195 Adds the specified pragma to the set of pragmas to be
21196 checked and sets the checks for all the specified pragmas
21197 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21198 does not correspond to any pragma name defined in the Ada
21199 standard or to the name of a GNAT-specific pragma defined
21200 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21201 Manual}, it is treated as the name of unknown pragma.
21202
21203 @item @code{GNAT}
21204 All the GNAT-specific pragmas are detected; this sets
21205 the checks for all the specified pragmas ON.
21206
21207 @item @code{ALL}
21208 All pragmas are detected; this sets the rule ON.
21209 @end table
21210
21211 @item For the @option{-R} option
21212 @table @asis
21213 @item @emph{Pragma_Name}
21214 Removes the specified pragma from the set of pragmas to be
21215 checked without affecting checks for
21216 other pragmas. @emph{Pragma_Name} is treated as a name
21217 of a pragma. If it does not correspond to any pragma
21218 defined in the Ada standard or to any name defined in
21219 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21220 this option is treated as turning OFF detection of all unknown pragmas.
21221
21222 @item GNAT
21223 Turn OFF detection of all GNAT-specific pragmas
21224
21225 @item ALL
21226 Clear the list of the pragmas to be detected and
21227 turn the rule OFF.
21228 @end table
21229 @end itemize
21230
21231 @noindent
21232 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21233 the syntax of an Ada identifier and therefore can not be considered
21234 as a pragma name, a diagnostic message is generated and the corresponding
21235 parameter is ignored.
21236
21237 When more then one parameter is given in the same rule option, the parameters
21238 must be separated by a comma.
21239
21240 If more then one option for this rule is specified for the @command{gnatcheck}
21241 call, a new option overrides the previous one(s).
21242
21243 The @option{+R} option with no parameters turns the rule ON with the set of
21244 pragmas to be detected defined by the previous rule options.
21245 (By default this set is empty, so if the only option specified for the rule is
21246 @option{+RForbidden_Pragmas} (with
21247 no parameter), then the rule is enabled, but it does not detect anything).
21248 The @option{-R} option with no parameter turns the rule OFF, but it does not
21249 affect the set of pragmas to be detected.
21250
21251
21252
21253
21254 @node Function_Style_Procedures
21255 @subsection @code{Function_Style_Procedures}
21256 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21257
21258 @noindent
21259 Flag each procedure that can be rewritten as a function. A procedure can be
21260 converted into a function if it has exactly one parameter of mode @code{out}
21261 and no parameters of mode @code{in out}. Procedure declarations,
21262 formal procedure declarations, and generic procedure declarations are always
21263 checked. Procedure
21264 bodies and body stubs are flagged only if they do not have corresponding
21265 separate declarations. Procedure renamings and procedure instantiations are
21266 not flagged.
21267
21268 If a procedure can be rewritten as a function, but its @code{out} parameter is
21269 of a limited type, it is not flagged.
21270
21271 Protected procedures are not flagged. Null procedures also are not flagged.
21272
21273 This rule has no parameters.
21274
21275
21276 @node Generics_In_Subprograms
21277 @subsection @code{Generics_In_Subprograms}
21278 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21279
21280 @noindent
21281 Flag each declaration of a generic unit in a subprogram. Generic
21282 declarations in the bodies of generic subprograms are also flagged.
21283 A generic unit nested in another generic unit is not flagged.
21284 If a generic unit is
21285 declared in a local package that is declared in a subprogram body, the
21286 generic unit is flagged.
21287
21288 This rule has no parameters.
21289
21290
21291 @node GOTO_Statements
21292 @subsection @code{GOTO_Statements}
21293 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21294
21295 @noindent
21296 Flag each occurrence of a @code{goto} statement.
21297
21298 This rule has no parameters.
21299
21300
21301 @node Implicit_IN_Mode_Parameters
21302 @subsection @code{Implicit_IN_Mode_Parameters}
21303 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21304
21305 @noindent
21306 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21307 Note that @code{access} parameters, although they technically behave
21308 like @code{in} parameters, are not flagged.
21309
21310 This rule has no parameters.
21311
21312
21313 @node Implicit_SMALL_For_Fixed_Point_Types
21314 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21315 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21316
21317 @noindent
21318 Flag each fixed point type declaration that lacks an explicit
21319 representation  clause to define its @code{'Small} value.
21320 Since @code{'Small} can be  defined only for ordinary fixed point types,
21321 decimal fixed point type declarations are not checked.
21322
21323 This rule has no parameters.
21324
21325
21326 @node Improperly_Located_Instantiations
21327 @subsection @code{Improperly_Located_Instantiations}
21328 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21329
21330 @noindent
21331 Flag all generic instantiations in library-level package specs
21332 (including library generic packages) and in all subprogram bodies.
21333
21334 Instantiations in task and entry bodies are not flagged. Instantiations in the
21335 bodies of protected subprograms are flagged.
21336
21337 This rule has no parameters.
21338
21339
21340
21341 @node Improper_Returns
21342 @subsection @code{Improper_Returns}
21343 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21344
21345 @noindent
21346 Flag each explicit @code{return} statement in procedures, and
21347 multiple @code{return} statements in functions.
21348 Diagnostic messages are generated for all @code{return} statements
21349 in a procedure (thus each procedure must be written so that it
21350 returns implicitly at the end of its statement part),
21351 and for all @code{return} statements in a function after the first one.
21352 This rule supports the stylistic convention that each subprogram
21353 should have no more than one point of normal return.
21354
21355 This rule has no parameters.
21356
21357
21358 @node Library_Level_Subprograms
21359 @subsection @code{Library_Level_Subprograms}
21360 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21361
21362 @noindent
21363 Flag all library-level subprograms (including generic subprogram instantiations).
21364
21365 This rule has no parameters.
21366
21367
21368 @node Local_Packages
21369 @subsection @code{Local_Packages}
21370 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21371
21372 @noindent
21373 Flag all local packages declared in package and generic package
21374 specs.
21375 Local packages in bodies are not flagged.
21376
21377 This rule has no parameters.
21378
21379 @ignore
21380 @node Improperly_Called_Protected_Entries
21381 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21382 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21383
21384 @noindent
21385 Flag each protected entry that can be called from more than one task.
21386
21387 This rule has no parameters.
21388 @end ignore
21389
21390 @node Metrics
21391 @subsection @code{Metrics}
21392 @cindex @code{Metrics} rule (for @command{gnatcheck})
21393
21394 @noindent
21395 There is a set of checks based on computing a metric value and comparing the
21396 result with the specified upper (or lower, depending on a specific metric)
21397 value specified for a given metric. A construct is flagged if a given metric
21398 is applicable (can be computed) for it and the computed value is greater
21399 then (lover then) the specified upper (lower) bound.
21400
21401 The name of any metric-based rule consists of the prefix @code{Metrics_}
21402 followed by the name of the corresponding metric (see the table below).
21403 For @option{+R} option, each metric-based rule has a numeric parameter
21404 specifying the bound (integer or real, depending on a metric), @option{-R}
21405 option for metric rules does not have a parameter.
21406
21407 The following table shows the metric names for that the corresponding
21408 metrics-based checks are supported by gnatcheck, including the
21409 constraint that must be satisfied by the bound that is specified for the check
21410 and what bound - upper (U) or lower (L) - should be specified.
21411
21412 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21413 @ifnothtml
21414 @headitem Check Name @tab Description @tab Bounds Value
21415 @end ifnothtml
21416 @ifhtml
21417 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21418 @end ifhtml
21419 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21420 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21421 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21422 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21423 @end multitable
21424
21425 @noindent
21426 The meaning and the computed values for all these metrics are exactly
21427 the same as for the corresponding metrics in @command{gnatmetric}.
21428
21429 @emph{Example:} the rule
21430 @smallexample
21431 +RMetrics_Cyclomatic_Complexity : 7
21432 @end smallexample
21433 @noindent
21434 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21435
21436 To turn OFF the check for cyclomatic complexity metric, use the following option:
21437 @smallexample
21438 -RMetrics_Cyclomatic_Complexity
21439 @end smallexample
21440
21441 @node Misnamed_Identifiers
21442 @subsection @code{Misnamed_Identifiers}
21443 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21444
21445 @noindent
21446 Flag the declaration of each identifier that does not have a suffix
21447 corresponding to the kind of entity being declared.
21448 The following declarations are checked:
21449
21450 @itemize @bullet
21451 @item
21452 type declarations
21453
21454 @item
21455 constant declarations (but not number declarations)
21456
21457 @item
21458 package renaming declarations (but not generic package renaming
21459 declarations)
21460 @end itemize
21461
21462 @noindent
21463 This rule may have parameters. When used without parameters, the rule enforces
21464 the following checks:
21465
21466 @itemize @bullet
21467 @item
21468 type-defining names end with @code{_T}, unless the type is an access type,
21469 in which case the suffix must be @code{_A}
21470 @item
21471 constant names end with @code{_C}
21472 @item
21473 names defining package renamings end with @code{_R}
21474 @end itemize
21475
21476 @noindent
21477 For a private or incomplete type declaration the following checks are
21478 made for the defining name suffix:
21479
21480 @itemize @bullet
21481 @item
21482 For an incomplete type declaration: if the corresponding full type
21483 declaration is available, the defining identifier from the full type
21484 declaration is checked, but the defining identifier from the incomplete type
21485 declaration is not; otherwise the defining identifier from the incomplete
21486 type declaration is checked against the suffix specified for type
21487 declarations.
21488
21489 @item
21490 For a private type declaration (including private extensions),  the defining
21491 identifier from the private type declaration is checked against the type
21492 suffix (even if the corresponding full declaration is an access type
21493 declaration), and the defining identifier from the corresponding full type
21494 declaration is not checked.
21495 @end itemize
21496
21497 @noindent
21498 For a deferred constant, the defining name in the corresponding full constant
21499 declaration is not checked.
21500
21501 Defining names of formal types are not checked.
21502
21503 The rule may have the following parameters:
21504
21505 @itemize @bullet
21506 @item
21507 For the @option{+R} option:
21508 @table @code
21509 @item Default
21510 Sets the default listed above for all the names to be checked.
21511
21512 @item Type_Suffix=@emph{string}
21513 Specifies the suffix for a type name.
21514
21515 @item Access_Suffix=@emph{string}
21516 Specifies the suffix for an access type name. If
21517 this parameter is set, it overrides for access
21518 types the suffix set by the @code{Type_Suffix} parameter.
21519
21520 @item Constant_Suffix=@emph{string}
21521 Specifies the suffix for a constant name.
21522
21523 @item Renaming_Suffix=@emph{string}
21524 Specifies the suffix for a package renaming name.
21525 @end table
21526
21527 @item
21528 For the @option{-R} option:
21529 @table @code
21530 @item All_Suffixes
21531 Remove all the suffixes specified for the
21532 identifier suffix checks, whether by default or
21533 as specified by other rule parameters. All the
21534 checks for this rule are disabled as a result.
21535
21536 @item Type_Suffix
21537 Removes the suffix specified for types. This
21538 disables checks for types but does not disable
21539 any other checks for this rule (including the
21540 check for access type names if @code{Access_Suffix} is
21541 set).
21542
21543 @item Access_Suffix
21544 Removes the suffix specified for access types.
21545 This disables checks for access type names but
21546 does not disable any other checks for this rule.
21547 If @code{Type_Suffix} is set, access type names are
21548 checked as ordinary type names.
21549
21550 @item Constant_Suffix
21551 Removes the suffix specified for constants. This
21552 disables checks for constant names but does not
21553 disable any other checks for this rule.
21554
21555 @item Renaming_Suffix
21556 Removes the suffix specified for package
21557 renamings. This disables checks for package
21558 renamings but does not disable any other checks
21559 for this rule.
21560 @end table
21561 @end itemize
21562
21563 @noindent
21564 If more than one parameter is used, parameters must be separated by commas.
21565
21566 If more than one  option is specified for the @command{gnatcheck} invocation,
21567 a new option overrides the previous one(s).
21568
21569 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21570 checks for all the
21571 name suffixes specified by previous options used for this rule.
21572
21573 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21574 all the checks but keeps
21575 all the suffixes specified by previous options used for this rule.
21576
21577 The @emph{string} value must be a valid suffix for an Ada identifier (after
21578 trimming all the leading and trailing space characters, if any).
21579 Parameters are not case sensitive, except the @emph{string} part.
21580
21581 If any error is detected in a rule parameter, the parameter is ignored.
21582 In such a case the options that are set for the rule are not
21583 specified.
21584
21585
21586
21587 @node Multiple_Entries_In_Protected_Definitions
21588 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21589 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21590
21591 @noindent
21592 Flag each protected definition (i.e., each protected object/type declaration)
21593 that defines more than one entry.
21594 Diagnostic messages are generated for all the entry declarations
21595 except the first one. An entry family is counted as one entry. Entries from
21596 the private part of the protected definition are also checked.
21597
21598 This rule has no parameters.
21599
21600 @node Name_Clashes
21601 @subsection @code{Name_Clashes}
21602 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21603
21604 @noindent
21605 Check that certain names are not used as defining identifiers. To activate
21606 this rule, you need to supply a reference to the dictionary file(s) as a rule
21607 parameter(s) (more then one dictionary file can be specified). If no
21608 dictionary file is set, this rule will not cause anything to be flagged.
21609 Only defining occurrences, not references, are checked.
21610 The check is not case-sensitive.
21611
21612 This rule is enabled by default, but without setting any corresponding
21613 dictionary file(s); thus the default effect is to do no checks.
21614
21615 A dictionary file is a plain text file. The maximum line length for this file
21616 is 1024 characters.  If the line is longer then this limit, extra characters
21617 are ignored.
21618
21619 Each line can be either an empty line, a comment line, or a line containing
21620 a list of identifiers separated by space or HT characters.
21621 A comment is an Ada-style comment (from @code{--} to end-of-line).
21622 Identifiers must follow the Ada syntax for identifiers.
21623 A line containing one or more identifiers may end with a comment.
21624
21625 @node Non_Qualified_Aggregates
21626 @subsection @code{Non_Qualified_Aggregates}
21627 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21628
21629 @noindent
21630 Flag each non-qualified aggregate.
21631 A non-qualified aggregate is an
21632 aggregate that is not the expression of a qualified expression. A
21633 string literal is not considered an aggregate, but an array
21634 aggregate of a string type is considered as a normal aggregate.
21635 Aggregates of anonymous array types are not flagged.
21636
21637 This rule has no parameters.
21638
21639
21640 @node Non_Short_Circuit_Operators
21641 @subsection @code{Non_Short_Circuit_Operators}
21642 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21643
21644 @noindent
21645 Flag all calls to predefined @code{and} and @code{or} operators for
21646 any boolean type. Calls to
21647 user-defined @code{and} and @code{or} and to operators defined by renaming
21648 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21649 operators for modular types or boolean array types are not flagged.
21650
21651 This rule has no parameters.
21652
21653
21654
21655 @node Non_SPARK_Attributes
21656 @subsection @code{Non_SPARK_Attributes}
21657 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21658
21659 @noindent
21660 The SPARK language defines the following subset of Ada 95 attribute
21661 designators as those that can be used in SPARK programs. The use of
21662 any other attribute is flagged.
21663
21664 @itemize @bullet
21665 @item @code{'Adjacent}
21666 @item @code{'Aft}
21667 @item @code{'Base}
21668 @item @code{'Ceiling}
21669 @item @code{'Component_Size}
21670 @item @code{'Compose}
21671 @item @code{'Copy_Sign}
21672 @item @code{'Delta}
21673 @item @code{'Denorm}
21674 @item @code{'Digits}
21675 @item @code{'Exponent}
21676 @item @code{'First}
21677 @item @code{'Floor}
21678 @item @code{'Fore}
21679 @item @code{'Fraction}
21680 @item @code{'Last}
21681 @item @code{'Leading_Part}
21682 @item @code{'Length}
21683 @item @code{'Machine}
21684 @item @code{'Machine_Emax}
21685 @item @code{'Machine_Emin}
21686 @item @code{'Machine_Mantissa}
21687 @item @code{'Machine_Overflows}
21688 @item @code{'Machine_Radix}
21689 @item @code{'Machine_Rounds}
21690 @item @code{'Max}
21691 @item @code{'Min}
21692 @item @code{'Model}
21693 @item @code{'Model_Emin}
21694 @item @code{'Model_Epsilon}
21695 @item @code{'Model_Mantissa}
21696 @item @code{'Model_Small}
21697 @item @code{'Modulus}
21698 @item @code{'Pos}
21699 @item @code{'Pred}
21700 @item @code{'Range}
21701 @item @code{'Remainder}
21702 @item @code{'Rounding}
21703 @item @code{'Safe_First}
21704 @item @code{'Safe_Last}
21705 @item @code{'Scaling}
21706 @item @code{'Signed_Zeros}
21707 @item @code{'Size}
21708 @item @code{'Small}
21709 @item @code{'Succ}
21710 @item @code{'Truncation}
21711 @item @code{'Unbiased_Rounding}
21712 @item @code{'Val}
21713 @item @code{'Valid}
21714 @end itemize
21715
21716 @noindent
21717 This rule has no parameters.
21718
21719
21720 @node Non_Tagged_Derived_Types
21721 @subsection @code{Non_Tagged_Derived_Types}
21722 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21723
21724 @noindent
21725 Flag all derived type declarations that do not have a record extension part.
21726
21727 This rule has no parameters.
21728
21729
21730
21731 @node Non_Visible_Exceptions
21732 @subsection @code{Non_Visible_Exceptions}
21733 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21734
21735 @noindent
21736 Flag constructs leading to the possibility of propagating an exception
21737 out of the scope in which the exception is declared.
21738 Two cases are detected:
21739
21740 @itemize @bullet
21741 @item
21742 An exception declaration in a subprogram body, task body or block
21743 statement is flagged if the body or statement does not contain a handler for
21744 that exception or a handler with an @code{others} choice.
21745
21746 @item
21747 A @code{raise} statement in an exception handler of a subprogram body,
21748 task body or block statement is flagged if it (re)raises a locally
21749 declared exception.  This may occur under the following circumstances:
21750 @itemize @minus
21751 @item
21752 it explicitly raises a locally declared exception, or
21753 @item
21754 it does not specify an exception name (i.e., it is simply @code{raise;})
21755 and the enclosing handler contains a locally declared exception in its
21756 exception choices.
21757 @end itemize
21758 @end itemize
21759
21760 @noindent
21761 Renamings of local exceptions are not flagged.
21762
21763 This rule has no parameters.
21764
21765
21766 @node Numeric_Literals
21767 @subsection @code{Numeric_Literals}
21768 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21769
21770 @noindent
21771 Flag each use of a numeric literal in an index expression, and in any
21772 circumstance except for the following:
21773
21774 @itemize @bullet
21775 @item
21776 a literal occurring in the initialization expression for a constant
21777 declaration or a named number declaration, or
21778
21779 @item
21780 an integer literal that is less than or equal to a value
21781 specified by the @option{N} rule parameter.
21782 @end itemize
21783
21784 @noindent
21785 This rule may have the following parameters for the @option{+R} option:
21786
21787 @table @asis
21788 @item @emph{N}
21789 @emph{N} is an integer literal used as the maximal value that is not flagged
21790 (i.e., integer literals not exceeding this value are allowed)
21791
21792 @item @code{ALL}
21793 All integer literals are flagged
21794 @end table
21795
21796 @noindent
21797 If no parameters are set, the maximum unflagged value is 1.
21798
21799 The last specified check limit (or the fact that there is no limit at
21800 all) is used when multiple @option{+R} options appear.
21801
21802 The @option{-R} option for this rule has no parameters.
21803 It disables the rule but retains the last specified maximum unflagged value.
21804 If the @option{+R} option subsequently appears, this value is used as the
21805 threshold for the check.
21806
21807
21808 @node OTHERS_In_Aggregates
21809 @subsection @code{OTHERS_In_Aggregates}
21810 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21811
21812 @noindent
21813 Flag each use of an @code{others} choice in extension aggregates.
21814 In record and array aggregates, an @code{others} choice is flagged unless
21815 it is used to refer to all components, or to all but one component.
21816
21817 If, in case of a named array aggregate, there are two associations, one
21818 with an @code{others} choice and another with a discrete range, the
21819 @code{others} choice is flagged even if the discrete range specifies
21820 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21821
21822 This rule has no parameters.
21823
21824 @node OTHERS_In_CASE_Statements
21825 @subsection @code{OTHERS_In_CASE_Statements}
21826 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21827
21828 @noindent
21829 Flag any use of an @code{others} choice in a @code{case} statement.
21830
21831 This rule has no parameters.
21832
21833 @node OTHERS_In_Exception_Handlers
21834 @subsection @code{OTHERS_In_Exception_Handlers}
21835 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21836
21837 @noindent
21838 Flag any use of an @code{others} choice in an exception handler.
21839
21840 This rule has no parameters.
21841
21842
21843 @node Outer_Loop_Exits
21844 @subsection @code{Outer_Loop_Exits}
21845 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21846
21847 @noindent
21848 Flag each @code{exit} statement containing a loop name that is not the name
21849 of the immediately enclosing @code{loop} statement.
21850
21851 This rule has no parameters.
21852
21853
21854 @node Overloaded_Operators
21855 @subsection @code{Overloaded_Operators}
21856 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21857
21858 @noindent
21859 Flag each function declaration that overloads an operator symbol.
21860 A function body is checked only if the body does not have a
21861 separate spec. Formal functions are also checked. For a
21862 renaming declaration, only renaming-as-declaration is checked
21863
21864 This rule has no parameters.
21865
21866
21867 @node Overly_Nested_Control_Structures
21868 @subsection @code{Overly_Nested_Control_Structures}
21869 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21870
21871 @noindent
21872 Flag each control structure whose nesting level exceeds the value provided
21873 in the rule parameter.
21874
21875 The control structures checked are the following:
21876
21877 @itemize @bullet
21878 @item    @code{if} statement
21879 @item    @code{case} statement
21880 @item    @code{loop} statement
21881 @item    Selective accept statement
21882 @item    Timed entry call statement
21883 @item    Conditional entry call
21884 @item    Asynchronous select statement
21885 @end itemize
21886
21887 @noindent
21888 The rule has the following parameter for the @option{+R} option:
21889
21890 @table @emph
21891 @item N
21892 Positive integer specifying the maximal control structure nesting
21893 level that is not flagged
21894 @end table
21895
21896 @noindent
21897 If the parameter for the @option{+R} option is not specified or
21898 if it is not a positive integer, @option{+R} option is ignored.
21899
21900 If more then one  option is specified for the gnatcheck call, the later option and
21901 new parameter override the previous one(s).
21902
21903
21904 @node Parameters_Out_Of_Order
21905 @subsection @code{Parameters_Out_Of_Order}
21906 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21907
21908 @noindent
21909 Flag each subprogram and entry declaration whose formal parameters are not
21910 ordered according to the following scheme:
21911
21912 @itemize @bullet
21913
21914 @item @code{in} and @code{access} parameters first,
21915 then @code{in out} parameters,
21916 and then @code{out} parameters;
21917
21918 @item for @code{in} mode, parameters with default initialization expressions
21919 occur last
21920 @end itemize
21921
21922 @noindent
21923 Only the first violation of the described order is flagged.
21924
21925 The following constructs are checked:
21926
21927 @itemize @bullet
21928 @item   subprogram declarations (including null procedures);
21929 @item   generic subprogram declarations;
21930 @item   formal subprogram declarations;
21931 @item   entry declarations;
21932 @item   subprogram bodies and subprogram body stubs that do not
21933 have separate specifications
21934 @end itemize
21935
21936 @noindent
21937 Subprogram renamings are not checked.
21938
21939 This rule has no parameters.
21940
21941
21942 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21943 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21944 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21945
21946 @noindent
21947 Flag each generic actual parameter corresponding to a generic formal
21948 parameter with a default initialization, if positional notation is used.
21949
21950 This rule has no parameters.
21951
21952 @node Positional_Actuals_For_Defaulted_Parameters
21953 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21954 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21955
21956 @noindent
21957 Flag each actual parameter to a subprogram or entry call where the
21958 corresponding formal parameter has a default expression, if positional
21959 notation is used.
21960
21961 This rule has no parameters.
21962
21963 @node Positional_Components
21964 @subsection @code{Positional_Components}
21965 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21966
21967 @noindent
21968 Flag each array, record and extension aggregate that includes positional
21969 notation.
21970
21971 This rule has no parameters.
21972
21973
21974 @node Positional_Generic_Parameters
21975 @subsection @code{Positional_Generic_Parameters}
21976 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21977
21978 @noindent
21979 Flag each instantiation using positional parameter notation.
21980
21981 This rule has no parameters.
21982
21983
21984 @node Positional_Parameters
21985 @subsection @code{Positional_Parameters}
21986 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21987
21988 @noindent
21989 Flag each subprogram or entry call using positional parameter notation,
21990 except for the following:
21991
21992 @itemize @bullet
21993 @item
21994 Invocations of prefix or infix operators are not flagged
21995 @item
21996 If the called subprogram or entry has only one formal parameter,
21997 the call is not flagged;
21998 @item
21999 If a subprogram call uses the @emph{Object.Operation} notation, then
22000 @itemize @minus
22001 @item
22002 the first parameter (that is, @emph{Object}) is not flagged;
22003 @item
22004 if the called subprogram has only two parameters, the second parameter
22005 of the call is not flagged;
22006 @end itemize
22007 @end itemize
22008
22009 @noindent
22010 This rule has no parameters.
22011
22012
22013
22014
22015 @node Predefined_Numeric_Types
22016 @subsection @code{Predefined_Numeric_Types}
22017 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22018
22019 @noindent
22020 Flag each explicit use of the name of any numeric type or subtype defined
22021 in package @code{Standard}.
22022
22023 The rationale for this rule is to detect when the
22024 program may depend on platform-specific characteristics of the implementation
22025 of the predefined numeric types. Note that this rule is over-pessimistic;
22026 for example, a program that uses @code{String} indexing
22027 likely needs a variable of type @code{Integer}.
22028 Another example is the flagging of predefined numeric types with explicit
22029 constraints:
22030
22031 @smallexample @c ada
22032     subtype My_Integer is Integer range Left .. Right;
22033     Vy_Var : My_Integer;
22034 @end smallexample
22035
22036 @noindent
22037 This rule detects only numeric types and subtypes defined in
22038 @code{Standard}. The use of numeric types and subtypes defined in other
22039 predefined packages (such as @code{System.Any_Priority} or
22040 @code{Ada.Text_IO.Count}) is not flagged
22041
22042 This rule has no parameters.
22043
22044
22045
22046 @node Raising_External_Exceptions
22047 @subsection @code{Raising_External_Exceptions}
22048 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22049
22050 @noindent
22051 Flag any @code{raise} statement, in a program unit declared in a library
22052 package or in a generic library package, for an exception that is
22053 neither a predefined exception nor an exception that is also declared (or
22054 renamed) in the visible part of the package.
22055
22056 This rule has no parameters.
22057
22058
22059
22060 @node Raising_Predefined_Exceptions
22061 @subsection @code{Raising_Predefined_Exceptions}
22062 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22063
22064 @noindent
22065 Flag each @code{raise} statement that raises a predefined exception
22066 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22067 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22068
22069 This rule has no parameters.
22070
22071 @node Separate_Numeric_Error_Handlers
22072 @subsection @code{Separate_Numeric_Error_Handlers}
22073 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22074
22075 @noindent
22076 Flags each exception handler that contains a choice for
22077 the predefined @code{Constraint_Error} exception, but does not contain
22078 the choice for the predefined @code{Numeric_Error} exception, or
22079 that contains the choice for @code{Numeric_Error}, but does not contain the
22080 choice for @code{Constraint_Error}.
22081
22082 This rule has no parameters.
22083
22084 @ignore
22085 @node Recursion
22086 @subsection @code{Recursion} (under construction, GLOBAL)
22087 @cindex @code{Recursion} rule (for @command{gnatcheck})
22088
22089 @noindent
22090 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22091 calls, of recursive subprograms are detected.
22092
22093 This rule has no parameters.
22094 @end ignore
22095
22096 @ignore
22097 @node Side_Effect_Functions
22098 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22099 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22100
22101 @noindent
22102 Flag functions with side effects.
22103
22104 We define a side effect as changing any data object that is not local for the
22105 body of this function.
22106
22107 At the moment, we do NOT consider a side effect any input-output operations
22108 (changing a state or a content of any file).
22109
22110 We do not consider protected functions for this rule (???)
22111
22112 There are the following sources of side effect:
22113
22114 @enumerate
22115 @item Explicit (or direct) side-effect:
22116
22117 @itemize @bullet
22118 @item
22119 direct assignment to a non-local variable;
22120
22121 @item
22122 direct call to an entity that is known to change some data object that is
22123      not local for the body of this function (Note, that if F1 calls F2 and F2
22124      does have a side effect, this does not automatically mean that F1 also
22125      have a side effect, because it may be the case that F2 is declared in
22126      F1's body and it changes some data object that is global for F2, but
22127      local for F1);
22128 @end itemize
22129
22130 @item Indirect side-effect:
22131 @itemize @bullet
22132 @item
22133 Subprogram calls implicitly issued by:
22134 @itemize @bullet
22135 @item
22136 computing initialization expressions from type declarations as a part
22137          of object elaboration or allocator evaluation;
22138 @item
22139 computing implicit parameters of subprogram or entry calls or generic
22140          instantiations;
22141 @end itemize
22142
22143 @item
22144 activation of a task that change some non-local data object (directly or
22145      indirectly);
22146
22147 @item
22148 elaboration code of a package that is a result of a package instantiation;
22149
22150 @item
22151 controlled objects;
22152 @end itemize
22153
22154 @item Situations when we can suspect a side-effect, but the full static check
22155 is either impossible or too hard:
22156 @itemize @bullet
22157 @item
22158 assignment to access variables or to the objects pointed by access
22159      variables;
22160
22161 @item
22162 call to a subprogram pointed by access-to-subprogram value
22163
22164 @item
22165 dispatching calls;
22166 @end itemize
22167 @end enumerate
22168
22169 @noindent
22170 This rule has no parameters.
22171 @end ignore
22172
22173 @node Slices
22174 @subsection @code{Slices}
22175 @cindex @code{Slices} rule (for @command{gnatcheck})
22176
22177 @noindent
22178 Flag all uses of array slicing
22179
22180 This rule has no parameters.
22181
22182
22183 @node Unassigned_OUT_Parameters
22184 @subsection @code{Unassigned_OUT_Parameters}
22185 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22186
22187 @noindent
22188 Flags procedures' @code{out} parameters that are not assigned, and
22189 identifies the contexts in which the assignments are missing.
22190
22191 An @code{out} parameter is flagged in the statements in the procedure
22192 body's handled sequence of statements (before the procedure body's
22193 @code{exception} part, if any) if this sequence of statements contains
22194 no assignments to the parameter.
22195
22196 An @code{out} parameter is flagged in an exception handler in the exception
22197 part of the procedure body's handled sequence of statements if the handler
22198 contains no assignment to the parameter.
22199
22200 Bodies of generic procedures are also considered.
22201
22202 The following are treated as assignments to an @code{out} parameter:
22203
22204 @itemize @bullet
22205 @item
22206 an assignment statement, with the parameter or some component as the target;
22207
22208 @item
22209 passing the parameter (or one of its components) as an @code{out} or
22210 @code{in out} parameter.
22211 @end itemize
22212
22213 @noindent
22214 This rule does not have any parameters.
22215
22216
22217
22218 @node Uncommented_BEGIN_In_Package_Bodies
22219 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22220 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22221
22222 @noindent
22223 Flags each package body with declarations and a statement part that does not
22224 include a trailing comment on the line containing the @code{begin} keyword;
22225 this trailing comment needs to specify the package name and nothing else.
22226 The @code{begin} is not flagged if the package body does not
22227 contain any declarations.
22228
22229 If the @code{begin} keyword is placed on the
22230 same line as the last declaration or the first statement, it is flagged
22231 independently of whether the line contains a trailing comment. The
22232 diagnostic message is attached to the line containing the first statement.
22233
22234 This rule has no parameters.
22235
22236
22237 @node Unconstrained_Array_Returns
22238 @subsection @code{Unconstrained_Array_Returns}
22239 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22240
22241 @noindent
22242 Flag each function returning an unconstrained array. Function declarations,
22243 function bodies (and body stubs) having no separate specifications,
22244 and generic function instantiations are checked.
22245 Generic function declarations, function calls and function renamings are
22246 not checked.
22247
22248 This rule has no parameters.
22249
22250 @node Universal_Ranges
22251 @subsection @code{Universal_Ranges}
22252 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22253
22254 @noindent
22255 Flag discrete ranges that are a part of an index constraint, constrained
22256 array definition, or @code{for}-loop parameter specification, and whose bounds
22257 are both of type @i{universal_integer}. Ranges that have at least one
22258 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22259 or an expression of non-universal type) are not flagged.
22260
22261 This rule has no parameters.
22262
22263
22264 @node Unnamed_Blocks_And_Loops
22265 @subsection @code{Unnamed_Blocks_And_Loops}
22266 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22267
22268 @noindent
22269 Flag each unnamed block statement and loop statement.
22270
22271 The rule has no parameters.
22272
22273
22274
22275 @ignore
22276 @node Unused_Subprograms
22277 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22278 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22279
22280 @noindent
22281 Flag all unused subprograms.
22282
22283 This rule has no parameters.
22284 @end ignore
22285
22286
22287
22288
22289 @node USE_PACKAGE_Clauses
22290 @subsection @code{USE_PACKAGE_Clauses}
22291 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22292
22293 @noindent
22294 Flag all @code{use} clauses for packages; @code{use type} clauses are
22295 not flagged.
22296
22297 This rule has no parameters.
22298
22299
22300
22301 @node Volatile_Objects_Without_Address_Clauses
22302 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22303 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22304
22305 @noindent
22306 Flag each volatile object that does not have an address clause.
22307
22308 The following check is made: if the pragma @code{Volatile} is applied to a
22309 data object or to its type, then an address clause must
22310 be supplied for this object.
22311
22312 This rule does not check the components of data objects,
22313 array components that are volatile as a result of the pragma
22314 @code{Volatile_Components}, or objects that are volatile because
22315 they are atomic as a result of pragmas @code{Atomic} or
22316 @code{Atomic_Components}.
22317
22318 Only variable declarations, and not constant declarations, are checked.
22319
22320 This rule has no parameters.
22321
22322
22323 @c *********************************
22324 @node Creating Sample Bodies Using gnatstub
22325 @chapter Creating Sample Bodies Using @command{gnatstub}
22326 @findex gnatstub
22327
22328 @noindent
22329 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22330 for library unit declarations.
22331
22332 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22333 driver (see @ref{The GNAT Driver and Project Files}).
22334
22335 To create a body stub, @command{gnatstub} has to compile the library
22336 unit declaration. Therefore, bodies can be created only for legal
22337 library units. Moreover, if a library unit depends semantically upon
22338 units located outside the current directory, you have to provide
22339 the source search path when calling @command{gnatstub}, see the description
22340 of @command{gnatstub} switches below.
22341
22342 By default, all the program unit body stubs generated by @code{gnatstub}
22343 raise the predefined @code{Program_Error} exception, which will catch
22344 accidental calls of generated stubs. This behavior can be changed with
22345 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22346
22347 @menu
22348 * Running gnatstub::
22349 * Switches for gnatstub::
22350 @end menu
22351
22352 @node Running gnatstub
22353 @section Running @command{gnatstub}
22354
22355 @noindent
22356 @command{gnatstub} has the command-line interface of the form
22357
22358 @smallexample
22359 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22360 @end smallexample
22361
22362 @noindent
22363 where
22364 @table @var
22365 @item filename
22366 is the name of the source file that contains a library unit declaration
22367 for which a body must be created. The file name may contain the path
22368 information.
22369 The file name does not have to follow the GNAT file name conventions. If the
22370 name
22371 does not follow GNAT file naming conventions, the name of the body file must
22372 be provided
22373 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22374 If the file name follows the GNAT file naming
22375 conventions and the name of the body file is not provided,
22376 @command{gnatstub}
22377 creates the name
22378 of the body file from the argument file name by replacing the @file{.ads}
22379 suffix
22380 with the @file{.adb} suffix.
22381
22382 @item directory
22383 indicates the directory in which the body stub is to be placed (the default
22384 is the
22385 current directory)
22386
22387 @item switches
22388 is an optional sequence of switches as described in the next section
22389 @end table
22390
22391 @node Switches for gnatstub
22392 @section Switches for @command{gnatstub}
22393
22394 @table @option
22395 @c !sort!
22396
22397 @item ^-f^/FULL^
22398 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22399 If the destination directory already contains a file with the name of the
22400 body file
22401 for the argument spec file, replace it with the generated body stub.
22402
22403 @item ^-hs^/HEADER=SPEC^
22404 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22405 Put the comment header (i.e., all the comments preceding the
22406 compilation unit) from the source of the library unit declaration
22407 into the body stub.
22408
22409 @item ^-hg^/HEADER=GENERAL^
22410 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22411 Put a sample comment header into the body stub.
22412
22413 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22414 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22415 Use the content of the file as the comment header for a generated body stub.
22416
22417 @ifclear vms
22418 @item -IDIR
22419 @cindex @option{-IDIR} (@command{gnatstub})
22420 @itemx -I-
22421 @cindex @option{-I-} (@command{gnatstub})
22422 @end ifclear
22423 @ifset vms
22424 @item /NOCURRENT_DIRECTORY
22425 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22426 @end ifset
22427 ^These switches have ^This switch has^ the same meaning as in calls to
22428 @command{gcc}.
22429 ^They define ^It defines ^ the source search path in the call to
22430 @command{gcc} issued
22431 by @command{gnatstub} to compile an argument source file.
22432
22433 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22434 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22435 This switch has the same meaning as in calls to @command{gcc}.
22436 It defines the additional configuration file to be passed to the call to
22437 @command{gcc} issued
22438 by @command{gnatstub} to compile an argument source file.
22439
22440 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22441 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22442 (@var{n} is a non-negative integer). Set the maximum line length in the
22443 body stub to @var{n}; the default is 79. The maximum value that can be
22444 specified is 32767. Note that in the special case of configuration
22445 pragma files, the maximum is always 32767 regardless of whether or
22446 not this switch appears.
22447
22448 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22449 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22450 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22451 the generated body sample to @var{n}.
22452 The default indentation is 3.
22453
22454 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22455 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22456 Order local bodies alphabetically. (By default local bodies are ordered
22457 in the same way as the corresponding local specs in the argument spec file.)
22458
22459 @item ^-i^/INDENTATION=^@var{n}
22460 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22461 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22462
22463 @item ^-k^/TREE_FILE=SAVE^
22464 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22465 Do not remove the tree file (i.e., the snapshot of the compiler internal
22466 structures used by @command{gnatstub}) after creating the body stub.
22467
22468 @item ^-l^/LINE_LENGTH=^@var{n}
22469 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22470 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22471
22472 @item ^--no-exception^/NO_EXCEPTION^
22473 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22474 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22475 This is not always possible for function stubs.
22476
22477 @item ^-o ^/BODY=^@var{body-name}
22478 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22479 Body file name.  This should be set if the argument file name does not
22480 follow
22481 the GNAT file naming
22482 conventions. If this switch is omitted the default name for the body will be
22483 obtained
22484 from the argument file name according to the GNAT file naming conventions.
22485
22486 @item ^-q^/QUIET^
22487 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22488 Quiet mode: do not generate a confirmation when a body is
22489 successfully created, and do not generate a message when a body is not
22490 required for an
22491 argument unit.
22492
22493 @item ^-r^/TREE_FILE=REUSE^
22494 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22495 Reuse the tree file (if it exists) instead of creating it.  Instead of
22496 creating the tree file for the library unit declaration, @command{gnatstub}
22497 tries to find it in the current directory and use it for creating
22498 a body. If the tree file is not found, no body is created. This option
22499 also implies @option{^-k^/SAVE^}, whether or not
22500 the latter is set explicitly.
22501
22502 @item ^-t^/TREE_FILE=OVERWRITE^
22503 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22504 Overwrite the existing tree file.  If the current directory already
22505 contains the file which, according to the GNAT file naming rules should
22506 be considered as a tree file for the argument source file,
22507 @command{gnatstub}
22508 will refuse to create the tree file needed to create a sample body
22509 unless this option is set.
22510
22511 @item ^-v^/VERBOSE^
22512 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22513 Verbose mode: generate version information.
22514
22515 @end table
22516
22517 @c *********************************
22518 @node Generating Ada Bindings for C and C++ headers
22519 @chapter Generating Ada Bindings for C and C++ headers
22520 @findex binding
22521
22522 @noindent
22523 GNAT now comes with a new experimental binding generator for C and C++
22524 headers which is intended to do 95% of the tedious work of generating
22525 Ada specs from C or C++ header files. Note that this still is a work in
22526 progress, not designed to generate 100% correct Ada specs.
22527
22528 The code generated is using the Ada 2005 syntax, which makes it
22529 easier to interface with other languages than previous versions of Ada.
22530
22531 @menu
22532 * Running the binding generator::
22533 * Generating bindings for C++ headers::
22534 * Switches::
22535 @end menu
22536
22537 @node Running the binding generator
22538 @section Running the binding generator
22539
22540 @noindent
22541 The binding generator is part of the @command{gcc} compiler and can be
22542 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
22543 spec files for the header files specified on the command line, and all
22544 header files needed by these files transitivitely. For example:
22545
22546 @smallexample
22547 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
22548 $ gcc -c -gnat05 *.ads
22549 @end smallexample
22550
22551 will generate, under GNU/Linux, the following files: @file{time_h.ads},
22552 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
22553 correspond to the files @file{/usr/include/time.h},
22554 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
22555 mode these Ada specs.
22556
22557 The @code{-C} switch tells @command{gcc} to extract comments from headers,
22558 and will attempt to generate corresponding Ada comments.
22559
22560 If you want to generate a single Ada file and not the transitive closure, you
22561 can use instead the @option{-fdump-ada-spec-slim} switch.
22562
22563 Note that we recommend when possible to use the @command{g++} driver to
22564 generate bindings, even for most C headers, since this will in general
22565 generate better Ada specs. For generating bindings for C++ headers, it is
22566 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
22567 is equivalent in this case. If @command{g++} cannot work on your C headers
22568 because of incompatibilities between C and C++, then you can fallback to
22569 @command{gcc} instead.
22570
22571 For an example of better bindings generated from the C++ front-end,
22572 the name of the parameters (when available) are actually ignored by the C
22573 front-end. Consider the following C header:
22574
22575 @smallexample
22576 extern void foo (int variable);
22577 @end smallexample
22578
22579 with the C front-end, @code{variable} is ignored, and the above is handled as:
22580
22581 @smallexample
22582 extern void foo (int);
22583 @end smallexample
22584
22585 generating a generic:
22586
22587 @smallexample
22588 procedure foo (param1 : int);
22589 @end smallexample
22590
22591 with the C++ front-end, the name is available, and we generate:
22592
22593 @smallexample
22594 procedure foo (variable : int);
22595 @end smallexample
22596
22597 In some cases, the generated bindings will be more complete or more meaningful
22598 when defining some macros, which you can do via the @option{-D} switch. This
22599 is for example the case with @file{Xlib.h} under GNU/Linux:
22600
22601 @smallexample
22602 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
22603 @end smallexample
22604
22605 The above will generate more complete bindings than a straight call without
22606 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
22607
22608 In other cases, it is not possible to parse a header file in a stand alone
22609 manner, because other include files need to be included first. In this
22610 case, the solution is to create a small header file including the needed
22611 @code{#include} and possible @code{#define} directives. For example, to
22612 generate Ada bindings for @file{readline/readline.h}, you need to first
22613 include @file{stdio.h}, so you can create a file with the following two
22614 lines in e.g. @file{readline1.h}:
22615
22616 @smallexample
22617 #include <stdio.h>
22618 #include <readline/readline.h>
22619 @end smallexample
22620
22621 and then generate Ada bindings from this file:
22622
22623 @smallexample
22624 $ g++ -c -fdump-ada-spec readline1.h
22625 @end smallexample
22626
22627 @node Generating bindings for C++ headers
22628 @section Generating bindings for C++ headers
22629
22630 @noindent
22631 Generating bindings for C++ headers is done using the same options, always
22632 with the @command{g++} compiler.
22633
22634 In this mode, C++ classes will be mapped to Ada tagged types, constructors
22635 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
22636 multiple inheritance of abstract classes will be mapped to Ada interfaces
22637 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
22638 information on interfacing to C++).
22639
22640 For example, given the following C++ header file:
22641
22642 @smallexample
22643 @group
22644 @cartouche
22645 class Carnivore @{
22646 public:
22647    virtual int Number_Of_Teeth () = 0;
22648 @};
22649
22650 class Domestic @{
22651 public:
22652    virtual void Set_Owner (char* Name) = 0;
22653 @};
22654
22655 class Animal @{
22656 public:
22657   int Age_Count;
22658   virtual void Set_Age (int New_Age);
22659 @};
22660
22661 class Dog : Animal, Carnivore, Domestic @{
22662  public:
22663   int  Tooth_Count;
22664   char *Owner;
22665
22666   virtual int  Number_Of_Teeth ();
22667   virtual void Set_Owner (char* Name);
22668
22669   Dog();
22670 @};
22671 @end cartouche
22672 @end group
22673 @end smallexample
22674
22675 The corresponding Ada code is generated:
22676
22677 @smallexample @c ada
22678 @group
22679 @cartouche
22680   package Class_Carnivore is
22681     type Carnivore is limited interface;
22682     pragma Import (CPP, Carnivore);
22683
22684     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
22685   end;
22686   use Class_Carnivore;
22687
22688   package Class_Domestic is
22689     type Domestic is limited interface;
22690     pragma Import (CPP, Domestic);
22691
22692     procedure Set_Owner
22693       (this : access Domestic;
22694        Name : Interfaces.C.Strings.chars_ptr) is abstract;
22695   end;
22696   use Class_Domestic;
22697
22698   package Class_Animal is
22699     type Animal is tagged limited record
22700       Age_Count : aliased int;
22701     end record;
22702     pragma Import (CPP, Animal);
22703
22704     procedure Set_Age (this : access Animal; New_Age : int);
22705     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
22706   end;
22707   use Class_Animal;
22708
22709   package Class_Dog is
22710     type Dog is new Animal and Carnivore and Domestic with record
22711       Tooth_Count : aliased int;
22712       Owner : Interfaces.C.Strings.chars_ptr;
22713     end record;
22714     pragma Import (CPP, Dog);
22715
22716     function Number_Of_Teeth (this : access Dog) return int;
22717     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
22718
22719     procedure Set_Owner
22720       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
22721     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
22722
22723     function New_Dog return Dog'Class;
22724     pragma CPP_Constructor (New_Dog);
22725     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
22726   end;
22727   use Class_Dog;
22728 @end cartouche
22729 @end group
22730 @end smallexample
22731
22732 @node Switches
22733 @section Switches
22734
22735 @table @option
22736 @item -fdump-ada-spec
22737 @cindex @option{-fdump-ada-spec} (@command{gcc})
22738 Generate Ada spec files for the given header files transitively (including
22739 all header files that these headers depend upon).
22740
22741 @item -fdump-ada-spec-slim
22742 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
22743 Generate Ada spec files for the header files specified on the command line
22744 only.
22745
22746 @item -C
22747 @cindex @option{-C} (@command{gcc})
22748 Extract comments from headers and generate Ada comments in the Ada spec files.
22749 @end table
22750
22751 @node Other Utility Programs
22752 @chapter Other Utility Programs
22753
22754 @noindent
22755 This chapter discusses some other utility programs available in the Ada
22756 environment.
22757
22758 @menu
22759 * Using Other Utility Programs with GNAT::
22760 * The External Symbol Naming Scheme of GNAT::
22761 * Converting Ada Files to html with gnathtml::
22762 * Installing gnathtml::
22763 @ifset vms
22764 * LSE::
22765 * Profiling::
22766 @end ifset
22767 @end menu
22768
22769 @node Using Other Utility Programs with GNAT
22770 @section Using Other Utility Programs with GNAT
22771
22772 @noindent
22773 The object files generated by GNAT are in standard system format and in
22774 particular the debugging information uses this format. This means
22775 programs generated by GNAT can be used with existing utilities that
22776 depend on these formats.
22777
22778 @ifclear vms
22779 In general, any utility program that works with C will also often work with
22780 Ada programs generated by GNAT. This includes software utilities such as
22781 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22782 as Purify.
22783 @end ifclear
22784
22785 @node The External Symbol Naming Scheme of GNAT
22786 @section The External Symbol Naming Scheme of GNAT
22787
22788 @noindent
22789 In order to interpret the output from GNAT, when using tools that are
22790 originally intended for use with other languages, it is useful to
22791 understand the conventions used to generate link names from the Ada
22792 entity names.
22793
22794 All link names are in all lowercase letters. With the exception of library
22795 procedure names, the mechanism used is simply to use the full expanded
22796 Ada name with dots replaced by double underscores. For example, suppose
22797 we have the following package spec:
22798
22799 @smallexample @c ada
22800 @group
22801 @cartouche
22802 package QRS is
22803    MN : Integer;
22804 end QRS;
22805 @end cartouche
22806 @end group
22807 @end smallexample
22808
22809 @noindent
22810 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22811 the corresponding link name is @code{qrs__mn}.
22812 @findex Export
22813 Of course if a @code{pragma Export} is used this may be overridden:
22814
22815 @smallexample @c ada
22816 @group
22817 @cartouche
22818 package Exports is
22819    Var1 : Integer;
22820    pragma Export (Var1, C, External_Name => "var1_name");
22821    Var2 : Integer;
22822    pragma Export (Var2, C, Link_Name => "var2_link_name");
22823 end Exports;
22824 @end cartouche
22825 @end group
22826 @end smallexample
22827
22828 @noindent
22829 In this case, the link name for @var{Var1} is whatever link name the
22830 C compiler would assign for the C function @var{var1_name}. This typically
22831 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22832 system conventions, but other possibilities exist. The link name for
22833 @var{Var2} is @var{var2_link_name}, and this is not operating system
22834 dependent.
22835
22836 @findex _main
22837 One exception occurs for library level procedures. A potential ambiguity
22838 arises between the required name @code{_main} for the C main program,
22839 and the name we would otherwise assign to an Ada library level procedure
22840 called @code{Main} (which might well not be the main program).
22841
22842 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22843 names. So if we have a library level procedure such as
22844
22845 @smallexample @c ada
22846 @group
22847 @cartouche
22848 procedure Hello (S : String);
22849 @end cartouche
22850 @end group
22851 @end smallexample
22852
22853 @noindent
22854 the external name of this procedure will be @var{_ada_hello}.
22855
22856
22857 @node Converting Ada Files to html with gnathtml
22858 @section Converting Ada Files to HTML with @code{gnathtml}
22859
22860 @noindent
22861 This @code{Perl} script allows Ada source files to be browsed using
22862 standard Web browsers. For installation procedure, see the section
22863 @xref{Installing gnathtml}.
22864
22865 Ada reserved keywords are highlighted in a bold font and Ada comments in
22866 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22867 switch to suppress the generation of cross-referencing information, user
22868 defined variables and types will appear in a different color; you will
22869 be able to click on any identifier and go to its declaration.
22870
22871 The command line is as follow:
22872 @smallexample
22873 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22874 @end smallexample
22875
22876 @noindent
22877 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22878 an html file for every ada file, and a global file called @file{index.htm}.
22879 This file is an index of every identifier defined in the files.
22880
22881 The available ^switches^options^ are the following ones:
22882
22883 @table @option
22884 @item -83
22885 @cindex @option{-83} (@code{gnathtml})
22886 Only the Ada 83 subset of keywords will be highlighted.
22887
22888 @item -cc @var{color}
22889 @cindex @option{-cc} (@code{gnathtml})
22890 This option allows you to change the color used for comments. The default
22891 value is green. The color argument can be any name accepted by html.
22892
22893 @item -d
22894 @cindex @option{-d} (@code{gnathtml})
22895 If the Ada files depend on some other files (for instance through
22896 @code{with} clauses, the latter files will also be converted to html.
22897 Only the files in the user project will be converted to html, not the files
22898 in the run-time library itself.
22899
22900 @item -D
22901 @cindex @option{-D} (@code{gnathtml})
22902 This command is the same as @option{-d} above, but @command{gnathtml} will
22903 also look for files in the run-time library, and generate html files for them.
22904
22905 @item -ext @var{extension}
22906 @cindex @option{-ext} (@code{gnathtml})
22907 This option allows you to change the extension of the generated HTML files.
22908 If you do not specify an extension, it will default to @file{htm}.
22909
22910 @item -f
22911 @cindex @option{-f} (@code{gnathtml})
22912 By default, gnathtml will generate html links only for global entities
22913 ('with'ed units, global variables and types,@dots{}).  If you specify
22914 @option{-f} on the command line, then links will be generated for local
22915 entities too.
22916
22917 @item -l @var{number}
22918 @cindex @option{-l} (@code{gnathtml})
22919 If this ^switch^option^ is provided and @var{number} is not 0, then
22920 @code{gnathtml} will number the html files every @var{number} line.
22921
22922 @item -I @var{dir}
22923 @cindex @option{-I} (@code{gnathtml})
22924 Specify a directory to search for library files (@file{.ALI} files) and
22925 source files. You can provide several -I switches on the command line,
22926 and the directories will be parsed in the order of the command line.
22927
22928 @item -o @var{dir}
22929 @cindex @option{-o} (@code{gnathtml})
22930 Specify the output directory for html files. By default, gnathtml will
22931 saved the generated html files in a subdirectory named @file{html/}.
22932
22933 @item -p @var{file}
22934 @cindex @option{-p} (@code{gnathtml})
22935 If you are using Emacs and the most recent Emacs Ada mode, which provides
22936 a full Integrated Development Environment for compiling, checking,
22937 running and debugging applications, you may use @file{.gpr} files
22938 to give the directories where Emacs can find sources and object files.
22939
22940 Using this ^switch^option^, you can tell gnathtml to use these files.
22941 This allows you to get an html version of your application, even if it
22942 is spread over multiple directories.
22943
22944 @item -sc @var{color}
22945 @cindex @option{-sc} (@code{gnathtml})
22946 This ^switch^option^ allows you to change the color used for symbol
22947 definitions.
22948 The default value is red. The color argument can be any name accepted by html.
22949
22950 @item -t @var{file}
22951 @cindex @option{-t} (@code{gnathtml})
22952 This ^switch^option^ provides the name of a file. This file contains a list of
22953 file names to be converted, and the effect is exactly as though they had
22954 appeared explicitly on the command line. This
22955 is the recommended way to work around the command line length limit on some
22956 systems.
22957
22958 @end table
22959
22960 @node Installing gnathtml
22961 @section Installing @code{gnathtml}
22962
22963 @noindent
22964 @code{Perl} needs to be installed on your machine to run this script.
22965 @code{Perl} is freely available for almost every architecture and
22966 Operating System via the Internet.
22967
22968 On Unix systems, you  may want to modify  the  first line of  the script
22969 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
22970 is. The syntax of this line is:
22971 @smallexample
22972 #!full_path_name_to_perl
22973 @end smallexample
22974
22975 @noindent
22976 Alternatively, you may run the script using the following command line:
22977
22978 @smallexample
22979 $ perl gnathtml.pl @ovar{switches} @var{files}
22980 @end smallexample
22981
22982 @ifset vms
22983 @node LSE
22984 @section LSE
22985 @findex LSE
22986
22987 @noindent
22988 The GNAT distribution provides an Ada 95 template for the HP Language
22989 Sensitive Editor (LSE), a component of DECset. In order to
22990 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22991
22992 @node Profiling
22993 @section Profiling
22994 @findex PCA
22995
22996 @noindent
22997 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22998 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22999 the collection phase with the /DEBUG qualifier.
23000
23001 @smallexample
23002 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23003 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23004 $ RUN/DEBUG <PROGRAM_NAME>
23005 @end smallexample
23006 @noindent
23007 @end ifset
23008
23009 @ifclear vms
23010 @c ******************************
23011 @node Code Coverage and Profiling
23012 @chapter Code Coverage and Profiling
23013 @cindex Code Coverage
23014 @cindex Profiling
23015
23016 @noindent
23017 This chapter describes how to use @code{gcov} - coverage testing tool - and
23018 @code{gprof} - profiler tool - on your Ada programs.
23019
23020 @menu
23021 * Code Coverage of Ada Programs using gcov::
23022 * Profiling an Ada Program using gprof::
23023 @end menu
23024
23025 @node Code Coverage of Ada Programs using gcov
23026 @section Code Coverage of Ada Programs using gcov
23027 @cindex gcov
23028 @cindex -fprofile-arcs
23029 @cindex -ftest-coverage
23030 @cindex -coverage
23031 @cindex Code Coverage
23032
23033 @noindent
23034 @code{gcov} is a test coverage program: it analyzes the execution of a given
23035 program on selected tests, to help you determine the portions of the program
23036 that are still untested.
23037
23038 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23039 User's Guide. You can refer to this documentation for a more complete
23040 description.
23041
23042 This chapter provides a quick startup guide, and
23043 details some Gnat-specific features.
23044
23045 @menu
23046 * Quick startup guide::
23047 * Gnat specifics::
23048 @end menu
23049
23050 @node Quick startup guide
23051 @subsection Quick startup guide
23052
23053 In order to perform coverage analysis of a program using @code{gcov}, 3
23054 steps are needed:
23055
23056 @itemize @bullet
23057 @item
23058 Code instrumentation during the compilation process
23059 @item
23060 Execution of the instrumented program
23061 @item
23062 Execution of the @code{gcov} tool to generate the result.
23063 @end itemize
23064
23065 The code instrumentation needed by gcov is created at the object level:
23066 The source code is not modified in any way, because the instrumentation code is
23067 inserted by gcc during the compilation process. To compile your code with code
23068 coverage activated, you need to recompile your whole project using the
23069 switches
23070 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23071 @code{-fprofile-arcs}.
23072
23073 @smallexample
23074 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23075    -largs -fprofile-arcs
23076 @end smallexample
23077
23078 This compilation process will create @file{.gcno} files together with
23079 the usual object files.
23080
23081 Once the program is compiled with coverage instrumentation, you can
23082 run it as many times as needed - on portions of a test suite for
23083 example. The first execution will produce @file{.gcda} files at the
23084 same location as the @file{.gcno} files.  The following executions
23085 will update those files, so that a cumulative result of the covered
23086 portions of the program is generated.
23087
23088 Finally, you need to call the @code{gcov} tool. The different options of
23089 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23090
23091 This will create annotated source files with a @file{.gcov} extension:
23092 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23093
23094 @node Gnat specifics
23095 @subsection Gnat specifics
23096
23097 Because Ada semantics, portions of the source code may be shared among
23098 several object files. This is the case for example when generics are
23099 involved, when inlining is active  or when declarations generate  initialisation
23100 calls. In order to take
23101 into account this shared code, you need to call @code{gcov} on all
23102 source files of the tested program at once.
23103
23104 The list of source files might exceed the system's maximum command line
23105 length. In order to bypass this limitation, a new mechanism has been
23106 implemented in @code{gcov}: you can now list all your project's files into a
23107 text file, and provide this file to gcov as a parameter,  preceded by a @@
23108 (e.g. @samp{gcov @@mysrclist.txt}).
23109
23110 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23111 not supported as there can be unresolved symbols during the final link.
23112
23113 @node Profiling an Ada Program using gprof
23114 @section Profiling an Ada Program using gprof
23115 @cindex gprof
23116 @cindex -pg
23117 @cindex Profiling
23118
23119 @noindent
23120 This section is not meant to be an exhaustive documentation of @code{gprof}.
23121 Full documentation for it can be found in the GNU Profiler User's Guide
23122 documentation that is part of this GNAT distribution.
23123
23124 Profiling a program helps determine the parts of a program that are executed
23125 most often, and are therefore the most time-consuming.
23126
23127 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23128 better handle Ada programs and multitasking.
23129 It is currently supported on the following platforms
23130 @itemize @bullet
23131 @item
23132 linux x86/x86_64
23133 @item
23134 solaris sparc/sparc64/x86
23135 @item
23136 windows x86
23137 @end itemize
23138
23139 @noindent
23140 In order to profile a program using @code{gprof}, 3 steps are needed:
23141
23142 @itemize @bullet
23143 @item
23144 Code instrumentation, requiring a full recompilation of the project with the
23145 proper switches.
23146 @item
23147 Execution of the program under the analysis conditions, i.e. with the desired
23148 input.
23149 @item
23150 Analysis of the results using the @code{gprof} tool.
23151 @end itemize
23152
23153 @noindent
23154 The following sections detail the different steps, and indicate how
23155 to interpret the results:
23156 @menu
23157 * Compilation for profiling::
23158 * Program execution::
23159 * Running gprof::
23160 * Interpretation of profiling results::
23161 @end menu
23162
23163 @node Compilation for profiling
23164 @subsection Compilation for profiling
23165 @cindex -pg
23166 @cindex Profiling
23167
23168 In order to profile a program the first step is to tell the compiler
23169 to generate the necessary profiling information. The compiler switch to be used
23170 is @code{-pg}, which must be added to other compilation switches. This
23171 switch needs to be specified both during compilation and link stages, and can
23172 be specified once when using gnatmake:
23173
23174 @smallexample
23175 gnatmake -f -pg -P my_project
23176 @end smallexample
23177
23178 @noindent
23179 Note that only the objects that were compiled with the @samp{-pg} switch will be
23180 profiled; if you need to profile your whole project, use the
23181 @samp{-f} gnatmake switch to force full recompilation.
23182
23183 @node Program execution
23184 @subsection Program execution
23185
23186 @noindent
23187 Once the program has been compiled for profiling, you can run it as usual.
23188
23189 The only constraint imposed by profiling is that the program must terminate
23190 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23191 properly analyzed.
23192
23193 Once the program completes execution, a data file called @file{gmon.out} is
23194 generated in the directory where the program was launched from. If this file
23195 already exists, it will be overwritten.
23196
23197 @node Running gprof
23198 @subsection Running gprof
23199
23200 @noindent
23201 The @code{gprof} tool is called as follow:
23202
23203 @smallexample
23204 gprof my_prog gmon.out
23205 @end smallexample
23206
23207 @noindent
23208 or simpler:
23209
23210 @smallexample
23211 gprof my_prog
23212 @end smallexample
23213
23214 @noindent
23215 The complete form of the gprof command line is the following:
23216
23217 @smallexample
23218 gprof [^switches^options^] [executable [data-file]]
23219 @end smallexample
23220
23221 @noindent
23222 @code{gprof} supports numerous ^switch^options^. The order of these
23223 ^switch^options^ does not matter. The full list of options can be found in
23224 the GNU Profiler User's Guide documentation that comes with this documentation.
23225
23226 The following is the subset of those switches that is most relevant:
23227
23228 @table @option
23229
23230 @item --demangle[=@var{style}]
23231 @itemx --no-demangle
23232 @cindex @option{--demangle} (@code{gprof})
23233 These options control whether symbol names should be demangled when
23234 printing output.  The default is to demangle C++ symbols.  The
23235 @code{--no-demangle} option may be used to turn off demangling. Different
23236 compilers have different mangling styles.  The optional demangling style
23237 argument can be used to choose an appropriate demangling style for your
23238 compiler, in particular Ada symbols generated by GNAT can be demangled using
23239 @code{--demangle=gnat}.
23240
23241 @item -e @var{function_name}
23242 @cindex @option{-e} (@code{gprof})
23243 The @samp{-e @var{function}} option tells @code{gprof} not to print
23244 information about the function @var{function_name} (and its
23245 children@dots{}) in the call graph.  The function will still be listed
23246 as a child of any functions that call it, but its index number will be
23247 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23248 given; only one @var{function_name} may be indicated with each @samp{-e}
23249 option.
23250
23251 @item -E @var{function_name}
23252 @cindex @option{-E} (@code{gprof})
23253 The @code{-E @var{function}} option works like the @code{-e} option, but
23254 execution time spent in the function (and children who were not called from
23255 anywhere else), will not be used to compute the percentages-of-time for
23256 the call graph.  More than one @samp{-E} option may be given; only one
23257 @var{function_name} may be indicated with each @samp{-E} option.
23258
23259 @item -f @var{function_name}
23260 @cindex @option{-f} (@code{gprof})
23261 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23262 call graph to the function @var{function_name} and its children (and
23263 their children@dots{}).  More than one @samp{-f} option may be given;
23264 only one @var{function_name} may be indicated with each @samp{-f}
23265 option.
23266
23267 @item -F @var{function_name}
23268 @cindex @option{-F} (@code{gprof})
23269 The @samp{-F @var{function}} option works like the @code{-f} option, but
23270 only time spent in the function and its children (and their
23271 children@dots{}) will be used to determine total-time and
23272 percentages-of-time for the call graph.  More than one @samp{-F} option
23273 may be given; only one @var{function_name} may be indicated with each
23274 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23275
23276 @end table
23277
23278 @node Interpretation of profiling results
23279 @subsection Interpretation of profiling results
23280
23281 @noindent
23282
23283 The results of the profiling analysis are represented by two arrays: the
23284 'flat profile' and the 'call graph'. Full documentation of those outputs
23285 can be found in the GNU Profiler User's Guide.
23286
23287 The flat profile shows the time spent in each function of the program, and how
23288 many time it has been called. This allows you to locate easily the most
23289 time-consuming functions.
23290
23291 The call graph shows, for each subprogram, the subprograms that call it,
23292 and the subprograms that it calls. It also provides an estimate of the time
23293 spent in each of those callers/called subprograms.
23294 @end ifclear
23295
23296 @c ******************************
23297 @node Running and Debugging Ada Programs
23298 @chapter Running and Debugging Ada Programs
23299 @cindex Debugging
23300
23301 @noindent
23302 This chapter discusses how to debug Ada programs.
23303 @ifset vms
23304 It applies to GNAT on the Alpha OpenVMS platform;
23305 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23306 since HP has implemented Ada support in the OpenVMS debugger on I64.
23307 @end ifset
23308
23309 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23310
23311 @enumerate
23312 @item
23313 The illegality may be a violation of the static semantics of Ada. In
23314 that case GNAT diagnoses the constructs in the program that are illegal.
23315 It is then a straightforward matter for the user to modify those parts of
23316 the program.
23317
23318 @item
23319 The illegality may be a violation of the dynamic semantics of Ada. In
23320 that case the program compiles and executes, but may generate incorrect
23321 results, or may terminate abnormally with some exception.
23322
23323 @item
23324 When presented with a program that contains convoluted errors, GNAT
23325 itself may terminate abnormally without providing full diagnostics on
23326 the incorrect user program.
23327 @end enumerate
23328
23329 @menu
23330 * The GNAT Debugger GDB::
23331 * Running GDB::
23332 * Introduction to GDB Commands::
23333 * Using Ada Expressions::
23334 * Calling User-Defined Subprograms::
23335 * Using the Next Command in a Function::
23336 * Ada Exceptions::
23337 * Ada Tasks::
23338 * Debugging Generic Units::
23339 * GNAT Abnormal Termination or Failure to Terminate::
23340 * Naming Conventions for GNAT Source Files::
23341 * Getting Internal Debugging Information::
23342 * Stack Traceback::
23343 @end menu
23344
23345 @cindex Debugger
23346 @findex gdb
23347
23348 @node The GNAT Debugger GDB
23349 @section The GNAT Debugger GDB
23350
23351 @noindent
23352 @code{GDB} is a general purpose, platform-independent debugger that
23353 can be used to debug mixed-language programs compiled with @command{gcc},
23354 and in particular is capable of debugging Ada programs compiled with
23355 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23356 complex Ada data structures.
23357
23358 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23359 @ifset vms
23360 located in the GNU:[DOCS] directory,
23361 @end ifset
23362 for full details on the usage of @code{GDB}, including a section on
23363 its usage on programs. This manual should be consulted for full
23364 details. The section that follows is a brief introduction to the
23365 philosophy and use of @code{GDB}.
23366
23367 When GNAT programs are compiled, the compiler optionally writes debugging
23368 information into the generated object file, including information on
23369 line numbers, and on declared types and variables. This information is
23370 separate from the generated code. It makes the object files considerably
23371 larger, but it does not add to the size of the actual executable that
23372 will be loaded into memory, and has no impact on run-time performance. The
23373 generation of debug information is triggered by the use of the
23374 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23375 used to carry out the compilations. It is important to emphasize that
23376 the use of these options does not change the generated code.
23377
23378 The debugging information is written in standard system formats that
23379 are used by many tools, including debuggers and profilers. The format
23380 of the information is typically designed to describe C types and
23381 semantics, but GNAT implements a translation scheme which allows full
23382 details about Ada types and variables to be encoded into these
23383 standard C formats. Details of this encoding scheme may be found in
23384 the file exp_dbug.ads in the GNAT source distribution. However, the
23385 details of this encoding are, in general, of no interest to a user,
23386 since @code{GDB} automatically performs the necessary decoding.
23387
23388 When a program is bound and linked, the debugging information is
23389 collected from the object files, and stored in the executable image of
23390 the program. Again, this process significantly increases the size of
23391 the generated executable file, but it does not increase the size of
23392 the executable program itself. Furthermore, if this program is run in
23393 the normal manner, it runs exactly as if the debug information were
23394 not present, and takes no more actual memory.
23395
23396 However, if the program is run under control of @code{GDB}, the
23397 debugger is activated.  The image of the program is loaded, at which
23398 point it is ready to run.  If a run command is given, then the program
23399 will run exactly as it would have if @code{GDB} were not present. This
23400 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23401 entirely non-intrusive until a breakpoint is encountered.  If no
23402 breakpoint is ever hit, the program will run exactly as it would if no
23403 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23404 the debugging information and can respond to user commands to inspect
23405 variables, and more generally to report on the state of execution.
23406
23407 @c **************
23408 @node Running GDB
23409 @section Running GDB
23410
23411 @noindent
23412 This section describes how to initiate the debugger.
23413 @c The above sentence is really just filler, but it was otherwise
23414 @c clumsy to get the first paragraph nonindented given the conditional
23415 @c nature of the description
23416
23417 @ifclear vms
23418 The debugger can be launched from a @code{GPS} menu or
23419 directly from the command line. The description below covers the latter use.
23420 All the commands shown can be used in the @code{GPS} debug console window,
23421 but there are usually more GUI-based ways to achieve the same effect.
23422 @end ifclear
23423
23424 The command to run @code{GDB} is
23425
23426 @smallexample
23427 $ ^gdb program^GDB PROGRAM^
23428 @end smallexample
23429
23430 @noindent
23431 where @code{^program^PROGRAM^} is the name of the executable file. This
23432 activates the debugger and results in a prompt for debugger commands.
23433 The simplest command is simply @code{run}, which causes the program to run
23434 exactly as if the debugger were not present. The following section
23435 describes some of the additional commands that can be given to @code{GDB}.
23436
23437 @c *******************************
23438 @node Introduction to GDB Commands
23439 @section Introduction to GDB Commands
23440
23441 @noindent
23442 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
23443 Debugging with GDB, gdb, Debugging with GDB},
23444 @ifset vms
23445 located in the GNU:[DOCS] directory,
23446 @end ifset
23447 for extensive documentation on the use
23448 of these commands, together with examples of their use. Furthermore,
23449 the command @command{help} invoked from within GDB activates a simple help
23450 facility which summarizes the available commands and their options.
23451 In this section we summarize a few of the most commonly
23452 used commands to give an idea of what @code{GDB} is about. You should create
23453 a simple program with debugging information and experiment with the use of
23454 these @code{GDB} commands on the program as you read through the
23455 following section.
23456
23457 @table @code
23458 @item set args @var{arguments}
23459 The @var{arguments} list above is a list of arguments to be passed to
23460 the program on a subsequent run command, just as though the arguments
23461 had been entered on a normal invocation of the program. The @code{set args}
23462 command is not needed if the program does not require arguments.
23463
23464 @item run
23465 The @code{run} command causes execution of the program to start from
23466 the beginning. If the program is already running, that is to say if
23467 you are currently positioned at a breakpoint, then a prompt will ask
23468 for confirmation that you want to abandon the current execution and
23469 restart.
23470
23471 @item breakpoint @var{location}
23472 The breakpoint command sets a breakpoint, that is to say a point at which
23473 execution will halt and @code{GDB} will await further
23474 commands. @var{location} is
23475 either a line number within a file, given in the format @code{file:linenumber},
23476 or it is the name of a subprogram. If you request that a breakpoint be set on
23477 a subprogram that is overloaded, a prompt will ask you to specify on which of
23478 those subprograms you want to breakpoint. You can also
23479 specify that all of them should be breakpointed. If the program is run
23480 and execution encounters the breakpoint, then the program
23481 stops and @code{GDB} signals that the breakpoint was encountered by
23482 printing the line of code before which the program is halted.
23483
23484 @item breakpoint exception @var{name}
23485 A special form of the breakpoint command which breakpoints whenever
23486 exception @var{name} is raised.
23487 If @var{name} is omitted,
23488 then a breakpoint will occur when any exception is raised.
23489
23490 @item print @var{expression}
23491 This will print the value of the given expression. Most simple
23492 Ada expression formats are properly handled by @code{GDB}, so the expression
23493 can contain function calls, variables, operators, and attribute references.
23494
23495 @item continue
23496 Continues execution following a breakpoint, until the next breakpoint or the
23497 termination of the program.
23498
23499 @item step
23500 Executes a single line after a breakpoint. If the next statement
23501 is a subprogram call, execution continues into (the first statement of)
23502 the called subprogram.
23503
23504 @item next
23505 Executes a single line. If this line is a subprogram call, executes and
23506 returns from the call.
23507
23508 @item list
23509 Lists a few lines around the current source location. In practice, it
23510 is usually more convenient to have a separate edit window open with the
23511 relevant source file displayed. Successive applications of this command
23512 print subsequent lines. The command can be given an argument which is a
23513 line number, in which case it displays a few lines around the specified one.
23514
23515 @item backtrace
23516 Displays a backtrace of the call chain. This command is typically
23517 used after a breakpoint has occurred, to examine the sequence of calls that
23518 leads to the current breakpoint. The display includes one line for each
23519 activation record (frame) corresponding to an active subprogram.
23520
23521 @item up
23522 At a breakpoint, @code{GDB} can display the values of variables local
23523 to the current frame. The command @code{up} can be used to
23524 examine the contents of other active frames, by moving the focus up
23525 the stack, that is to say from callee to caller, one frame at a time.
23526
23527 @item down
23528 Moves the focus of @code{GDB} down from the frame currently being
23529 examined to the frame of its callee (the reverse of the previous command),
23530
23531 @item frame @var{n}
23532 Inspect the frame with the given number. The value 0 denotes the frame
23533 of the current breakpoint, that is to say the top of the call stack.
23534
23535 @end table
23536
23537 @noindent
23538 The above list is a very short introduction to the commands that
23539 @code{GDB} provides. Important additional capabilities, including conditional
23540 breakpoints, the ability to execute command sequences on a breakpoint,
23541 the ability to debug at the machine instruction level and many other
23542 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23543 Debugging with GDB}.  Note that most commands can be abbreviated
23544 (for example, c for continue, bt for backtrace).
23545
23546 @node Using Ada Expressions
23547 @section Using Ada Expressions
23548 @cindex Ada expressions
23549
23550 @noindent
23551 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23552 extensions. The philosophy behind the design of this subset is
23553
23554 @itemize @bullet
23555 @item
23556 That @code{GDB} should provide basic literals and access to operations for
23557 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23558 leaving more sophisticated computations to subprograms written into the
23559 program (which therefore may be called from @code{GDB}).
23560
23561 @item
23562 That type safety and strict adherence to Ada language restrictions
23563 are not particularly important to the @code{GDB} user.
23564
23565 @item
23566 That brevity is important to the @code{GDB} user.
23567 @end itemize
23568
23569 @noindent
23570 Thus, for brevity, the debugger acts as if there were
23571 implicit @code{with} and @code{use} clauses in effect for all user-written
23572 packages, thus making it unnecessary to fully qualify most names with
23573 their packages, regardless of context. Where this causes ambiguity,
23574 @code{GDB} asks the user's intent.
23575
23576 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23577 GDB, gdb, Debugging with GDB}.
23578
23579 @node Calling User-Defined Subprograms
23580 @section Calling User-Defined Subprograms
23581
23582 @noindent
23583 An important capability of @code{GDB} is the ability to call user-defined
23584 subprograms while debugging. This is achieved simply by entering
23585 a subprogram call statement in the form:
23586
23587 @smallexample
23588 call subprogram-name (parameters)
23589 @end smallexample
23590
23591 @noindent
23592 The keyword @code{call} can be omitted in the normal case where the
23593 @code{subprogram-name} does not coincide with any of the predefined
23594 @code{GDB} commands.
23595
23596 The effect is to invoke the given subprogram, passing it the
23597 list of parameters that is supplied. The parameters can be expressions and
23598 can include variables from the program being debugged. The
23599 subprogram must be defined
23600 at the library level within your program, and @code{GDB} will call the
23601 subprogram within the environment of your program execution (which
23602 means that the subprogram is free to access or even modify variables
23603 within your program).
23604
23605 The most important use of this facility is in allowing the inclusion of
23606 debugging routines that are tailored to particular data structures
23607 in your program. Such debugging routines can be written to provide a suitably
23608 high-level description of an abstract type, rather than a low-level dump
23609 of its physical layout. After all, the standard
23610 @code{GDB print} command only knows the physical layout of your
23611 types, not their abstract meaning. Debugging routines can provide information
23612 at the desired semantic level and are thus enormously useful.
23613
23614 For example, when debugging GNAT itself, it is crucial to have access to
23615 the contents of the tree nodes used to represent the program internally.
23616 But tree nodes are represented simply by an integer value (which in turn
23617 is an index into a table of nodes).
23618 Using the @code{print} command on a tree node would simply print this integer
23619 value, which is not very useful. But the PN routine (defined in file
23620 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23621 a useful high level representation of the tree node, which includes the
23622 syntactic category of the node, its position in the source, the integers
23623 that denote descendant nodes and parent node, as well as varied
23624 semantic information. To study this example in more detail, you might want to
23625 look at the body of the PN procedure in the stated file.
23626
23627 @node Using the Next Command in a Function
23628 @section Using the Next Command in a Function
23629
23630 @noindent
23631 When you use the @code{next} command in a function, the current source
23632 location will advance to the next statement as usual. A special case
23633 arises in the case of a @code{return} statement.
23634
23635 Part of the code for a return statement is the ``epilog'' of the function.
23636 This is the code that returns to the caller. There is only one copy of
23637 this epilog code, and it is typically associated with the last return
23638 statement in the function if there is more than one return. In some
23639 implementations, this epilog is associated with the first statement
23640 of the function.
23641
23642 The result is that if you use the @code{next} command from a return
23643 statement that is not the last return statement of the function you
23644 may see a strange apparent jump to the last return statement or to
23645 the start of the function. You should simply ignore this odd jump.
23646 The value returned is always that from the first return statement
23647 that was stepped through.
23648
23649 @node Ada Exceptions
23650 @section Breaking on Ada Exceptions
23651 @cindex Exceptions
23652
23653 @noindent
23654 You can set breakpoints that trip when your program raises
23655 selected exceptions.
23656
23657 @table @code
23658 @item break exception
23659 Set a breakpoint that trips whenever (any task in the) program raises
23660 any exception.
23661
23662 @item break exception @var{name}
23663 Set a breakpoint that trips whenever (any task in the) program raises
23664 the exception @var{name}.
23665
23666 @item break exception unhandled
23667 Set a breakpoint that trips whenever (any task in the) program raises an
23668 exception for which there is no handler.
23669
23670 @item info exceptions
23671 @itemx info exceptions @var{regexp}
23672 The @code{info exceptions} command permits the user to examine all defined
23673 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23674 argument, prints out only those exceptions whose name matches @var{regexp}.
23675 @end table
23676
23677 @node Ada Tasks
23678 @section Ada Tasks
23679 @cindex Tasks
23680
23681 @noindent
23682 @code{GDB} allows the following task-related commands:
23683
23684 @table @code
23685 @item info tasks
23686 This command shows a list of current Ada tasks, as in the following example:
23687
23688 @smallexample
23689 @iftex
23690 @leftskip=0cm
23691 @end iftex
23692 (gdb) info tasks
23693   ID       TID P-ID   Thread Pri State                 Name
23694    1   8088000   0   807e000  15 Child Activation Wait main_task
23695    2   80a4000   1   80ae000  15 Accept/Select Wait    b
23696    3   809a800   1   80a4800  15 Child Activation Wait a
23697 *  4   80ae800   3   80b8000  15 Running               c
23698 @end smallexample
23699
23700 @noindent
23701 In this listing, the asterisk before the first task indicates it to be the
23702 currently running task. The first column lists the task ID that is used
23703 to refer to tasks in the following commands.
23704
23705 @item break @var{linespec} task @var{taskid}
23706 @itemx break @var{linespec} task @var{taskid} if @dots{}
23707 @cindex Breakpoints and tasks
23708 These commands are like the @code{break @dots{} thread @dots{}}.
23709 @var{linespec} specifies source lines.
23710
23711 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23712 to specify that you only want @code{GDB} to stop the program when a
23713 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23714 numeric task identifiers assigned by @code{GDB}, shown in the first
23715 column of the @samp{info tasks} display.
23716
23717 If you do not specify @samp{task @var{taskid}} when you set a
23718 breakpoint, the breakpoint applies to @emph{all} tasks of your
23719 program.
23720
23721 You can use the @code{task} qualifier on conditional breakpoints as
23722 well; in this case, place @samp{task @var{taskid}} before the
23723 breakpoint condition (before the @code{if}).
23724
23725 @item task @var{taskno}
23726 @cindex Task switching
23727
23728 This command allows to switch to the task referred by @var{taskno}. In
23729 particular, This allows to browse the backtrace of the specified
23730 task. It is advised to switch back to the original task before
23731 continuing execution otherwise the scheduling of the program may be
23732 perturbed.
23733 @end table
23734
23735 @noindent
23736 For more detailed information on the tasking support,
23737 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23738
23739 @node Debugging Generic Units
23740 @section Debugging Generic Units
23741 @cindex Debugging Generic Units
23742 @cindex Generics
23743
23744 @noindent
23745 GNAT always uses code expansion for generic instantiation. This means that
23746 each time an instantiation occurs, a complete copy of the original code is
23747 made, with appropriate substitutions of formals by actuals.
23748
23749 It is not possible to refer to the original generic entities in
23750 @code{GDB}, but it is always possible to debug a particular instance of
23751 a generic, by using the appropriate expanded names. For example, if we have
23752
23753 @smallexample @c ada
23754 @group
23755 @cartouche
23756 procedure g is
23757
23758    generic package k is
23759       procedure kp (v1 : in out integer);
23760    end k;
23761
23762    package body k is
23763       procedure kp (v1 : in out integer) is
23764       begin
23765          v1 := v1 + 1;
23766       end kp;
23767    end k;
23768
23769    package k1 is new k;
23770    package k2 is new k;
23771
23772    var : integer := 1;
23773
23774 begin
23775    k1.kp (var);
23776    k2.kp (var);
23777    k1.kp (var);
23778    k2.kp (var);
23779 end;
23780 @end cartouche
23781 @end group
23782 @end smallexample
23783
23784 @noindent
23785 Then to break on a call to procedure kp in the k2 instance, simply
23786 use the command:
23787
23788 @smallexample
23789 (gdb) break g.k2.kp
23790 @end smallexample
23791
23792 @noindent
23793 When the breakpoint occurs, you can step through the code of the
23794 instance in the normal manner and examine the values of local variables, as for
23795 other units.
23796
23797 @node GNAT Abnormal Termination or Failure to Terminate
23798 @section GNAT Abnormal Termination or Failure to Terminate
23799 @cindex GNAT Abnormal Termination or Failure to Terminate
23800
23801 @noindent
23802 When presented with programs that contain serious errors in syntax
23803 or semantics,
23804 GNAT may on rare occasions  experience problems in operation, such
23805 as aborting with a
23806 segmentation fault or illegal memory access, raising an internal
23807 exception, terminating abnormally, or failing to terminate at all.
23808 In such cases, you can activate
23809 various features of GNAT that can help you pinpoint the construct in your
23810 program that is the likely source of the problem.
23811
23812 The following strategies are presented in increasing order of
23813 difficulty, corresponding to your experience in using GNAT and your
23814 familiarity with compiler internals.
23815
23816 @enumerate
23817 @item
23818 Run @command{gcc} with the @option{-gnatf}. This first
23819 switch causes all errors on a given line to be reported. In its absence,
23820 only the first error on a line is displayed.
23821
23822 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23823 are encountered, rather than after compilation is terminated. If GNAT
23824 terminates prematurely or goes into an infinite loop, the last error
23825 message displayed may help to pinpoint the culprit.
23826
23827 @item
23828 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23829 mode, @command{gcc} produces ongoing information about the progress of the
23830 compilation and provides the name of each procedure as code is
23831 generated. This switch allows you to find which Ada procedure was being
23832 compiled when it encountered a code generation problem.
23833
23834 @item
23835 @cindex @option{-gnatdc} switch
23836 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23837 switch that does for the front-end what @option{^-v^VERBOSE^} does
23838 for the back end. The system prints the name of each unit,
23839 either a compilation unit or nested unit, as it is being analyzed.
23840 @item
23841 Finally, you can start
23842 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23843 front-end of GNAT, and can be run independently (normally it is just
23844 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23845 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23846 @code{where} command is the first line of attack; the variable
23847 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23848 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23849 which the execution stopped, and @code{input_file name} indicates the name of
23850 the source file.
23851 @end enumerate
23852
23853 @node Naming Conventions for GNAT Source Files
23854 @section Naming Conventions for GNAT Source Files
23855
23856 @noindent
23857 In order to examine the workings of the GNAT system, the following
23858 brief description of its organization may be helpful:
23859
23860 @itemize @bullet
23861 @item
23862 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23863
23864 @item
23865 All files prefixed with @file{^par^PAR^} are components of the parser. The
23866 numbers correspond to chapters of the Ada Reference Manual. For example,
23867 parsing of select statements can be found in @file{par-ch9.adb}.
23868
23869 @item
23870 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23871 numbers correspond to chapters of the Ada standard. For example, all
23872 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23873 addition, some features of the language require sufficient special processing
23874 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23875 dynamic dispatching, etc.
23876
23877 @item
23878 All files prefixed with @file{^exp^EXP^} perform normalization and
23879 expansion of the intermediate representation (abstract syntax tree, or AST).
23880 these files use the same numbering scheme as the parser and semantics files.
23881 For example, the construction of record initialization procedures is done in
23882 @file{exp_ch3.adb}.
23883
23884 @item
23885 The files prefixed with @file{^bind^BIND^} implement the binder, which
23886 verifies the consistency of the compilation, determines an order of
23887 elaboration, and generates the bind file.
23888
23889 @item
23890 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23891 data structures used by the front-end.
23892
23893 @item
23894 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23895 the abstract syntax tree as produced by the parser.
23896
23897 @item
23898 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23899 all entities, computed during semantic analysis.
23900
23901 @item
23902 Library management issues are dealt with in files with prefix
23903 @file{^lib^LIB^}.
23904
23905 @item
23906 @findex Ada
23907 @cindex Annex A
23908 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23909 defined in Annex A.
23910
23911 @item
23912 @findex Interfaces
23913 @cindex Annex B
23914 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23915 defined in Annex B.
23916
23917 @item
23918 @findex System
23919 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23920 both language-defined children and GNAT run-time routines.
23921
23922 @item
23923 @findex GNAT
23924 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23925 general-purpose packages, fully documented in their specs. All
23926 the other @file{.c} files are modifications of common @command{gcc} files.
23927 @end itemize
23928
23929 @node Getting Internal Debugging Information
23930 @section Getting Internal Debugging Information
23931
23932 @noindent
23933 Most compilers have internal debugging switches and modes. GNAT
23934 does also, except GNAT internal debugging switches and modes are not
23935 secret. A summary and full description of all the compiler and binder
23936 debug flags are in the file @file{debug.adb}. You must obtain the
23937 sources of the compiler to see the full detailed effects of these flags.
23938
23939 The switches that print the source of the program (reconstructed from
23940 the internal tree) are of general interest for user programs, as are the
23941 options to print
23942 the full internal tree, and the entity table (the symbol table
23943 information). The reconstructed source provides a readable version of the
23944 program after the front-end has completed analysis and  expansion,
23945 and is useful when studying the performance of specific constructs.
23946 For example, constraint checks are indicated, complex aggregates
23947 are replaced with loops and assignments, and tasking primitives
23948 are replaced with run-time calls.
23949
23950 @node Stack Traceback
23951 @section Stack Traceback
23952 @cindex traceback
23953 @cindex stack traceback
23954 @cindex stack unwinding
23955
23956 @noindent
23957 Traceback is a mechanism to display the sequence of subprogram calls that
23958 leads to a specified execution point in a program. Often (but not always)
23959 the execution point is an instruction at which an exception has been raised.
23960 This mechanism is also known as @i{stack unwinding} because it obtains
23961 its information by scanning the run-time stack and recovering the activation
23962 records of all active subprograms. Stack unwinding is one of the most
23963 important tools for program debugging.
23964
23965 The first entry stored in traceback corresponds to the deepest calling level,
23966 that is to say the subprogram currently executing the instruction
23967 from which we want to obtain the traceback.
23968
23969 Note that there is no runtime performance penalty when stack traceback
23970 is enabled, and no exception is raised during program execution.
23971
23972 @menu
23973 * Non-Symbolic Traceback::
23974 * Symbolic Traceback::
23975 @end menu
23976
23977 @node Non-Symbolic Traceback
23978 @subsection Non-Symbolic Traceback
23979 @cindex traceback, non-symbolic
23980
23981 @noindent
23982 Note: this feature is not supported on all platforms. See
23983 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23984 platforms.
23985
23986 @menu
23987 * Tracebacks From an Unhandled Exception::
23988 * Tracebacks From Exception Occurrences (non-symbolic)::
23989 * Tracebacks From Anywhere in a Program (non-symbolic)::
23990 @end menu
23991
23992 @node Tracebacks From an Unhandled Exception
23993 @subsubsection Tracebacks From an Unhandled Exception
23994
23995 @noindent
23996 A runtime non-symbolic traceback is a list of addresses of call instructions.
23997 To enable this feature you must use the @option{-E}
23998 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23999 of exception information. You can retrieve this information using the
24000 @code{addr2line} tool.
24001
24002 Here is a simple example:
24003
24004 @smallexample @c ada
24005 @cartouche
24006 procedure STB is
24007
24008    procedure P1 is
24009    begin
24010       raise Constraint_Error;
24011    end P1;
24012
24013    procedure P2 is
24014    begin
24015       P1;
24016    end P2;
24017
24018 begin
24019    P2;
24020 end STB;
24021 @end cartouche
24022 @end smallexample
24023
24024 @smallexample
24025 $ gnatmake stb -bargs -E
24026 $ stb
24027
24028 Execution terminated by unhandled exception
24029 Exception name: CONSTRAINT_ERROR
24030 Message: stb.adb:5
24031 Call stack traceback locations:
24032 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24033 @end smallexample
24034
24035 @noindent
24036 As we see the traceback lists a sequence of addresses for the unhandled
24037 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24038 guess that this exception come from procedure P1. To translate these
24039 addresses into the source lines where the calls appear, the
24040 @code{addr2line} tool, described below, is invaluable. The use of this tool
24041 requires the program to be compiled with debug information.
24042
24043 @smallexample
24044 $ gnatmake -g stb -bargs -E
24045 $ stb
24046
24047 Execution terminated by unhandled exception
24048 Exception name: CONSTRAINT_ERROR
24049 Message: stb.adb:5
24050 Call stack traceback locations:
24051 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24052
24053 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24054    0x4011f1 0x77e892a4
24055
24056 00401373 at d:/stb/stb.adb:5
24057 0040138B at d:/stb/stb.adb:10
24058 0040139C at d:/stb/stb.adb:14
24059 00401335 at d:/stb/b~stb.adb:104
24060 004011C4 at /build/@dots{}/crt1.c:200
24061 004011F1 at /build/@dots{}/crt1.c:222
24062 77E892A4 in ?? at ??:0
24063 @end smallexample
24064
24065 @noindent
24066 The @code{addr2line} tool has several other useful options:
24067
24068 @table @code
24069 @item --functions
24070 to get the function name corresponding to any location
24071
24072 @item --demangle=gnat
24073 to use the gnat decoding mode for the function names. Note that
24074 for binutils version 2.9.x the option is simply @option{--demangle}.
24075 @end table
24076
24077 @smallexample
24078 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24079    0x40139c 0x401335 0x4011c4 0x4011f1
24080
24081 00401373 in stb.p1 at d:/stb/stb.adb:5
24082 0040138B in stb.p2 at d:/stb/stb.adb:10
24083 0040139C in stb at d:/stb/stb.adb:14
24084 00401335 in main at d:/stb/b~stb.adb:104
24085 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24086 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24087 @end smallexample
24088
24089 @noindent
24090 From this traceback we can see that the exception was raised in
24091 @file{stb.adb} at line 5, which was reached from a procedure call in
24092 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24093 which contains the call to the main program.
24094 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24095 and the output will vary from platform to platform.
24096
24097 It is also possible to use @code{GDB} with these traceback addresses to debug
24098 the program. For example, we can break at a given code location, as reported
24099 in the stack traceback:
24100
24101 @smallexample
24102 $ gdb -nw stb
24103 @ifclear vms
24104 @noindent
24105 Furthermore, this feature is not implemented inside Windows DLL. Only
24106 the non-symbolic traceback is reported in this case.
24107 @end ifclear
24108
24109 (gdb) break *0x401373
24110 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24111 @end smallexample
24112
24113 @noindent
24114 It is important to note that the stack traceback addresses
24115 do not change when debug information is included. This is particularly useful
24116 because it makes it possible to release software without debug information (to
24117 minimize object size), get a field report that includes a stack traceback
24118 whenever an internal bug occurs, and then be able to retrieve the sequence
24119 of calls with the same program compiled with debug information.
24120
24121 @node Tracebacks From Exception Occurrences (non-symbolic)
24122 @subsubsection Tracebacks From Exception Occurrences
24123
24124 @noindent
24125 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24126 The stack traceback is attached to the exception information string, and can
24127 be retrieved in an exception handler within the Ada program, by means of the
24128 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24129
24130 @smallexample @c ada
24131 with Ada.Text_IO;
24132 with Ada.Exceptions;
24133
24134 procedure STB is
24135
24136    use Ada;
24137    use Ada.Exceptions;
24138
24139    procedure P1 is
24140       K : Positive := 1;
24141    begin
24142       K := K - 1;
24143    exception
24144       when E : others =>
24145          Text_IO.Put_Line (Exception_Information (E));
24146    end P1;
24147
24148    procedure P2 is
24149    begin
24150       P1;
24151    end P2;
24152
24153 begin
24154    P2;
24155 end STB;
24156 @end smallexample
24157
24158 @noindent
24159 This program will output:
24160
24161 @smallexample
24162 $ stb
24163
24164 Exception name: CONSTRAINT_ERROR
24165 Message: stb.adb:12
24166 Call stack traceback locations:
24167 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24168 @end smallexample
24169
24170 @node Tracebacks From Anywhere in a Program (non-symbolic)
24171 @subsubsection Tracebacks From Anywhere in a Program
24172
24173 @noindent
24174 It is also possible to retrieve a stack traceback from anywhere in a
24175 program. For this you need to
24176 use the @code{GNAT.Traceback} API. This package includes a procedure called
24177 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24178 display procedures described below. It is not necessary to use the
24179 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24180 is invoked explicitly.
24181
24182 @noindent
24183 In the following example we compute a traceback at a specific location in
24184 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24185 convert addresses to strings:
24186
24187 @smallexample @c ada
24188 with Ada.Text_IO;
24189 with GNAT.Traceback;
24190 with GNAT.Debug_Utilities;
24191
24192 procedure STB is
24193
24194    use Ada;
24195    use GNAT;
24196    use GNAT.Traceback;
24197
24198    procedure P1 is
24199       TB  : Tracebacks_Array (1 .. 10);
24200       --  We are asking for a maximum of 10 stack frames.
24201       Len : Natural;
24202       --  Len will receive the actual number of stack frames returned.
24203    begin
24204       Call_Chain (TB, Len);
24205
24206       Text_IO.Put ("In STB.P1 : ");
24207
24208       for K in 1 .. Len loop
24209          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24210          Text_IO.Put (' ');
24211       end loop;
24212
24213       Text_IO.New_Line;
24214    end P1;
24215
24216    procedure P2 is
24217    begin
24218       P1;
24219    end P2;
24220
24221 begin
24222    P2;
24223 end STB;
24224 @end smallexample
24225
24226 @smallexample
24227 $ gnatmake -g stb
24228 $ stb
24229
24230 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24231 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24232 @end smallexample
24233
24234 @noindent
24235 You can then get further information by invoking the @code{addr2line}
24236 tool as described earlier (note that the hexadecimal addresses
24237 need to be specified in C format, with a leading ``0x'').
24238
24239 @node Symbolic Traceback
24240 @subsection Symbolic Traceback
24241 @cindex traceback, symbolic
24242
24243 @noindent
24244 A symbolic traceback is a stack traceback in which procedure names are
24245 associated with each code location.
24246
24247 @noindent
24248 Note that this feature is not supported on all platforms. See
24249 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24250 list of currently supported platforms.
24251
24252 @noindent
24253 Note that the symbolic traceback requires that the program be compiled
24254 with debug information. If it is not compiled with debug information
24255 only the non-symbolic information will be valid.
24256
24257 @menu
24258 * Tracebacks From Exception Occurrences (symbolic)::
24259 * Tracebacks From Anywhere in a Program (symbolic)::
24260 @end menu
24261
24262 @node Tracebacks From Exception Occurrences (symbolic)
24263 @subsubsection Tracebacks From Exception Occurrences
24264
24265 @smallexample @c ada
24266 with Ada.Text_IO;
24267 with GNAT.Traceback.Symbolic;
24268
24269 procedure STB is
24270
24271    procedure P1 is
24272    begin
24273       raise Constraint_Error;
24274    end P1;
24275
24276    procedure P2 is
24277    begin
24278       P1;
24279    end P2;
24280
24281    procedure P3 is
24282    begin
24283       P2;
24284    end P3;
24285
24286 begin
24287    P3;
24288 exception
24289    when E : others =>
24290       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24291 end STB;
24292 @end smallexample
24293
24294 @smallexample
24295 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24296 $ stb
24297
24298 0040149F in stb.p1 at stb.adb:8
24299 004014B7 in stb.p2 at stb.adb:13
24300 004014CF in stb.p3 at stb.adb:18
24301 004015DD in ada.stb at stb.adb:22
24302 00401461 in main at b~stb.adb:168
24303 004011C4 in __mingw_CRTStartup at crt1.c:200
24304 004011F1 in mainCRTStartup at crt1.c:222
24305 77E892A4 in ?? at ??:0
24306 @end smallexample
24307
24308 @noindent
24309 In the above example the ``.\'' syntax in the @command{gnatmake} command
24310 is currently required by @command{addr2line} for files that are in
24311 the current working directory.
24312 Moreover, the exact sequence of linker options may vary from platform
24313 to platform.
24314 The above @option{-largs} section is for Windows platforms. By contrast,
24315 under Unix there is no need for the @option{-largs} section.
24316 Differences across platforms are due to details of linker implementation.
24317
24318 @node Tracebacks From Anywhere in a Program (symbolic)
24319 @subsubsection Tracebacks From Anywhere in a Program
24320
24321 @noindent
24322 It is possible to get a symbolic stack traceback
24323 from anywhere in a program, just as for non-symbolic tracebacks.
24324 The first step is to obtain a non-symbolic
24325 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24326 information. Here is an example:
24327
24328 @smallexample @c ada
24329 with Ada.Text_IO;
24330 with GNAT.Traceback;
24331 with GNAT.Traceback.Symbolic;
24332
24333 procedure STB is
24334
24335    use Ada;
24336    use GNAT.Traceback;
24337    use GNAT.Traceback.Symbolic;
24338
24339    procedure P1 is
24340       TB  : Tracebacks_Array (1 .. 10);
24341       --  We are asking for a maximum of 10 stack frames.
24342       Len : Natural;
24343       --  Len will receive the actual number of stack frames returned.
24344    begin
24345       Call_Chain (TB, Len);
24346       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24347    end P1;
24348
24349    procedure P2 is
24350    begin
24351       P1;
24352    end P2;
24353
24354 begin
24355    P2;
24356 end STB;
24357 @end smallexample
24358
24359 @c ******************************
24360 @ifset vms
24361 @node Compatibility with HP Ada
24362 @chapter Compatibility with HP Ada
24363 @cindex Compatibility
24364
24365 @noindent
24366 @cindex DEC Ada
24367 @cindex HP Ada
24368 @cindex Compatibility between GNAT and HP Ada
24369 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24370 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24371 GNAT is highly compatible
24372 with HP Ada, and it should generally be straightforward to port code
24373 from the HP Ada environment to GNAT. However, there are a few language
24374 and implementation differences of which the user must be aware. These
24375 differences are discussed in this chapter. In
24376 addition, the operating environment and command structure for the
24377 compiler are different, and these differences are also discussed.
24378
24379 For further details on these and other compatibility issues,
24380 see Appendix E of the HP publication
24381 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24382
24383 Except where otherwise indicated, the description of GNAT for OpenVMS
24384 applies to both the Alpha and I64 platforms.
24385
24386 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24387 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24388
24389 The discussion in this chapter addresses specifically the implementation
24390 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24391 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24392 GNAT always follows the Alpha implementation.
24393
24394 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24395 attributes are recognized, although only a subset of them can sensibly
24396 be implemented.  The description of pragmas in
24397 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24398 indicates whether or not they are applicable to non-VMS systems.
24399
24400 @menu
24401 * Ada Language Compatibility::
24402 * Differences in the Definition of Package System::
24403 * Language-Related Features::
24404 * The Package STANDARD::
24405 * The Package SYSTEM::
24406 * Tasking and Task-Related Features::
24407 * Pragmas and Pragma-Related Features::
24408 * Library of Predefined Units::
24409 * Bindings::
24410 * Main Program Definition::
24411 * Implementation-Defined Attributes::
24412 * Compiler and Run-Time Interfacing::
24413 * Program Compilation and Library Management::
24414 * Input-Output::
24415 * Implementation Limits::
24416 * Tools and Utilities::
24417 @end menu
24418
24419 @node Ada Language Compatibility
24420 @section Ada Language Compatibility
24421
24422 @noindent
24423 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24424 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24425 with Ada 83, and therefore Ada 83 programs will compile
24426 and run under GNAT with
24427 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24428 provides details on specific incompatibilities.
24429
24430 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24431 as well as the pragma @code{ADA_83}, to force the compiler to
24432 operate in Ada 83 mode. This mode does not guarantee complete
24433 conformance to Ada 83, but in practice is sufficient to
24434 eliminate most sources of incompatibilities.
24435 In particular, it eliminates the recognition of the
24436 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24437 in Ada 83 programs is legal, and handles the cases of packages
24438 with optional bodies, and generics that instantiate unconstrained
24439 types without the use of @code{(<>)}.
24440
24441 @node Differences in the Definition of Package System
24442 @section Differences in the Definition of Package @code{System}
24443
24444 @noindent
24445 An Ada compiler is allowed to add
24446 implementation-dependent declarations to package @code{System}.
24447 In normal mode,
24448 GNAT does not take advantage of this permission, and the version of
24449 @code{System} provided by GNAT exactly matches that defined in the Ada
24450 Reference Manual.
24451
24452 However, HP Ada adds an extensive set of declarations to package
24453 @code{System},
24454 as fully documented in the HP Ada manuals. To minimize changes required
24455 for programs that make use of these extensions, GNAT provides the pragma
24456 @code{Extend_System} for extending the definition of package System. By using:
24457 @cindex pragma @code{Extend_System}
24458 @cindex @code{Extend_System} pragma
24459
24460 @smallexample @c ada
24461 @group
24462 @cartouche
24463 pragma Extend_System (Aux_DEC);
24464 @end cartouche
24465 @end group
24466 @end smallexample
24467
24468 @noindent
24469 the set of definitions in @code{System} is extended to include those in
24470 package @code{System.Aux_DEC}.
24471 @cindex @code{System.Aux_DEC} package
24472 @cindex @code{Aux_DEC} package (child of @code{System})
24473 These definitions are incorporated directly into package @code{System},
24474 as though they had been declared there. For a
24475 list of the declarations added, see the spec of this package,
24476 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24477 @cindex @file{s-auxdec.ads} file
24478 The pragma @code{Extend_System} is a configuration pragma, which means that
24479 it can be placed in the file @file{gnat.adc}, so that it will automatically
24480 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24481 for further details.
24482
24483 An alternative approach that avoids the use of the non-standard
24484 @code{Extend_System} pragma is to add a context clause to the unit that
24485 references these facilities:
24486
24487 @smallexample @c ada
24488 @cartouche
24489 with System.Aux_DEC;
24490 use  System.Aux_DEC;
24491 @end cartouche
24492 @end smallexample
24493
24494 @noindent
24495 The effect is not quite semantically identical to incorporating
24496 the declarations directly into package @code{System},
24497 but most programs will not notice a difference
24498 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24499 to reference the entities directly in package @code{System}.
24500 For units containing such references,
24501 the prefixes must either be removed, or the pragma @code{Extend_System}
24502 must be used.
24503
24504 @node Language-Related Features
24505 @section Language-Related Features
24506
24507 @noindent
24508 The following sections highlight differences in types,
24509 representations of types, operations, alignment, and
24510 related topics.
24511
24512 @menu
24513 * Integer Types and Representations::
24514 * Floating-Point Types and Representations::
24515 * Pragmas Float_Representation and Long_Float::
24516 * Fixed-Point Types and Representations::
24517 * Record and Array Component Alignment::
24518 * Address Clauses::
24519 * Other Representation Clauses::
24520 @end menu
24521
24522 @node Integer Types and Representations
24523 @subsection Integer Types and Representations
24524
24525 @noindent
24526 The set of predefined integer types is identical in HP Ada and GNAT.
24527 Furthermore the representation of these integer types is also identical,
24528 including the capability of size clauses forcing biased representation.
24529
24530 In addition,
24531 HP Ada for OpenVMS Alpha systems has defined the
24532 following additional integer types in package @code{System}:
24533
24534 @itemize @bullet
24535
24536 @item
24537 @code{INTEGER_8}
24538
24539 @item
24540 @code{INTEGER_16}
24541
24542 @item
24543 @code{INTEGER_32}
24544
24545 @item
24546 @code{INTEGER_64}
24547
24548 @item
24549 @code{LARGEST_INTEGER}
24550 @end itemize
24551
24552 @noindent
24553 In GNAT, the first four of these types may be obtained from the
24554 standard Ada package @code{Interfaces}.
24555 Alternatively, by use of the pragma @code{Extend_System}, identical
24556 declarations can be referenced directly in package @code{System}.
24557 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24558
24559 @node Floating-Point Types and Representations
24560 @subsection Floating-Point Types and Representations
24561 @cindex Floating-Point types
24562
24563 @noindent
24564 The set of predefined floating-point types is identical in HP Ada and GNAT.
24565 Furthermore the representation of these floating-point
24566 types is also identical. One important difference is that the default
24567 representation for HP Ada is @code{VAX_Float}, but the default representation
24568 for GNAT is IEEE.
24569
24570 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24571 pragma @code{Float_Representation} as described in the HP Ada
24572 documentation.
24573 For example, the declarations:
24574
24575 @smallexample @c ada
24576 @cartouche
24577 type F_Float is digits 6;
24578 pragma Float_Representation (VAX_Float, F_Float);
24579 @end cartouche
24580 @end smallexample
24581
24582 @noindent
24583 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24584 format.
24585 This set of declarations actually appears in @code{System.Aux_DEC},
24586 which contains
24587 the full set of additional floating-point declarations provided in
24588 the HP Ada version of package @code{System}.
24589 This and similar declarations may be accessed in a user program
24590 by using pragma @code{Extend_System}. The use of this
24591 pragma, and the related pragma @code{Long_Float} is described in further
24592 detail in the following section.
24593
24594 @node Pragmas Float_Representation and Long_Float
24595 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24596
24597 @noindent
24598 HP Ada provides the pragma @code{Float_Representation}, which
24599 acts as a program library switch to allow control over
24600 the internal representation chosen for the predefined
24601 floating-point types declared in the package @code{Standard}.
24602 The format of this pragma is as follows:
24603
24604 @smallexample @c ada
24605 @cartouche
24606 pragma Float_Representation(VAX_Float | IEEE_Float);
24607 @end cartouche
24608 @end smallexample
24609
24610 @noindent
24611 This pragma controls the representation of floating-point
24612 types as follows:
24613
24614 @itemize @bullet
24615 @item
24616 @code{VAX_Float} specifies that floating-point
24617 types are represented by default with the VAX system hardware types
24618 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24619 Note that the @code{H-floating}
24620 type was available only on VAX systems, and is not available
24621 in either HP Ada or GNAT.
24622
24623 @item
24624 @code{IEEE_Float} specifies that floating-point
24625 types are represented by default with the IEEE single and
24626 double floating-point types.
24627 @end itemize
24628
24629 @noindent
24630 GNAT provides an identical implementation of the pragma
24631 @code{Float_Representation}, except that it functions as a
24632 configuration pragma. Note that the
24633 notion of configuration pragma corresponds closely to the
24634 HP Ada notion of a program library switch.
24635
24636 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24637 which is different
24638 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24639 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24640 advisable to change the format of numbers passed to standard library
24641 routines, and if necessary explicit type conversions may be needed.
24642
24643 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24644 efficient, and (given that it conforms to an international standard)
24645 potentially more portable.
24646 The situation in which @code{VAX_Float} may be useful is in interfacing
24647 to existing code and data that expect the use of @code{VAX_Float}.
24648 In such a situation use the predefined @code{VAX_Float}
24649 types in package @code{System}, as extended by
24650 @code{Extend_System}. For example, use @code{System.F_Float}
24651 to specify the 32-bit @code{F-Float} format.
24652
24653 @noindent
24654 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24655 to allow control over the internal representation chosen
24656 for the predefined type @code{Long_Float} and for floating-point
24657 type declarations with digits specified in the range 7 .. 15.
24658 The format of this pragma is as follows:
24659
24660 @smallexample @c ada
24661 @cartouche
24662 pragma Long_Float (D_FLOAT | G_FLOAT);
24663 @end cartouche
24664 @end smallexample
24665
24666 @node Fixed-Point Types and Representations
24667 @subsection Fixed-Point Types and Representations
24668
24669 @noindent
24670 On HP Ada for OpenVMS Alpha systems, rounding is
24671 away from zero for both positive and negative numbers.
24672 Therefore, @code{+0.5} rounds to @code{1},
24673 and @code{-0.5} rounds to @code{-1}.
24674
24675 On GNAT the results of operations
24676 on fixed-point types are in accordance with the Ada
24677 rules. In particular, results of operations on decimal
24678 fixed-point types are truncated.
24679
24680 @node Record and Array Component Alignment
24681 @subsection Record and Array Component Alignment
24682
24683 @noindent
24684 On HP Ada for OpenVMS Alpha, all non-composite components
24685 are aligned on natural boundaries. For example, 1-byte
24686 components are aligned on byte boundaries, 2-byte
24687 components on 2-byte boundaries, 4-byte components on 4-byte
24688 byte boundaries, and so on. The OpenVMS Alpha hardware
24689 runs more efficiently with naturally aligned data.
24690
24691 On GNAT, alignment rules are compatible
24692 with HP Ada for OpenVMS Alpha.
24693
24694 @node Address Clauses
24695 @subsection Address Clauses
24696
24697 @noindent
24698 In HP Ada and GNAT, address clauses are supported for
24699 objects and imported subprograms.
24700 The predefined type @code{System.Address} is a private type
24701 in both compilers on Alpha OpenVMS, with the same representation
24702 (it is simply a machine pointer). Addition, subtraction, and comparison
24703 operations are available in the standard Ada package
24704 @code{System.Storage_Elements}, or in package @code{System}
24705 if it is extended to include @code{System.Aux_DEC} using a
24706 pragma @code{Extend_System} as previously described.
24707
24708 Note that code that @code{with}'s both this extended package @code{System}
24709 and the package @code{System.Storage_Elements} should not @code{use}
24710 both packages, or ambiguities will result. In general it is better
24711 not to mix these two sets of facilities. The Ada package was
24712 designed specifically to provide the kind of features that HP Ada
24713 adds directly to package @code{System}.
24714
24715 The type @code{System.Address} is a 64-bit integer type in GNAT for
24716 I64 OpenVMS.  For more information,
24717 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24718
24719 GNAT is compatible with HP Ada in its handling of address
24720 clauses, except for some limitations in
24721 the form of address clauses for composite objects with
24722 initialization. Such address clauses are easily replaced
24723 by the use of an explicitly-defined constant as described
24724 in the Ada Reference Manual (13.1(22)). For example, the sequence
24725 of declarations:
24726
24727 @smallexample @c ada
24728 @cartouche
24729 X, Y : Integer := Init_Func;
24730 Q : String (X .. Y) := "abc";
24731 @dots{}
24732 for Q'Address use Compute_Address;
24733 @end cartouche
24734 @end smallexample
24735
24736 @noindent
24737 will be rejected by GNAT, since the address cannot be computed at the time
24738 that @code{Q} is declared. To achieve the intended effect, write instead:
24739
24740 @smallexample @c ada
24741 @group
24742 @cartouche
24743 X, Y : Integer := Init_Func;
24744 Q_Address : constant Address := Compute_Address;
24745 Q : String (X .. Y) := "abc";
24746 @dots{}
24747 for Q'Address use Q_Address;
24748 @end cartouche
24749 @end group
24750 @end smallexample
24751
24752 @noindent
24753 which will be accepted by GNAT (and other Ada compilers), and is also
24754 compatible with Ada 83. A fuller description of the restrictions
24755 on address specifications is found in @ref{Top, GNAT Reference Manual,
24756 About This Guide, gnat_rm, GNAT Reference Manual}.
24757
24758 @node Other Representation Clauses
24759 @subsection Other Representation Clauses
24760
24761 @noindent
24762 GNAT implements in a compatible manner all the representation
24763 clauses supported by HP Ada. In addition, GNAT
24764 implements the representation clause forms that were introduced in Ada 95,
24765 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24766
24767 @node The Package STANDARD
24768 @section The Package @code{STANDARD}
24769
24770 @noindent
24771 The package @code{STANDARD}, as implemented by HP Ada, is fully
24772 described in the @cite{Ada Reference Manual} and in the
24773 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24774 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24775
24776 In addition, HP Ada supports the Latin-1 character set in
24777 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24778 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24779 the type @code{WIDE_CHARACTER}.
24780
24781 The floating-point types supported by GNAT are those
24782 supported by HP Ada, but the defaults are different, and are controlled by
24783 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24784
24785 @node The Package SYSTEM
24786 @section The Package @code{SYSTEM}
24787
24788 @noindent
24789 HP Ada provides a specific version of the package
24790 @code{SYSTEM} for each platform on which the language is implemented.
24791 For the complete spec of the package @code{SYSTEM}, see
24792 Appendix F of the @cite{HP Ada Language Reference Manual}.
24793
24794 On HP Ada, the package @code{SYSTEM} includes the following conversion
24795 functions:
24796 @itemize @bullet
24797 @item @code{TO_ADDRESS(INTEGER)}
24798
24799 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24800
24801 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24802
24803 @item @code{TO_INTEGER(ADDRESS)}
24804
24805 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24806
24807 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24808 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24809 @end itemize
24810
24811 @noindent
24812 By default, GNAT supplies a version of @code{SYSTEM} that matches
24813 the definition given in the @cite{Ada Reference Manual}.
24814 This
24815 is a subset of the HP system definitions, which is as
24816 close as possible to the original definitions. The only difference
24817 is that the definition of @code{SYSTEM_NAME} is different:
24818
24819 @smallexample @c ada
24820 @cartouche
24821 type Name is (SYSTEM_NAME_GNAT);
24822 System_Name : constant Name := SYSTEM_NAME_GNAT;
24823 @end cartouche
24824 @end smallexample
24825
24826 @noindent
24827 Also, GNAT adds the Ada declarations for
24828 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24829
24830 However, the use of the following pragma causes GNAT
24831 to extend the definition of package @code{SYSTEM} so that it
24832 encompasses the full set of HP-specific extensions,
24833 including the functions listed above:
24834
24835 @smallexample @c ada
24836 @cartouche
24837 pragma Extend_System (Aux_DEC);
24838 @end cartouche
24839 @end smallexample
24840
24841 @noindent
24842 The pragma @code{Extend_System} is a configuration pragma that
24843 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24844 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24845
24846 HP Ada does not allow the recompilation of the package
24847 @code{SYSTEM}. Instead HP Ada provides several pragmas
24848 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24849 to modify values in the package @code{SYSTEM}.
24850 On OpenVMS Alpha systems, the pragma
24851 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24852 its single argument.
24853
24854 GNAT does permit the recompilation of package @code{SYSTEM} using
24855 the special switch @option{-gnatg}, and this switch can be used if
24856 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24857 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24858 or @code{MEMORY_SIZE} by any other means.
24859
24860 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24861 enumeration literal @code{SYSTEM_NAME_GNAT}.
24862
24863 The definitions provided by the use of
24864
24865 @smallexample @c ada
24866 pragma Extend_System (AUX_Dec);
24867 @end smallexample
24868
24869 @noindent
24870 are virtually identical to those provided by the HP Ada 83 package
24871 @code{SYSTEM}. One important difference is that the name of the
24872 @code{TO_ADDRESS}
24873 function for type @code{UNSIGNED_LONGWORD} is changed to
24874 @code{TO_ADDRESS_LONG}.
24875 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24876 discussion of why this change was necessary.
24877
24878 @noindent
24879 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24880 is in fact
24881 an extension to Ada 83 not strictly compatible with the reference manual.
24882 GNAT, in order to be exactly compatible with the standard,
24883 does not provide this capability. In HP Ada 83, the
24884 point of this definition is to deal with a call like:
24885
24886 @smallexample @c ada
24887 TO_ADDRESS (16#12777#);
24888 @end smallexample
24889
24890 @noindent
24891 Normally, according to Ada 83 semantics, one would expect this to be
24892 ambiguous, since it matches both the @code{INTEGER} and
24893 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24894 However, in HP Ada 83, there is no ambiguity, since the
24895 definition using @i{universal_integer} takes precedence.
24896
24897 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24898 it is
24899 not possible to be 100% compatible. Since there are many programs using
24900 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24901 GNAT was
24902 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24903 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24904
24905 @smallexample @c ada
24906 function To_Address (X : Integer) return Address;
24907 pragma Pure_Function (To_Address);
24908
24909 function To_Address_Long (X : Unsigned_Longword) return Address;
24910 pragma Pure_Function (To_Address_Long);
24911 @end smallexample
24912
24913 @noindent
24914 This means that programs using @code{TO_ADDRESS} for
24915 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24916
24917 @node Tasking and Task-Related Features
24918 @section Tasking and Task-Related Features
24919
24920 @noindent
24921 This section compares the treatment of tasking in GNAT
24922 and in HP Ada for OpenVMS Alpha.
24923 The GNAT description applies to both Alpha and I64 OpenVMS.
24924 For detailed information on tasking in
24925 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24926 relevant run-time reference manual.
24927
24928 @menu
24929 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24930 * Assigning Task IDs::
24931 * Task IDs and Delays::
24932 * Task-Related Pragmas::
24933 * Scheduling and Task Priority::
24934 * The Task Stack::
24935 * External Interrupts::
24936 @end menu
24937
24938 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24939 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24940
24941 @noindent
24942 On OpenVMS Alpha systems, each Ada task (except a passive
24943 task) is implemented as a single stream of execution
24944 that is created and managed by the kernel. On these
24945 systems, HP Ada tasking support is based on DECthreads,
24946 an implementation of the POSIX standard for threads.
24947
24948 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24949 code that calls DECthreads routines can be used together.
24950 The interaction between Ada tasks and DECthreads routines
24951 can have some benefits. For example when on OpenVMS Alpha,
24952 HP Ada can call C code that is already threaded.
24953
24954 GNAT uses the facilities of DECthreads,
24955 and Ada tasks are mapped to threads.
24956
24957 @node Assigning Task IDs
24958 @subsection Assigning Task IDs
24959
24960 @noindent
24961 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24962 the environment task that executes the main program. On
24963 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24964 that have been created but are not yet activated.
24965
24966 On OpenVMS Alpha systems, task IDs are assigned at
24967 activation. On GNAT systems, task IDs are also assigned at
24968 task creation but do not have the same form or values as
24969 task ID values in HP Ada. There is no null task, and the
24970 environment task does not have a specific task ID value.
24971
24972 @node Task IDs and Delays
24973 @subsection Task IDs and Delays
24974
24975 @noindent
24976 On OpenVMS Alpha systems, tasking delays are implemented
24977 using Timer System Services. The Task ID is used for the
24978 identification of the timer request (the @code{REQIDT} parameter).
24979 If Timers are used in the application take care not to use
24980 @code{0} for the identification, because cancelling such a timer
24981 will cancel all timers and may lead to unpredictable results.
24982
24983 @node Task-Related Pragmas
24984 @subsection Task-Related Pragmas
24985
24986 @noindent
24987 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24988 specification of the size of the guard area for a task
24989 stack. (The guard area forms an area of memory that has no
24990 read or write access and thus helps in the detection of
24991 stack overflow.) On OpenVMS Alpha systems, if the pragma
24992 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24993 area is created. In the absence of a pragma @code{TASK_STORAGE},
24994 a default guard area is created.
24995
24996 GNAT supplies the following task-related pragmas:
24997
24998 @itemize @bullet
24999 @item  @code{TASK_INFO}
25000
25001 This pragma appears within a task definition and
25002 applies to the task in which it appears. The argument
25003 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25004
25005 @item  @code{TASK_STORAGE}
25006
25007 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25008 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25009 @code{SUPPRESS}, and @code{VOLATILE}.
25010 @end itemize
25011 @node Scheduling and Task Priority
25012 @subsection Scheduling and Task Priority
25013
25014 @noindent
25015 HP Ada implements the Ada language requirement that
25016 when two tasks are eligible for execution and they have
25017 different priorities, the lower priority task does not
25018 execute while the higher priority task is waiting. The HP
25019 Ada Run-Time Library keeps a task running until either the
25020 task is suspended or a higher priority task becomes ready.
25021
25022 On OpenVMS Alpha systems, the default strategy is round-
25023 robin with preemption. Tasks of equal priority take turns
25024 at the processor. A task is run for a certain period of
25025 time and then placed at the tail of the ready queue for
25026 its priority level.
25027
25028 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25029 which can be used to enable or disable round-robin
25030 scheduling of tasks with the same priority.
25031 See the relevant HP Ada run-time reference manual for
25032 information on using the pragmas to control HP Ada task
25033 scheduling.
25034
25035 GNAT follows the scheduling rules of Annex D (Real-Time
25036 Annex) of the @cite{Ada Reference Manual}. In general, this
25037 scheduling strategy is fully compatible with HP Ada
25038 although it provides some additional constraints (as
25039 fully documented in Annex D).
25040 GNAT implements time slicing control in a manner compatible with
25041 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25042 are identical to the HP Ada 83 pragma of the same name.
25043 Note that it is not possible to mix GNAT tasking and
25044 HP Ada 83 tasking in the same program, since the two run-time
25045 libraries are not compatible.
25046
25047 @node The Task Stack
25048 @subsection The Task Stack
25049
25050 @noindent
25051 In HP Ada, a task stack is allocated each time a
25052 non-passive task is activated. As soon as the task is
25053 terminated, the storage for the task stack is deallocated.
25054 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25055 a default stack size is used. Also, regardless of the size
25056 specified, some additional space is allocated for task
25057 management purposes. On OpenVMS Alpha systems, at least
25058 one page is allocated.
25059
25060 GNAT handles task stacks in a similar manner. In accordance with
25061 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25062 an alternative method for controlling the task stack size.
25063 The specification of the attribute @code{T'STORAGE_SIZE} is also
25064 supported in a manner compatible with HP Ada.
25065
25066 @node External Interrupts
25067 @subsection External Interrupts
25068
25069 @noindent
25070 On HP Ada, external interrupts can be associated with task entries.
25071 GNAT is compatible with HP Ada in its handling of external interrupts.
25072
25073 @node Pragmas and Pragma-Related Features
25074 @section Pragmas and Pragma-Related Features
25075
25076 @noindent
25077 Both HP Ada and GNAT supply all language-defined pragmas
25078 as specified by the Ada 83 standard. GNAT also supplies all
25079 language-defined pragmas introduced by Ada 95 and Ada 2005.
25080 In addition, GNAT implements the implementation-defined pragmas
25081 from HP Ada 83.
25082
25083 @itemize @bullet
25084 @item  @code{AST_ENTRY}
25085
25086 @item  @code{COMMON_OBJECT}
25087
25088 @item  @code{COMPONENT_ALIGNMENT}
25089
25090 @item  @code{EXPORT_EXCEPTION}
25091
25092 @item  @code{EXPORT_FUNCTION}
25093
25094 @item  @code{EXPORT_OBJECT}
25095
25096 @item  @code{EXPORT_PROCEDURE}
25097
25098 @item  @code{EXPORT_VALUED_PROCEDURE}
25099
25100 @item  @code{FLOAT_REPRESENTATION}
25101
25102 @item  @code{IDENT}
25103
25104 @item  @code{IMPORT_EXCEPTION}
25105
25106 @item  @code{IMPORT_FUNCTION}
25107
25108 @item  @code{IMPORT_OBJECT}
25109
25110 @item  @code{IMPORT_PROCEDURE}
25111
25112 @item  @code{IMPORT_VALUED_PROCEDURE}
25113
25114 @item  @code{INLINE_GENERIC}
25115
25116 @item  @code{INTERFACE_NAME}
25117
25118 @item  @code{LONG_FLOAT}
25119
25120 @item  @code{MAIN_STORAGE}
25121
25122 @item  @code{PASSIVE}
25123
25124 @item  @code{PSECT_OBJECT}
25125
25126 @item  @code{SHARE_GENERIC}
25127
25128 @item  @code{SUPPRESS_ALL}
25129
25130 @item  @code{TASK_STORAGE}
25131
25132 @item  @code{TIME_SLICE}
25133
25134 @item  @code{TITLE}
25135 @end itemize
25136
25137 @noindent
25138 These pragmas are all fully implemented, with the exception of @code{TITLE},
25139 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25140 recognized, but which have no
25141 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25142 use of Ada protected objects. In GNAT, all generics are inlined.
25143
25144 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25145 a separate subprogram specification which must appear before the
25146 subprogram body.
25147
25148 GNAT also supplies a number of implementation-defined pragmas as follows:
25149 @itemize @bullet
25150 @item  @code{ABORT_DEFER}
25151
25152 @item  @code{ADA_83}
25153
25154 @item  @code{ADA_95}
25155
25156 @item  @code{ADA_05}
25157
25158 @item  @code{ANNOTATE}
25159
25160 @item  @code{ASSERT}
25161
25162 @item  @code{C_PASS_BY_COPY}
25163
25164 @item  @code{CPP_CLASS}
25165
25166 @item  @code{CPP_CONSTRUCTOR}
25167
25168 @item  @code{CPP_DESTRUCTOR}
25169
25170 @item  @code{DEBUG}
25171
25172 @item  @code{EXTEND_SYSTEM}
25173
25174 @item  @code{LINKER_ALIAS}
25175
25176 @item  @code{LINKER_SECTION}
25177
25178 @item  @code{MACHINE_ATTRIBUTE}
25179
25180 @item  @code{NO_RETURN}
25181
25182 @item  @code{PURE_FUNCTION}
25183
25184 @item  @code{SOURCE_FILE_NAME}
25185
25186 @item  @code{SOURCE_REFERENCE}
25187
25188 @item  @code{TASK_INFO}
25189
25190 @item  @code{UNCHECKED_UNION}
25191
25192 @item  @code{UNIMPLEMENTED_UNIT}
25193
25194 @item  @code{UNIVERSAL_DATA}
25195
25196 @item  @code{UNSUPPRESS}
25197
25198 @item  @code{WARNINGS}
25199
25200 @item  @code{WEAK_EXTERNAL}
25201 @end itemize
25202
25203 @noindent
25204 For full details on these GNAT implementation-defined pragmas,
25205 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25206 Manual}.
25207
25208 @menu
25209 * Restrictions on the Pragma INLINE::
25210 * Restrictions on the Pragma INTERFACE::
25211 * Restrictions on the Pragma SYSTEM_NAME::
25212 @end menu
25213
25214 @node Restrictions on the Pragma INLINE
25215 @subsection Restrictions on Pragma @code{INLINE}
25216
25217 @noindent
25218 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25219 @itemize @bullet
25220 @item  Parameters cannot have a task type.
25221
25222 @item  Function results cannot be task types, unconstrained
25223 array types, or unconstrained types with discriminants.
25224
25225 @item  Bodies cannot declare the following:
25226 @itemize @bullet
25227 @item  Subprogram body or stub (imported subprogram is allowed)
25228
25229 @item  Tasks
25230
25231 @item  Generic declarations
25232
25233 @item  Instantiations
25234
25235 @item  Exceptions
25236
25237 @item  Access types (types derived from access types allowed)
25238
25239 @item  Array or record types
25240
25241 @item  Dependent tasks
25242
25243 @item  Direct recursive calls of subprogram or containing
25244 subprogram, directly or via a renaming
25245
25246 @end itemize
25247 @end itemize
25248
25249 @noindent
25250 In GNAT, the only restriction on pragma @code{INLINE} is that the
25251 body must occur before the call if both are in the same
25252 unit, and the size must be appropriately small. There are
25253 no other specific restrictions which cause subprograms to
25254 be incapable of being inlined.
25255
25256 @node  Restrictions on the Pragma INTERFACE
25257 @subsection  Restrictions on Pragma @code{INTERFACE}
25258
25259 @noindent
25260 The following restrictions on pragma @code{INTERFACE}
25261 are enforced by both HP Ada and GNAT:
25262 @itemize @bullet
25263 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25264 Default is the default on OpenVMS Alpha systems.
25265
25266 @item  Parameter passing: Language specifies default
25267 mechanisms but can be overridden with an @code{EXPORT} pragma.
25268
25269 @itemize @bullet
25270 @item  Ada: Use internal Ada rules.
25271
25272 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25273 record or task type. Result cannot be a string, an
25274 array, or a record.
25275
25276 @item  Fortran: Parameters cannot have a task type. Result cannot
25277 be a string, an array, or a record.
25278 @end itemize
25279 @end itemize
25280
25281 @noindent
25282 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25283 record parameters for all languages.
25284
25285 @node  Restrictions on the Pragma SYSTEM_NAME
25286 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25287
25288 @noindent
25289 For HP Ada for OpenVMS Alpha, the enumeration literal
25290 for the type @code{NAME} is @code{OPENVMS_AXP}.
25291 In GNAT, the enumeration
25292 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25293
25294 @node  Library of Predefined Units
25295 @section  Library of Predefined Units
25296
25297 @noindent
25298 A library of predefined units is provided as part of the
25299 HP Ada and GNAT implementations. HP Ada does not provide
25300 the package @code{MACHINE_CODE} but instead recommends importing
25301 assembler code.
25302
25303 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25304 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25305 version.
25306 The HP Ada Predefined Library units are modified to remove post-Ada 83
25307 incompatibilities and to make them interoperable with GNAT
25308 (@pxref{Changes to DECLIB}, for details).
25309 The units are located in the @file{DECLIB} directory.
25310
25311 The GNAT RTL is contained in
25312 the @file{ADALIB} directory, and
25313 the default search path is set up to find @code{DECLIB} units in preference
25314 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25315 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25316
25317 @menu
25318 * Changes to DECLIB::
25319 @end menu
25320
25321 @node Changes to DECLIB
25322 @subsection Changes to @code{DECLIB}
25323
25324 @noindent
25325 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25326 compatibility are minor and include the following:
25327
25328 @itemize @bullet
25329 @item  Adjusting the location of pragmas and record representation
25330 clauses to obey Ada 95 (and thus Ada 2005) rules
25331
25332 @item  Adding the proper notation to generic formal parameters
25333 that take unconstrained types in instantiation
25334
25335 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25336 that have package bodies not otherwise allowed
25337
25338 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25339 ``@code{PROTECTD}''.
25340 Currently these are found only in the @code{STARLET} package spec.
25341
25342 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25343 where the address size is constrained to 32 bits.
25344 @end itemize
25345
25346 @noindent
25347 None of the above changes is visible to users.
25348
25349 @node Bindings
25350 @section Bindings
25351
25352 @noindent
25353 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25354 @itemize @bullet
25355
25356 @item  Command Language Interpreter (CLI interface)
25357
25358 @item  DECtalk Run-Time Library (DTK interface)
25359
25360 @item  Librarian utility routines (LBR interface)
25361
25362 @item  General Purpose Run-Time Library (LIB interface)
25363
25364 @item  Math Run-Time Library (MTH interface)
25365
25366 @item  National Character Set Run-Time Library (NCS interface)
25367
25368 @item  Compiled Code Support Run-Time Library (OTS interface)
25369
25370 @item  Parallel Processing Run-Time Library (PPL interface)
25371
25372 @item  Screen Management Run-Time Library (SMG interface)
25373
25374 @item  Sort Run-Time Library (SOR interface)
25375
25376 @item  String Run-Time Library (STR interface)
25377
25378 @item STARLET System Library
25379 @findex Starlet
25380
25381 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25382
25383 @item  X Windows Toolkit (XT interface)
25384
25385 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25386 @end itemize
25387
25388 @noindent
25389 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25390 directory, on both the Alpha and I64 OpenVMS platforms.
25391
25392 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25393 in the
25394 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25395 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25396 @code{Xt}, and @code{X_Lib}
25397 causing the default X/Motif sharable image libraries to be linked in. This
25398 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25399 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25400
25401 It may be necessary to edit these options files to update or correct the
25402 library names if, for example, the newer X/Motif bindings from
25403 @file{ADA$EXAMPLES}
25404 had been (previous to installing GNAT) copied and renamed to supersede the
25405 default @file{ADA$PREDEFINED} versions.
25406
25407 @menu
25408 * Shared Libraries and Options Files::
25409 * Interfaces to C::
25410 @end menu
25411
25412 @node Shared Libraries and Options Files
25413 @subsection Shared Libraries and Options Files
25414
25415 @noindent
25416 When using the HP Ada
25417 predefined X and Motif bindings, the linking with their sharable images is
25418 done automatically by @command{GNAT LINK}.
25419 When using other X and Motif bindings, you need
25420 to add the corresponding sharable images to the command line for
25421 @code{GNAT LINK}. When linking with shared libraries, or with
25422 @file{.OPT} files, you must
25423 also add them to the command line for @command{GNAT LINK}.
25424
25425 A shared library to be used with GNAT is built in the same way as other
25426 libraries under VMS. The VMS Link command can be used in standard fashion.
25427
25428 @node Interfaces to C
25429 @subsection Interfaces to C
25430
25431 @noindent
25432 HP Ada
25433 provides the following Ada types and operations:
25434
25435 @itemize @bullet
25436 @item C types package (@code{C_TYPES})
25437
25438 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25439
25440 @item Other_types (@code{SHORT_INT})
25441 @end itemize
25442
25443 @noindent
25444 Interfacing to C with GNAT, you can use the above approach
25445 described for HP Ada or the facilities of Annex B of
25446 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25447 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25448 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25449
25450 The @option{-gnatF} qualifier forces default and explicit
25451 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25452 to be uppercased for compatibility with the default behavior
25453 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25454
25455 @node Main Program Definition
25456 @section Main Program Definition
25457
25458 @noindent
25459 The following section discusses differences in the
25460 definition of main programs on HP Ada and GNAT.
25461 On HP Ada, main programs are defined to meet the
25462 following conditions:
25463 @itemize @bullet
25464 @item  Procedure with no formal parameters (returns @code{0} upon
25465 normal completion)
25466
25467 @item  Procedure with no formal parameters (returns @code{42} when
25468 an unhandled exception is raised)
25469
25470 @item  Function with no formal parameters whose returned value
25471 is of a discrete type
25472
25473 @item  Procedure with one @code{out} formal of a discrete type for
25474 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25475
25476 @end itemize
25477
25478 @noindent
25479 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25480 a main function or main procedure returns a discrete
25481 value whose size is less than 64 bits (32 on VAX systems),
25482 the value is zero- or sign-extended as appropriate.
25483 On GNAT, main programs are defined as follows:
25484 @itemize @bullet
25485 @item  Must be a non-generic, parameterless subprogram that
25486 is either a procedure or function returning an Ada
25487 @code{STANDARD.INTEGER} (the predefined type)
25488
25489 @item  Cannot be a generic subprogram or an instantiation of a
25490 generic subprogram
25491 @end itemize
25492
25493 @node Implementation-Defined Attributes
25494 @section Implementation-Defined Attributes
25495
25496 @noindent
25497 GNAT provides all HP Ada implementation-defined
25498 attributes.
25499
25500 @node Compiler and Run-Time Interfacing
25501 @section Compiler and Run-Time Interfacing
25502
25503 @noindent
25504 HP Ada provides the following qualifiers to pass options to the linker
25505 (ACS LINK):
25506 @itemize @bullet
25507 @item  @option{/WAIT} and @option{/SUBMIT}
25508
25509 @item  @option{/COMMAND}
25510
25511 @item  @option{/@r{[}NO@r{]}MAP}
25512
25513 @item  @option{/OUTPUT=@var{file-spec}}
25514
25515 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25516 @end itemize
25517
25518 @noindent
25519 To pass options to the linker, GNAT provides the following
25520 switches:
25521
25522 @itemize @bullet
25523 @item   @option{/EXECUTABLE=@var{exec-name}}
25524
25525 @item   @option{/VERBOSE}
25526
25527 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25528 @end itemize
25529
25530 @noindent
25531 For more information on these switches, see
25532 @ref{Switches for gnatlink}.
25533 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25534 to control optimization. HP Ada also supplies the
25535 following pragmas:
25536 @itemize @bullet
25537 @item  @code{OPTIMIZE}
25538
25539 @item  @code{INLINE}
25540
25541 @item  @code{INLINE_GENERIC}
25542
25543 @item  @code{SUPPRESS_ALL}
25544
25545 @item  @code{PASSIVE}
25546 @end itemize
25547
25548 @noindent
25549 In GNAT, optimization is controlled strictly by command
25550 line parameters, as described in the corresponding section of this guide.
25551 The HP pragmas for control of optimization are
25552 recognized but ignored.
25553
25554 Note that in GNAT, the default is optimization off, whereas in HP Ada
25555 the default is that optimization is turned on.
25556
25557 @node Program Compilation and Library Management
25558 @section Program Compilation and Library Management
25559
25560 @noindent
25561 HP Ada and GNAT provide a comparable set of commands to
25562 build programs. HP Ada also provides a program library,
25563 which is a concept that does not exist on GNAT. Instead,
25564 GNAT provides directories of sources that are compiled as
25565 needed.
25566
25567 The following table summarizes
25568 the HP Ada commands and provides
25569 equivalent GNAT commands. In this table, some GNAT
25570 equivalents reflect the fact that GNAT does not use the
25571 concept of a program library. Instead, it uses a model
25572 in which collections of source and object files are used
25573 in a manner consistent with other languages like C and
25574 Fortran. Therefore, standard system file commands are used
25575 to manipulate these elements. Those GNAT commands are marked with
25576 an asterisk.
25577 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25578
25579 @need 1500
25580 @multitable @columnfractions .35 .65
25581
25582 @item @emph{HP Ada Command}
25583 @tab @emph{GNAT Equivalent / Description}
25584
25585 @item @command{ADA}
25586 @tab @command{GNAT COMPILE}@*
25587 Invokes the compiler to compile one or more Ada source files.
25588
25589 @item @command{ACS ATTACH}@*
25590 @tab [No equivalent]@*
25591 Switches control of terminal from current process running the program
25592 library manager.
25593
25594 @item @command{ACS CHECK}
25595 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25596 Forms the execution closure of one
25597 or more compiled units and checks completeness and currency.
25598
25599 @item @command{ACS COMPILE}
25600 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25601 Forms the execution closure of one or
25602 more specified units, checks completeness and currency,
25603 identifies units that have revised source files, compiles same,
25604 and recompiles units that are or will become obsolete.
25605 Also completes incomplete generic instantiations.
25606
25607 @item @command{ACS COPY FOREIGN}
25608 @tab Copy (*)@*
25609 Copies a foreign object file into the program library as a
25610 library unit body.
25611
25612 @item @command{ACS COPY UNIT}
25613 @tab Copy (*)@*
25614 Copies a compiled unit from one program library to another.
25615
25616 @item @command{ACS CREATE LIBRARY}
25617 @tab Create /directory (*)@*
25618 Creates a program library.
25619
25620 @item @command{ACS CREATE SUBLIBRARY}
25621 @tab Create /directory (*)@*
25622 Creates a program sublibrary.
25623
25624 @item @command{ACS DELETE LIBRARY}
25625 @tab @*
25626 Deletes a program library and its contents.
25627
25628 @item @command{ACS DELETE SUBLIBRARY}
25629 @tab @*
25630 Deletes a program sublibrary and its contents.
25631
25632 @item @command{ACS DELETE UNIT}
25633 @tab Delete file (*)@*
25634 On OpenVMS systems, deletes one or more compiled units from
25635 the current program library.
25636
25637 @item @command{ACS DIRECTORY}
25638 @tab Directory (*)@*
25639 On OpenVMS systems, lists units contained in the current
25640 program library.
25641
25642 @item @command{ACS ENTER FOREIGN}
25643 @tab Copy (*)@*
25644 Allows the import of a foreign body as an Ada library
25645 spec and enters a reference to a pointer.
25646
25647 @item @command{ACS ENTER UNIT}
25648 @tab Copy (*)@*
25649 Enters a reference (pointer) from the current program library to
25650 a unit compiled into another program library.
25651
25652 @item @command{ACS EXIT}
25653 @tab [No equivalent]@*
25654 Exits from the program library manager.
25655
25656 @item @command{ACS EXPORT}
25657 @tab Copy (*)@*
25658 Creates an object file that contains system-specific object code
25659 for one or more units. With GNAT, object files can simply be copied
25660 into the desired directory.
25661
25662 @item @command{ACS EXTRACT SOURCE}
25663 @tab Copy (*)@*
25664 Allows access to the copied source file for each Ada compilation unit
25665
25666 @item @command{ACS HELP}
25667 @tab @command{HELP GNAT}@*
25668 Provides online help.
25669
25670 @item @command{ACS LINK}
25671 @tab @command{GNAT LINK}@*
25672 Links an object file containing Ada units into an executable file.
25673
25674 @item @command{ACS LOAD}
25675 @tab Copy (*)@*
25676 Loads (partially compiles) Ada units into the program library.
25677 Allows loading a program from a collection of files into a library
25678 without knowing the relationship among units.
25679
25680 @item @command{ACS MERGE}
25681 @tab Copy (*)@*
25682 Merges into the current program library, one or more units from
25683 another library where they were modified.
25684
25685 @item @command{ACS RECOMPILE}
25686 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25687 Recompiles from   external or copied source files any obsolete
25688 unit in the closure. Also, completes any incomplete generic
25689 instantiations.
25690
25691 @item @command{ACS REENTER}
25692 @tab @command{GNAT MAKE}@*
25693 Reenters current references to units compiled after last entered
25694 with the @command{ACS ENTER UNIT} command.
25695
25696 @item @command{ACS SET LIBRARY}
25697 @tab Set default (*)@*
25698 Defines a program library to be the compilation context as well
25699 as the target library for compiler output and commands in general.
25700
25701 @item @command{ACS SET PRAGMA}
25702 @tab Edit @file{gnat.adc} (*)@*
25703 Redefines specified  values of the library characteristics
25704 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25705 and @code{Float_Representation}.
25706
25707 @item @command{ACS SET SOURCE}
25708 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25709 Defines the source file search list for the @command{ACS COMPILE} command.
25710
25711 @item @command{ACS SHOW LIBRARY}
25712 @tab Directory (*)@*
25713 Lists information about one or more program libraries.
25714
25715 @item @command{ACS SHOW PROGRAM}
25716 @tab [No equivalent]@*
25717 Lists information about the execution closure of one or
25718 more units in the program library.
25719
25720 @item @command{ACS SHOW SOURCE}
25721 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25722 Shows the source file search used when compiling units.
25723
25724 @item @command{ACS SHOW VERSION}
25725 @tab Compile with @option{VERBOSE} option
25726 Displays the version number of the compiler and program library
25727 manager used.
25728
25729 @item @command{ACS SPAWN}
25730 @tab [No equivalent]@*
25731 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25732 command).
25733
25734 @item @command{ACS VERIFY}
25735 @tab [No equivalent]@*
25736 Performs a series of consistency checks on a program library to
25737 determine whether the library structure and library files are in
25738 valid form.
25739 @end multitable
25740
25741 @noindent
25742
25743 @node Input-Output
25744 @section Input-Output
25745
25746 @noindent
25747 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25748 Management Services (RMS) to perform operations on
25749 external files.
25750
25751 @noindent
25752 HP Ada and GNAT predefine an identical set of input-
25753 output packages. To make the use of the
25754 generic @code{TEXT_IO} operations more convenient, HP Ada
25755 provides predefined library packages that instantiate the
25756 integer and floating-point operations for the predefined
25757 integer and floating-point types as shown in the following table.
25758
25759 @multitable @columnfractions .45 .55
25760 @item @emph{Package Name} @tab Instantiation
25761
25762 @item @code{INTEGER_TEXT_IO}
25763 @tab @code{INTEGER_IO(INTEGER)}
25764
25765 @item @code{SHORT_INTEGER_TEXT_IO}
25766 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25767
25768 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25769 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25770
25771 @item @code{FLOAT_TEXT_IO}
25772 @tab @code{FLOAT_IO(FLOAT)}
25773
25774 @item @code{LONG_FLOAT_TEXT_IO}
25775 @tab @code{FLOAT_IO(LONG_FLOAT)}
25776 @end multitable
25777
25778 @noindent
25779 The HP Ada predefined packages and their operations
25780 are implemented using OpenVMS Alpha files and input-output
25781 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25782 Familiarity with the following is recommended:
25783 @itemize @bullet
25784 @item  RMS file organizations and access methods
25785
25786 @item  OpenVMS file specifications and directories
25787
25788 @item  OpenVMS File Definition Language (FDL)
25789 @end itemize
25790
25791 @noindent
25792 GNAT provides I/O facilities that are completely
25793 compatible with HP Ada. The distribution includes the
25794 standard HP Ada versions of all I/O packages, operating
25795 in a manner compatible with HP Ada. In particular, the
25796 following packages are by default the HP Ada (Ada 83)
25797 versions of these packages rather than the renamings
25798 suggested in Annex J of the Ada Reference Manual:
25799 @itemize @bullet
25800 @item  @code{TEXT_IO}
25801
25802 @item  @code{SEQUENTIAL_IO}
25803
25804 @item  @code{DIRECT_IO}
25805 @end itemize
25806
25807 @noindent
25808 The use of the standard child package syntax (for
25809 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25810 packages.
25811 GNAT provides HP-compatible predefined instantiations
25812 of the @code{TEXT_IO} packages, and also
25813 provides the standard predefined instantiations required
25814 by the @cite{Ada Reference Manual}.
25815
25816 For further information on how GNAT interfaces to the file
25817 system or how I/O is implemented in programs written in
25818 mixed languages, see @ref{Implementation of the Standard I/O,,,
25819 gnat_rm, GNAT Reference Manual}.
25820 This chapter covers the following:
25821 @itemize @bullet
25822 @item  Standard I/O packages
25823
25824 @item  @code{FORM} strings
25825
25826 @item  @code{ADA.DIRECT_IO}
25827
25828 @item  @code{ADA.SEQUENTIAL_IO}
25829
25830 @item  @code{ADA.TEXT_IO}
25831
25832 @item  Stream pointer positioning
25833
25834 @item  Reading and writing non-regular files
25835
25836 @item  @code{GET_IMMEDIATE}
25837
25838 @item  Treating @code{TEXT_IO} files as streams
25839
25840 @item  Shared files
25841
25842 @item  Open modes
25843 @end itemize
25844
25845 @node Implementation Limits
25846 @section Implementation Limits
25847
25848 @noindent
25849 The following table lists implementation limits for HP Ada
25850 and GNAT systems.
25851 @multitable @columnfractions .60 .20 .20
25852 @sp 1
25853 @item  @emph{Compilation Parameter}
25854 @tab   @emph{HP Ada}
25855 @tab   @emph{GNAT}
25856 @sp 1
25857
25858 @item  In a subprogram or entry  declaration, maximum number of
25859 formal parameters that are of an unconstrained record type
25860 @tab   32
25861 @tab   No set limit
25862 @sp 1
25863
25864 @item  Maximum identifier length (number of characters)
25865 @tab   255
25866 @tab   32766
25867 @sp 1
25868
25869 @item  Maximum number of characters in a source line
25870 @tab   255
25871 @tab   32766
25872 @sp 1
25873
25874 @item  Maximum collection size   (number of bytes)
25875 @tab   2**31-1
25876 @tab   2**31-1
25877 @sp 1
25878
25879 @item  Maximum number of discriminants for a record type
25880 @tab   245
25881 @tab   No set limit
25882 @sp 1
25883
25884 @item  Maximum number of formal parameters in an entry or
25885 subprogram declaration
25886 @tab   246
25887 @tab    No set limit
25888 @sp 1
25889
25890 @item  Maximum number of dimensions in an array type
25891 @tab   255
25892 @tab   No set limit
25893 @sp 1
25894
25895 @item  Maximum number of library  units and subunits in a compilation.
25896 @tab   4095
25897 @tab   No set limit
25898 @sp 1
25899
25900 @item  Maximum number of library units and subunits in an execution.
25901 @tab   16383
25902 @tab   No set limit
25903 @sp 1
25904
25905 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25906 or @code{PSECT_OBJECT}
25907 @tab   32757
25908 @tab   No set limit
25909 @sp 1
25910
25911 @item  Maximum number of enumeration literals in an enumeration type
25912 definition
25913 @tab   65535
25914 @tab   No set limit
25915 @sp 1
25916
25917 @item  Maximum number of lines in a source file
25918 @tab   65534
25919 @tab   No set limit
25920 @sp 1
25921
25922 @item  Maximum number of bits in any object
25923 @tab   2**31-1
25924 @tab   2**31-1
25925 @sp 1
25926
25927 @item  Maximum size of the static portion of a stack frame (approximate)
25928 @tab   2**31-1
25929 @tab   2**31-1
25930 @end multitable
25931
25932 @node Tools and Utilities
25933 @section Tools and Utilities
25934
25935 @noindent
25936 The following table lists some of the OpenVMS development tools
25937 available for HP Ada, and the corresponding tools for
25938 use with @value{EDITION} on Alpha and I64 platforms.
25939 Aside from the debugger, all the OpenVMS tools identified are part
25940 of the DECset package.
25941
25942 @iftex
25943 @c Specify table in TeX since Texinfo does a poor job
25944 @tex
25945 \smallskip
25946 \smallskip
25947 \settabs\+Language-Sensitive Editor\quad
25948    &Product with HP Ada\quad
25949    &\cr
25950 \+\it Tool
25951    &\it Product with HP Ada
25952    & \it Product with GNAT Pro\cr
25953 \smallskip
25954 \+Code Management System
25955    &HP CMS
25956    & HP CMS\cr
25957 \smallskip
25958 \+Language-Sensitive Editor
25959    &HP LSE
25960    & emacs or HP LSE (Alpha)\cr
25961 \+
25962    &
25963    & HP LSE (I64)\cr
25964 \smallskip
25965 \+Debugger
25966    &OpenVMS Debug
25967    & gdb (Alpha),\cr
25968 \+
25969    &
25970    & OpenVMS Debug (I64)\cr
25971 \smallskip
25972 \+Source Code Analyzer /
25973    &HP SCA
25974    & GNAT XREF\cr
25975 \+Cross Referencer
25976    &
25977    &\cr
25978 \smallskip
25979 \+Test Manager
25980    &HP Digital Test
25981    & HP DTM\cr
25982 \+
25983    &Manager (DTM)
25984    &\cr
25985 \smallskip
25986 \+Performance and
25987    & HP PCA
25988    & HP PCA\cr
25989 \+Coverage Analyzer
25990    &
25991    &\cr
25992 \smallskip
25993 \+Module Management
25994    & HP MMS
25995    & Not applicable\cr
25996 \+ System
25997    &
25998    &\cr
25999 \smallskip
26000 \smallskip
26001 @end tex
26002 @end iftex
26003
26004 @ifnottex
26005 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26006 @c the TeX version above for the printed version
26007 @flushleft
26008 @c @multitable @columnfractions .3 .4 .4
26009 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26010 @item @i{Tool}
26011 @tab @i{Tool with HP Ada}
26012 @tab @i{Tool with @value{EDITION}}
26013 @item Code Management@*System
26014 @tab HP CMS
26015 @tab HP CMS
26016 @item Language-Sensitive@*Editor
26017 @tab HP LSE
26018 @tab emacs or HP LSE (Alpha)
26019 @item
26020 @tab
26021 @tab HP LSE (I64)
26022 @item Debugger
26023 @tab OpenVMS Debug
26024 @tab gdb (Alpha),
26025 @item
26026 @tab
26027 @tab OpenVMS Debug (I64)
26028 @item Source Code Analyzer /@*Cross Referencer
26029 @tab HP SCA
26030 @tab GNAT XREF
26031 @item Test Manager
26032 @tab HP Digital Test@*Manager (DTM)
26033 @tab HP DTM
26034 @item Performance and@*Coverage Analyzer
26035 @tab HP PCA
26036 @tab HP PCA
26037 @item Module Management@*System
26038 @tab HP MMS
26039 @tab Not applicable
26040 @end multitable
26041 @end flushleft
26042 @end ifnottex
26043
26044 @end ifset
26045
26046 @c **************************************
26047 @node Platform-Specific Information for the Run-Time Libraries
26048 @appendix Platform-Specific Information for the Run-Time Libraries
26049 @cindex Tasking and threads libraries
26050 @cindex Threads libraries and tasking
26051 @cindex Run-time libraries (platform-specific information)
26052
26053 @noindent
26054 The GNAT run-time implementation may vary with respect to both the
26055 underlying threads library and the exception handling scheme.
26056 For threads support, one or more of the following are supplied:
26057 @itemize @bullet
26058 @item @b{native threads library}, a binding to the thread package from
26059 the underlying operating system
26060
26061 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26062 POSIX thread package
26063 @end itemize
26064
26065 @noindent
26066 For exception handling, either or both of two models are supplied:
26067 @itemize @bullet
26068 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26069 Most programs should experience a substantial speed improvement by
26070 being compiled with a ZCX run-time.
26071 This is especially true for
26072 tasking applications or applications with many exception handlers.}
26073 @cindex Zero-Cost Exceptions
26074 @cindex ZCX (Zero-Cost Exceptions)
26075 which uses binder-generated tables that
26076 are interrogated at run time to locate a handler
26077
26078 @item @b{setjmp / longjmp} (``SJLJ''),
26079 @cindex setjmp/longjmp Exception Model
26080 @cindex SJLJ (setjmp/longjmp Exception Model)
26081 which uses dynamically-set data to establish
26082 the set of handlers
26083 @end itemize
26084
26085 @noindent
26086 This appendix summarizes which combinations of threads and exception support
26087 are supplied on various GNAT platforms.
26088 It then shows how to select a particular library either
26089 permanently or temporarily,
26090 explains the properties of (and tradeoffs among) the various threads
26091 libraries, and provides some additional
26092 information about several specific platforms.
26093
26094 @menu
26095 * Summary of Run-Time Configurations::
26096 * Specifying a Run-Time Library::
26097 * Choosing the Scheduling Policy::
26098 * Solaris-Specific Considerations::
26099 * Linux-Specific Considerations::
26100 * AIX-Specific Considerations::
26101 * Irix-Specific Considerations::
26102 * RTX-Specific Considerations::
26103 @end menu
26104
26105 @node Summary of Run-Time Configurations
26106 @section Summary of Run-Time Configurations
26107
26108 @multitable @columnfractions .30 .70
26109 @item @b{alpha-openvms}
26110 @item @code{@ @ }@i{rts-native (default)}
26111 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26112 @item @code{@ @ @ @ }Exceptions @tab ZCX
26113 @*
26114 @item @b{alpha-tru64}
26115 @item @code{@ @ }@i{rts-native (default)}
26116 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26117 @item @code{@ @ @ @ }Exceptions @tab ZCX
26118 @*
26119 @item @code{@ @ }@i{rts-sjlj}
26120 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26121 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26122 @*
26123 @item @b{ia64-hp_linux}
26124 @item @code{@ @ }@i{rts-native (default)}
26125 @item @code{@ @ @ @ }Tasking    @tab pthread library
26126 @item @code{@ @ @ @ }Exceptions @tab ZCX
26127 @*
26128 @item @b{ia64-hpux}
26129 @item @code{@ @ }@i{rts-native (default)}
26130 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26131 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26132 @*
26133 @item @b{ia64-openvms}
26134 @item @code{@ @ }@i{rts-native (default)}
26135 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26136 @item @code{@ @ @ @ }Exceptions @tab ZCX
26137 @*
26138 @item @b{ia64-sgi_linux}
26139 @item @code{@ @ }@i{rts-native (default)}
26140 @item @code{@ @ @ @ }Tasking    @tab pthread library
26141 @item @code{@ @ @ @ }Exceptions @tab ZCX
26142 @*
26143 @item @b{mips-irix}
26144 @item @code{@ @ }@i{rts-native (default)}
26145 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26146 @item @code{@ @ @ @ }Exceptions @tab ZCX
26147 @*
26148 @item @b{pa-hpux}
26149 @item @code{@ @ }@i{rts-native (default)}
26150 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26151 @item @code{@ @ @ @ }Exceptions @tab ZCX
26152 @*
26153 @item @code{@ @ }@i{rts-sjlj}
26154 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26155 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26156 @*
26157 @item @b{ppc-aix}
26158 @item @code{@ @ }@i{rts-native (default)}
26159 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26160 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26161 @*
26162 @item @b{ppc-darwin}
26163 @item @code{@ @ }@i{rts-native (default)}
26164 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26165 @item @code{@ @ @ @ }Exceptions @tab ZCX
26166 @*
26167 @item @b{sparc-solaris}  @tab
26168 @item @code{@ @ }@i{rts-native (default)}
26169 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26170 @item @code{@ @ @ @ }Exceptions @tab ZCX
26171 @*
26172 @item @code{@ @ }@i{rts-pthread}
26173 @item @code{@ @ @ @ }Tasking    @tab pthread library
26174 @item @code{@ @ @ @ }Exceptions @tab ZCX
26175 @*
26176 @item @code{@ @ }@i{rts-sjlj}
26177 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26178 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26179 @*
26180 @item @b{sparc64-solaris}  @tab
26181 @item @code{@ @ }@i{rts-native (default)}
26182 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26183 @item @code{@ @ @ @ }Exceptions @tab ZCX
26184 @*
26185 @item @b{x86-linux}
26186 @item @code{@ @ }@i{rts-native (default)}
26187 @item @code{@ @ @ @ }Tasking    @tab pthread library
26188 @item @code{@ @ @ @ }Exceptions @tab ZCX
26189 @*
26190 @item @code{@ @ }@i{rts-sjlj}
26191 @item @code{@ @ @ @ }Tasking    @tab pthread library
26192 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26193 @*
26194 @item @b{x86-lynx}
26195 @item @code{@ @ }@i{rts-native (default)}
26196 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26197 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26198 @*
26199 @item @b{x86-solaris}
26200 @item @code{@ @ }@i{rts-native (default)}
26201 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26202 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26203 @*
26204 @item @b{x86-windows}
26205 @item @code{@ @ }@i{rts-native (default)}
26206 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26207 @item @code{@ @ @ @ }Exceptions @tab ZCX
26208 @*
26209 @item @code{@ @ }@i{rts-sjlj (default)}
26210 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26211 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26212 @*
26213 @item @b{x86-windows-rtx}
26214 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26215 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26216 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26217 @*
26218 @item @code{@ @ }@i{rts-rtx-w32}
26219 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26220 @item @code{@ @ @ @ }Exceptions @tab ZCX
26221 @*
26222 @item @b{x86_64-linux}
26223 @item @code{@ @ }@i{rts-native (default)}
26224 @item @code{@ @ @ @ }Tasking    @tab pthread library
26225 @item @code{@ @ @ @ }Exceptions @tab ZCX
26226 @*
26227 @item @code{@ @ }@i{rts-sjlj}
26228 @item @code{@ @ @ @ }Tasking    @tab pthread library
26229 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26230 @*
26231 @end multitable
26232
26233 @node Specifying a Run-Time Library
26234 @section Specifying a Run-Time Library
26235
26236 @noindent
26237 The @file{adainclude} subdirectory containing the sources of the GNAT
26238 run-time library, and the @file{adalib} subdirectory containing the
26239 @file{ALI} files and the static and/or shared GNAT library, are located
26240 in the gcc target-dependent area:
26241
26242 @smallexample
26243 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26244 @end smallexample
26245
26246 @noindent
26247 As indicated above, on some platforms several run-time libraries are supplied.
26248 These libraries are installed in the target dependent area and
26249 contain a complete source and binary subdirectory. The detailed description
26250 below explains the differences between the different libraries in terms of
26251 their thread support.
26252
26253 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26254 This default run time is selected by the means of soft links.
26255 For example on x86-linux:
26256
26257 @smallexample
26258 @group
26259  $(target-dir)
26260      |
26261      +--- adainclude----------+
26262      |                        |
26263      +--- adalib-----------+  |
26264      |                     |  |
26265      +--- rts-native       |  |
26266      |    |                |  |
26267      |    +--- adainclude <---+
26268      |    |                |
26269      |    +--- adalib <----+
26270      |
26271      +--- rts-sjlj
26272           |
26273           +--- adainclude
26274           |
26275           +--- adalib
26276 @end group
26277 @end smallexample
26278
26279 @noindent
26280 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26281 these soft links can be modified with the following commands:
26282
26283 @smallexample
26284 $ cd $target
26285 $ rm -f adainclude adalib
26286 $ ln -s rts-sjlj/adainclude adainclude
26287 $ ln -s rts-sjlj/adalib adalib
26288 @end smallexample
26289
26290 @noindent
26291 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26292 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26293 @file{$target/ada_object_path}.
26294
26295 Selecting another run-time library temporarily can be
26296 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26297 @cindex @option{--RTS} option
26298
26299 @node Choosing the Scheduling Policy
26300 @section Choosing the Scheduling Policy
26301
26302 @noindent
26303 When using a POSIX threads implementation, you have a choice of several
26304 scheduling policies: @code{SCHED_FIFO},
26305 @cindex @code{SCHED_FIFO} scheduling policy
26306 @code{SCHED_RR}
26307 @cindex @code{SCHED_RR} scheduling policy
26308 and @code{SCHED_OTHER}.
26309 @cindex @code{SCHED_OTHER} scheduling policy
26310 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26311 or @code{SCHED_RR} requires special (e.g., root) privileges.
26312
26313 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26314 @code{SCHED_FIFO},
26315 @cindex @code{SCHED_FIFO} scheduling policy
26316 you can use one of the following:
26317
26318 @itemize @bullet
26319 @item
26320 @code{pragma Time_Slice (0.0)}
26321 @cindex pragma Time_Slice
26322 @item
26323 the corresponding binder option @option{-T0}
26324 @cindex @option{-T0} option
26325 @item
26326 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26327 @cindex pragma Task_Dispatching_Policy
26328 @end itemize
26329
26330 @noindent
26331 To specify @code{SCHED_RR},
26332 @cindex @code{SCHED_RR} scheduling policy
26333 you should use @code{pragma Time_Slice} with a
26334 value greater than @code{0.0}, or else use the corresponding @option{-T}
26335 binder option.
26336
26337 @node Solaris-Specific Considerations
26338 @section Solaris-Specific Considerations
26339 @cindex Solaris Sparc threads libraries
26340
26341 @noindent
26342 This section addresses some topics related to the various threads libraries
26343 on Sparc Solaris.
26344
26345 @menu
26346 * Solaris Threads Issues::
26347 @end menu
26348
26349 @node Solaris Threads Issues
26350 @subsection Solaris Threads Issues
26351
26352 @noindent
26353 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26354 library based on POSIX threads --- @emph{rts-pthread}.
26355 @cindex rts-pthread threads library
26356 This run-time library has the advantage of being mostly shared across all
26357 POSIX-compliant thread implementations, and it also provides under
26358 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26359 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26360 and @code{PTHREAD_PRIO_PROTECT}
26361 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26362 semantics that can be selected using the predefined pragma
26363 @code{Locking_Policy}
26364 @cindex pragma Locking_Policy (under rts-pthread)
26365 with respectively
26366 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26367 @cindex @code{Inheritance_Locking} (under rts-pthread)
26368 @cindex @code{Ceiling_Locking} (under rts-pthread)
26369
26370 As explained above, the native run-time library is based on the Solaris thread
26371 library (@code{libthread}) and is the default library.
26372
26373 When the Solaris threads library is used (this is the default), programs
26374 compiled with GNAT can automatically take advantage of
26375 and can thus execute on multiple processors.
26376 The user can alternatively specify a processor on which the program should run
26377 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26378 is made by
26379 setting the environment variable @env{GNAT_PROCESSOR}
26380 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26381 to one of the following:
26382
26383 @table @code
26384 @item -2
26385 Use the default configuration (run the program on all
26386 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26387 unset
26388
26389 @item -1
26390 Let the run-time implementation choose one processor and run the program on
26391 that processor
26392
26393 @item 0 .. Last_Proc
26394 Run the program on the specified processor.
26395 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26396 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26397 @end table
26398
26399 @node Linux-Specific Considerations
26400 @section Linux-Specific Considerations
26401 @cindex Linux threads libraries
26402
26403 @noindent
26404 On GNU/Linux without NPTL support (usually system with GNU C Library
26405 older than 2.3), the signal model is not POSIX compliant, which means
26406 that to send a signal to the process, you need to send the signal to all
26407 threads, e.g.@: by using @code{killpg()}.
26408
26409 @node AIX-Specific Considerations
26410 @section AIX-Specific Considerations
26411 @cindex AIX resolver library
26412
26413 @noindent
26414 On AIX, the resolver library initializes some internal structure on
26415 the first call to @code{get*by*} functions, which are used to implement
26416 @code{GNAT.Sockets.Get_Host_By_Name} and
26417 @code{GNAT.Sockets.Get_Host_By_Address}.
26418 If such initialization occurs within an Ada task, and the stack size for
26419 the task is the default size, a stack overflow may occur.
26420
26421 To avoid this overflow, the user should either ensure that the first call
26422 to @code{GNAT.Sockets.Get_Host_By_Name} or
26423 @code{GNAT.Sockets.Get_Host_By_Addrss}
26424 occurs in the environment task, or use @code{pragma Storage_Size} to
26425 specify a sufficiently large size for the stack of the task that contains
26426 this call.
26427
26428 @node Irix-Specific Considerations
26429 @section Irix-Specific Considerations
26430 @cindex Irix libraries
26431
26432 @noindent
26433 The GCC support libraries coming with the Irix compiler have moved to
26434 their canonical place with respect to the general Irix ABI related
26435 conventions. Running applications built with the default shared GNAT
26436 run-time now requires the LD_LIBRARY_PATH environment variable to
26437 include this location. A possible way to achieve this is to issue the
26438 following command line on a bash prompt:
26439
26440 @smallexample
26441 @group
26442 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26443 @end group
26444 @end smallexample
26445
26446 @node RTX-Specific Considerations
26447 @section RTX-Specific Considerations
26448 @cindex RTX libraries
26449
26450 @noindent
26451 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26452 API. Applications can be built to work in two different modes:
26453
26454 @itemize @bullet
26455 @item
26456 Windows executables that run in Ring 3 to utilize memory protection
26457 (@emph{rts-rtx-w32}).
26458
26459 @item
26460 Real-time subsystem (RTSS) executables that run in Ring 0, where
26461 performance can be optimized with RTSS applications taking precedent
26462 over all Windows applications (@emph{rts-rtx-rtss}).
26463
26464 @end itemize
26465
26466 @c *******************************
26467 @node Example of Binder Output File
26468 @appendix Example of Binder Output File
26469
26470 @noindent
26471 This Appendix displays the source code for @command{gnatbind}'s output
26472 file generated for a simple ``Hello World'' program.
26473 Comments have been added for clarification purposes.
26474
26475 @smallexample @c adanocomment
26476 @iftex
26477 @leftskip=0cm
26478 @end iftex
26479 --  The package is called Ada_Main unless this name is actually used
26480 --  as a unit name in the partition, in which case some other unique
26481 --  name is used.
26482
26483 with System;
26484 package ada_main is
26485
26486    Elab_Final_Code : Integer;
26487    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26488
26489    --  The main program saves the parameters (argument count,
26490    --  argument values, environment pointer) in global variables
26491    --  for later access by other units including
26492    --  Ada.Command_Line.
26493
26494    gnat_argc : Integer;
26495    gnat_argv : System.Address;
26496    gnat_envp : System.Address;
26497
26498    --  The actual variables are stored in a library routine. This
26499    --  is useful for some shared library situations, where there
26500    --  are problems if variables are not in the library.
26501
26502    pragma Import (C, gnat_argc);
26503    pragma Import (C, gnat_argv);
26504    pragma Import (C, gnat_envp);
26505
26506    --  The exit status is similarly an external location
26507
26508    gnat_exit_status : Integer;
26509    pragma Import (C, gnat_exit_status);
26510
26511    GNAT_Version : constant String :=
26512                     "GNAT Version: 6.0.0w (20061115)";
26513    pragma Export (C, GNAT_Version, "__gnat_version");
26514
26515    --  This is the generated adafinal routine that performs
26516    --  finalization at the end of execution. In the case where
26517    --  Ada is the main program, this main program makes a call
26518    --  to adafinal at program termination.
26519
26520    procedure adafinal;
26521    pragma Export (C, adafinal, "adafinal");
26522
26523    --  This is the generated adainit routine that performs
26524    --  initialization at the start of execution. In the case
26525    --  where Ada is the main program, this main program makes
26526    --  a call to adainit at program startup.
26527
26528    procedure adainit;
26529    pragma Export (C, adainit, "adainit");
26530
26531    --  This routine is called at the start of execution. It is
26532    --  a dummy routine that is used by the debugger to breakpoint
26533    --  at the start of execution.
26534
26535    procedure Break_Start;
26536    pragma Import (C, Break_Start, "__gnat_break_start");
26537
26538    --  This is the actual generated main program (it would be
26539    --  suppressed if the no main program switch were used). As
26540    --  required by standard system conventions, this program has
26541    --  the external name main.
26542
26543    function main
26544      (argc : Integer;
26545       argv : System.Address;
26546       envp : System.Address)
26547       return Integer;
26548    pragma Export (C, main, "main");
26549
26550    --  The following set of constants give the version
26551    --  identification values for every unit in the bound
26552    --  partition. This identification is computed from all
26553    --  dependent semantic units, and corresponds to the
26554    --  string that would be returned by use of the
26555    --  Body_Version or Version attributes.
26556
26557    type Version_32 is mod 2 ** 32;
26558    u00001 : constant Version_32 := 16#7880BEB3#;
26559    u00002 : constant Version_32 := 16#0D24CBD0#;
26560    u00003 : constant Version_32 := 16#3283DBEB#;
26561    u00004 : constant Version_32 := 16#2359F9ED#;
26562    u00005 : constant Version_32 := 16#664FB847#;
26563    u00006 : constant Version_32 := 16#68E803DF#;
26564    u00007 : constant Version_32 := 16#5572E604#;
26565    u00008 : constant Version_32 := 16#46B173D8#;
26566    u00009 : constant Version_32 := 16#156A40CF#;
26567    u00010 : constant Version_32 := 16#033DABE0#;
26568    u00011 : constant Version_32 := 16#6AB38FEA#;
26569    u00012 : constant Version_32 := 16#22B6217D#;
26570    u00013 : constant Version_32 := 16#68A22947#;
26571    u00014 : constant Version_32 := 16#18CC4A56#;
26572    u00015 : constant Version_32 := 16#08258E1B#;
26573    u00016 : constant Version_32 := 16#367D5222#;
26574    u00017 : constant Version_32 := 16#20C9ECA4#;
26575    u00018 : constant Version_32 := 16#50D32CB6#;
26576    u00019 : constant Version_32 := 16#39A8BB77#;
26577    u00020 : constant Version_32 := 16#5CF8FA2B#;
26578    u00021 : constant Version_32 := 16#2F1EB794#;
26579    u00022 : constant Version_32 := 16#31AB6444#;
26580    u00023 : constant Version_32 := 16#1574B6E9#;
26581    u00024 : constant Version_32 := 16#5109C189#;
26582    u00025 : constant Version_32 := 16#56D770CD#;
26583    u00026 : constant Version_32 := 16#02F9DE3D#;
26584    u00027 : constant Version_32 := 16#08AB6B2C#;
26585    u00028 : constant Version_32 := 16#3FA37670#;
26586    u00029 : constant Version_32 := 16#476457A0#;
26587    u00030 : constant Version_32 := 16#731E1B6E#;
26588    u00031 : constant Version_32 := 16#23C2E789#;
26589    u00032 : constant Version_32 := 16#0F1BD6A1#;
26590    u00033 : constant Version_32 := 16#7C25DE96#;
26591    u00034 : constant Version_32 := 16#39ADFFA2#;
26592    u00035 : constant Version_32 := 16#571DE3E7#;
26593    u00036 : constant Version_32 := 16#5EB646AB#;
26594    u00037 : constant Version_32 := 16#4249379B#;
26595    u00038 : constant Version_32 := 16#0357E00A#;
26596    u00039 : constant Version_32 := 16#3784FB72#;
26597    u00040 : constant Version_32 := 16#2E723019#;
26598    u00041 : constant Version_32 := 16#623358EA#;
26599    u00042 : constant Version_32 := 16#107F9465#;
26600    u00043 : constant Version_32 := 16#6843F68A#;
26601    u00044 : constant Version_32 := 16#63305874#;
26602    u00045 : constant Version_32 := 16#31E56CE1#;
26603    u00046 : constant Version_32 := 16#02917970#;
26604    u00047 : constant Version_32 := 16#6CCBA70E#;
26605    u00048 : constant Version_32 := 16#41CD4204#;
26606    u00049 : constant Version_32 := 16#572E3F58#;
26607    u00050 : constant Version_32 := 16#20729FF5#;
26608    u00051 : constant Version_32 := 16#1D4F93E8#;
26609    u00052 : constant Version_32 := 16#30B2EC3D#;
26610    u00053 : constant Version_32 := 16#34054F96#;
26611    u00054 : constant Version_32 := 16#5A199860#;
26612    u00055 : constant Version_32 := 16#0E7F912B#;
26613    u00056 : constant Version_32 := 16#5760634A#;
26614    u00057 : constant Version_32 := 16#5D851835#;
26615
26616    --  The following Export pragmas export the version numbers
26617    --  with symbolic names ending in B (for body) or S
26618    --  (for spec) so that they can be located in a link. The
26619    --  information provided here is sufficient to track down
26620    --  the exact versions of units used in a given build.
26621
26622    pragma Export (C, u00001, "helloB");
26623    pragma Export (C, u00002, "system__standard_libraryB");
26624    pragma Export (C, u00003, "system__standard_libraryS");
26625    pragma Export (C, u00004, "adaS");
26626    pragma Export (C, u00005, "ada__text_ioB");
26627    pragma Export (C, u00006, "ada__text_ioS");
26628    pragma Export (C, u00007, "ada__exceptionsB");
26629    pragma Export (C, u00008, "ada__exceptionsS");
26630    pragma Export (C, u00009, "gnatS");
26631    pragma Export (C, u00010, "gnat__heap_sort_aB");
26632    pragma Export (C, u00011, "gnat__heap_sort_aS");
26633    pragma Export (C, u00012, "systemS");
26634    pragma Export (C, u00013, "system__exception_tableB");
26635    pragma Export (C, u00014, "system__exception_tableS");
26636    pragma Export (C, u00015, "gnat__htableB");
26637    pragma Export (C, u00016, "gnat__htableS");
26638    pragma Export (C, u00017, "system__exceptionsS");
26639    pragma Export (C, u00018, "system__machine_state_operationsB");
26640    pragma Export (C, u00019, "system__machine_state_operationsS");
26641    pragma Export (C, u00020, "system__machine_codeS");
26642    pragma Export (C, u00021, "system__storage_elementsB");
26643    pragma Export (C, u00022, "system__storage_elementsS");
26644    pragma Export (C, u00023, "system__secondary_stackB");
26645    pragma Export (C, u00024, "system__secondary_stackS");
26646    pragma Export (C, u00025, "system__parametersB");
26647    pragma Export (C, u00026, "system__parametersS");
26648    pragma Export (C, u00027, "system__soft_linksB");
26649    pragma Export (C, u00028, "system__soft_linksS");
26650    pragma Export (C, u00029, "system__stack_checkingB");
26651    pragma Export (C, u00030, "system__stack_checkingS");
26652    pragma Export (C, u00031, "system__tracebackB");
26653    pragma Export (C, u00032, "system__tracebackS");
26654    pragma Export (C, u00033, "ada__streamsS");
26655    pragma Export (C, u00034, "ada__tagsB");
26656    pragma Export (C, u00035, "ada__tagsS");
26657    pragma Export (C, u00036, "system__string_opsB");
26658    pragma Export (C, u00037, "system__string_opsS");
26659    pragma Export (C, u00038, "interfacesS");
26660    pragma Export (C, u00039, "interfaces__c_streamsB");
26661    pragma Export (C, u00040, "interfaces__c_streamsS");
26662    pragma Export (C, u00041, "system__file_ioB");
26663    pragma Export (C, u00042, "system__file_ioS");
26664    pragma Export (C, u00043, "ada__finalizationB");
26665    pragma Export (C, u00044, "ada__finalizationS");
26666    pragma Export (C, u00045, "system__finalization_rootB");
26667    pragma Export (C, u00046, "system__finalization_rootS");
26668    pragma Export (C, u00047, "system__finalization_implementationB");
26669    pragma Export (C, u00048, "system__finalization_implementationS");
26670    pragma Export (C, u00049, "system__string_ops_concat_3B");
26671    pragma Export (C, u00050, "system__string_ops_concat_3S");
26672    pragma Export (C, u00051, "system__stream_attributesB");
26673    pragma Export (C, u00052, "system__stream_attributesS");
26674    pragma Export (C, u00053, "ada__io_exceptionsS");
26675    pragma Export (C, u00054, "system__unsigned_typesS");
26676    pragma Export (C, u00055, "system__file_control_blockS");
26677    pragma Export (C, u00056, "ada__finalization__list_controllerB");
26678    pragma Export (C, u00057, "ada__finalization__list_controllerS");
26679
26680    -- BEGIN ELABORATION ORDER
26681    -- ada (spec)
26682    -- gnat (spec)
26683    -- gnat.heap_sort_a (spec)
26684    -- gnat.heap_sort_a (body)
26685    -- gnat.htable (spec)
26686    -- gnat.htable (body)
26687    -- interfaces (spec)
26688    -- system (spec)
26689    -- system.machine_code (spec)
26690    -- system.parameters (spec)
26691    -- system.parameters (body)
26692    -- interfaces.c_streams (spec)
26693    -- interfaces.c_streams (body)
26694    -- system.standard_library (spec)
26695    -- ada.exceptions (spec)
26696    -- system.exception_table (spec)
26697    -- system.exception_table (body)
26698    -- ada.io_exceptions (spec)
26699    -- system.exceptions (spec)
26700    -- system.storage_elements (spec)
26701    -- system.storage_elements (body)
26702    -- system.machine_state_operations (spec)
26703    -- system.machine_state_operations (body)
26704    -- system.secondary_stack (spec)
26705    -- system.stack_checking (spec)
26706    -- system.soft_links (spec)
26707    -- system.soft_links (body)
26708    -- system.stack_checking (body)
26709    -- system.secondary_stack (body)
26710    -- system.standard_library (body)
26711    -- system.string_ops (spec)
26712    -- system.string_ops (body)
26713    -- ada.tags (spec)
26714    -- ada.tags (body)
26715    -- ada.streams (spec)
26716    -- system.finalization_root (spec)
26717    -- system.finalization_root (body)
26718    -- system.string_ops_concat_3 (spec)
26719    -- system.string_ops_concat_3 (body)
26720    -- system.traceback (spec)
26721    -- system.traceback (body)
26722    -- ada.exceptions (body)
26723    -- system.unsigned_types (spec)
26724    -- system.stream_attributes (spec)
26725    -- system.stream_attributes (body)
26726    -- system.finalization_implementation (spec)
26727    -- system.finalization_implementation (body)
26728    -- ada.finalization (spec)
26729    -- ada.finalization (body)
26730    -- ada.finalization.list_controller (spec)
26731    -- ada.finalization.list_controller (body)
26732    -- system.file_control_block (spec)
26733    -- system.file_io (spec)
26734    -- system.file_io (body)
26735    -- ada.text_io (spec)
26736    -- ada.text_io (body)
26737    -- hello (body)
26738    -- END ELABORATION ORDER
26739
26740 end ada_main;
26741
26742 --  The following source file name pragmas allow the generated file
26743 --  names to be unique for different main programs. They are needed
26744 --  since the package name will always be Ada_Main.
26745
26746 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26747 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26748
26749 --  Generated package body for Ada_Main starts here
26750
26751 package body ada_main is
26752
26753    --  The actual finalization is performed by calling the
26754    --  library routine in System.Standard_Library.Adafinal
26755
26756    procedure Do_Finalize;
26757    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26758
26759    -------------
26760    -- adainit --
26761    -------------
26762
26763 @findex adainit
26764    procedure adainit is
26765
26766       --  These booleans are set to True once the associated unit has
26767       --  been elaborated. It is also used to avoid elaborating the
26768       --  same unit twice.
26769
26770       E040 : Boolean;
26771       pragma Import (Ada, E040, "interfaces__c_streams_E");
26772
26773       E008 : Boolean;
26774       pragma Import (Ada, E008, "ada__exceptions_E");
26775
26776       E014 : Boolean;
26777       pragma Import (Ada, E014, "system__exception_table_E");
26778
26779       E053 : Boolean;
26780       pragma Import (Ada, E053, "ada__io_exceptions_E");
26781
26782       E017 : Boolean;
26783       pragma Import (Ada, E017, "system__exceptions_E");
26784
26785       E024 : Boolean;
26786       pragma Import (Ada, E024, "system__secondary_stack_E");
26787
26788       E030 : Boolean;
26789       pragma Import (Ada, E030, "system__stack_checking_E");
26790
26791       E028 : Boolean;
26792       pragma Import (Ada, E028, "system__soft_links_E");
26793
26794       E035 : Boolean;
26795       pragma Import (Ada, E035, "ada__tags_E");
26796
26797       E033 : Boolean;
26798       pragma Import (Ada, E033, "ada__streams_E");
26799
26800       E046 : Boolean;
26801       pragma Import (Ada, E046, "system__finalization_root_E");
26802
26803       E048 : Boolean;
26804       pragma Import (Ada, E048, "system__finalization_implementation_E");
26805
26806       E044 : Boolean;
26807       pragma Import (Ada, E044, "ada__finalization_E");
26808
26809       E057 : Boolean;
26810       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26811
26812       E055 : Boolean;
26813       pragma Import (Ada, E055, "system__file_control_block_E");
26814
26815       E042 : Boolean;
26816       pragma Import (Ada, E042, "system__file_io_E");
26817
26818       E006 : Boolean;
26819       pragma Import (Ada, E006, "ada__text_io_E");
26820
26821       --  Set_Globals is a library routine that stores away the
26822       --  value of the indicated set of global values in global
26823       --  variables within the library.
26824
26825       procedure Set_Globals
26826         (Main_Priority            : Integer;
26827          Time_Slice_Value         : Integer;
26828          WC_Encoding              : Character;
26829          Locking_Policy           : Character;
26830          Queuing_Policy           : Character;
26831          Task_Dispatching_Policy  : Character;
26832          Adafinal                 : System.Address;
26833          Unreserve_All_Interrupts : Integer;
26834          Exception_Tracebacks     : Integer);
26835 @findex __gnat_set_globals
26836       pragma Import (C, Set_Globals, "__gnat_set_globals");
26837
26838       --  SDP_Table_Build is a library routine used to build the
26839       --  exception tables. See unit Ada.Exceptions in files
26840       --  a-except.ads/adb for full details of how zero cost
26841       --  exception handling works. This procedure, the call to
26842       --  it, and the two following tables are all omitted if the
26843       --  build is in longjmp/setjmp exception mode.
26844
26845 @findex SDP_Table_Build
26846 @findex Zero Cost Exceptions
26847       procedure SDP_Table_Build
26848         (SDP_Addresses   : System.Address;
26849          SDP_Count       : Natural;
26850          Elab_Addresses  : System.Address;
26851          Elab_Addr_Count : Natural);
26852       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26853
26854       --  Table of Unit_Exception_Table addresses. Used for zero
26855       --  cost exception handling to build the top level table.
26856
26857       ST : aliased constant array (1 .. 23) of System.Address := (
26858         Hello'UET_Address,
26859         Ada.Text_Io'UET_Address,
26860         Ada.Exceptions'UET_Address,
26861         Gnat.Heap_Sort_A'UET_Address,
26862         System.Exception_Table'UET_Address,
26863         System.Machine_State_Operations'UET_Address,
26864         System.Secondary_Stack'UET_Address,
26865         System.Parameters'UET_Address,
26866         System.Soft_Links'UET_Address,
26867         System.Stack_Checking'UET_Address,
26868         System.Traceback'UET_Address,
26869         Ada.Streams'UET_Address,
26870         Ada.Tags'UET_Address,
26871         System.String_Ops'UET_Address,
26872         Interfaces.C_Streams'UET_Address,
26873         System.File_Io'UET_Address,
26874         Ada.Finalization'UET_Address,
26875         System.Finalization_Root'UET_Address,
26876         System.Finalization_Implementation'UET_Address,
26877         System.String_Ops_Concat_3'UET_Address,
26878         System.Stream_Attributes'UET_Address,
26879         System.File_Control_Block'UET_Address,
26880         Ada.Finalization.List_Controller'UET_Address);
26881
26882       --  Table of addresses of elaboration routines. Used for
26883       --  zero cost exception handling to make sure these
26884       --  addresses are included in the top level procedure
26885       --  address table.
26886
26887       EA : aliased constant array (1 .. 23) of System.Address := (
26888         adainit'Code_Address,
26889         Do_Finalize'Code_Address,
26890         Ada.Exceptions'Elab_Spec'Address,
26891         System.Exceptions'Elab_Spec'Address,
26892         Interfaces.C_Streams'Elab_Spec'Address,
26893         System.Exception_Table'Elab_Body'Address,
26894         Ada.Io_Exceptions'Elab_Spec'Address,
26895         System.Stack_Checking'Elab_Spec'Address,
26896         System.Soft_Links'Elab_Body'Address,
26897         System.Secondary_Stack'Elab_Body'Address,
26898         Ada.Tags'Elab_Spec'Address,
26899         Ada.Tags'Elab_Body'Address,
26900         Ada.Streams'Elab_Spec'Address,
26901         System.Finalization_Root'Elab_Spec'Address,
26902         Ada.Exceptions'Elab_Body'Address,
26903         System.Finalization_Implementation'Elab_Spec'Address,
26904         System.Finalization_Implementation'Elab_Body'Address,
26905         Ada.Finalization'Elab_Spec'Address,
26906         Ada.Finalization.List_Controller'Elab_Spec'Address,
26907         System.File_Control_Block'Elab_Spec'Address,
26908         System.File_Io'Elab_Body'Address,
26909         Ada.Text_Io'Elab_Spec'Address,
26910         Ada.Text_Io'Elab_Body'Address);
26911
26912    --  Start of processing for adainit
26913
26914    begin
26915
26916       --  Call SDP_Table_Build to build the top level procedure
26917       --  table for zero cost exception handling (omitted in
26918       --  longjmp/setjmp mode).
26919
26920       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26921
26922       --  Call Set_Globals to record various information for
26923       --  this partition.  The values are derived by the binder
26924       --  from information stored in the ali files by the compiler.
26925
26926 @findex __gnat_set_globals
26927       Set_Globals
26928         (Main_Priority            => -1,
26929          --  Priority of main program, -1 if no pragma Priority used
26930
26931          Time_Slice_Value         => -1,
26932          --  Time slice from Time_Slice pragma, -1 if none used
26933
26934          WC_Encoding              => 'b',
26935          --  Wide_Character encoding used, default is brackets
26936
26937          Locking_Policy           => ' ',
26938          --  Locking_Policy used, default of space means not
26939          --  specified, otherwise it is the first character of
26940          --  the policy name.
26941
26942          Queuing_Policy           => ' ',
26943          --  Queuing_Policy used, default of space means not
26944          --  specified, otherwise it is the first character of
26945          --  the policy name.
26946
26947          Task_Dispatching_Policy  => ' ',
26948          --  Task_Dispatching_Policy used, default of space means
26949          --  not specified, otherwise first character of the
26950          --  policy name.
26951
26952          Adafinal                 => System.Null_Address,
26953          --  Address of Adafinal routine, not used anymore
26954
26955          Unreserve_All_Interrupts => 0,
26956          --  Set true if pragma Unreserve_All_Interrupts was used
26957
26958          Exception_Tracebacks     => 0);
26959          --  Indicates if exception tracebacks are enabled
26960
26961       Elab_Final_Code := 1;
26962
26963       --  Now we have the elaboration calls for all units in the partition.
26964       --  The Elab_Spec and Elab_Body attributes generate references to the
26965       --  implicit elaboration procedures generated by the compiler for
26966       --  each unit that requires elaboration.
26967
26968       if not E040 then
26969          Interfaces.C_Streams'Elab_Spec;
26970       end if;
26971       E040 := True;
26972       if not E008 then
26973          Ada.Exceptions'Elab_Spec;
26974       end if;
26975       if not E014 then
26976          System.Exception_Table'Elab_Body;
26977          E014 := True;
26978       end if;
26979       if not E053 then
26980          Ada.Io_Exceptions'Elab_Spec;
26981          E053 := True;
26982       end if;
26983       if not E017 then
26984          System.Exceptions'Elab_Spec;
26985          E017 := True;
26986       end if;
26987       if not E030 then
26988          System.Stack_Checking'Elab_Spec;
26989       end if;
26990       if not E028 then
26991          System.Soft_Links'Elab_Body;
26992          E028 := True;
26993       end if;
26994       E030 := True;
26995       if not E024 then
26996          System.Secondary_Stack'Elab_Body;
26997          E024 := True;
26998       end if;
26999       if not E035 then
27000          Ada.Tags'Elab_Spec;
27001       end if;
27002       if not E035 then
27003          Ada.Tags'Elab_Body;
27004          E035 := True;
27005       end if;
27006       if not E033 then
27007          Ada.Streams'Elab_Spec;
27008          E033 := True;
27009       end if;
27010       if not E046 then
27011          System.Finalization_Root'Elab_Spec;
27012       end if;
27013       E046 := True;
27014       if not E008 then
27015          Ada.Exceptions'Elab_Body;
27016          E008 := True;
27017       end if;
27018       if not E048 then
27019          System.Finalization_Implementation'Elab_Spec;
27020       end if;
27021       if not E048 then
27022          System.Finalization_Implementation'Elab_Body;
27023          E048 := True;
27024       end if;
27025       if not E044 then
27026          Ada.Finalization'Elab_Spec;
27027       end if;
27028       E044 := True;
27029       if not E057 then
27030          Ada.Finalization.List_Controller'Elab_Spec;
27031       end if;
27032       E057 := True;
27033       if not E055 then
27034          System.File_Control_Block'Elab_Spec;
27035          E055 := True;
27036       end if;
27037       if not E042 then
27038          System.File_Io'Elab_Body;
27039          E042 := True;
27040       end if;
27041       if not E006 then
27042          Ada.Text_Io'Elab_Spec;
27043       end if;
27044       if not E006 then
27045          Ada.Text_Io'Elab_Body;
27046          E006 := True;
27047       end if;
27048
27049       Elab_Final_Code := 0;
27050    end adainit;
27051
27052    --------------
27053    -- adafinal --
27054    --------------
27055
27056 @findex adafinal
27057    procedure adafinal is
27058    begin
27059       Do_Finalize;
27060    end adafinal;
27061
27062    ----------
27063    -- main --
27064    ----------
27065
27066    --  main is actually a function, as in the ANSI C standard,
27067    --  defined to return the exit status. The three parameters
27068    --  are the argument count, argument values and environment
27069    --  pointer.
27070
27071 @findex Main Program
27072    function main
27073      (argc : Integer;
27074       argv : System.Address;
27075       envp : System.Address)
27076       return Integer
27077    is
27078       --  The initialize routine performs low level system
27079       --  initialization using a standard library routine which
27080       --  sets up signal handling and performs any other
27081       --  required setup. The routine can be found in file
27082       --  a-init.c.
27083
27084 @findex __gnat_initialize
27085       procedure initialize;
27086       pragma Import (C, initialize, "__gnat_initialize");
27087
27088       --  The finalize routine performs low level system
27089       --  finalization using a standard library routine. The
27090       --  routine is found in file a-final.c and in the standard
27091       --  distribution is a dummy routine that does nothing, so
27092       --  really this is a hook for special user finalization.
27093
27094 @findex __gnat_finalize
27095       procedure finalize;
27096       pragma Import (C, finalize, "__gnat_finalize");
27097
27098       --  We get to the main program of the partition by using
27099       --  pragma Import because if we try to with the unit and
27100       --  call it Ada style, then not only do we waste time
27101       --  recompiling it, but also, we don't really know the right
27102       --  switches (e.g.@: identifier character set) to be used
27103       --  to compile it.
27104
27105       procedure Ada_Main_Program;
27106       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27107
27108    --  Start of processing for main
27109
27110    begin
27111       --  Save global variables
27112
27113       gnat_argc := argc;
27114       gnat_argv := argv;
27115       gnat_envp := envp;
27116
27117       --  Call low level system initialization
27118
27119       Initialize;
27120
27121       --  Call our generated Ada initialization routine
27122
27123       adainit;
27124
27125       --  This is the point at which we want the debugger to get
27126       --  control
27127
27128       Break_Start;
27129
27130       --  Now we call the main program of the partition
27131
27132       Ada_Main_Program;
27133
27134       --  Perform Ada finalization
27135
27136       adafinal;
27137
27138       --  Perform low level system finalization
27139
27140       Finalize;
27141
27142       --  Return the proper exit status
27143       return (gnat_exit_status);
27144    end;
27145
27146 --  This section is entirely comments, so it has no effect on the
27147 --  compilation of the Ada_Main package. It provides the list of
27148 --  object files and linker options, as well as some standard
27149 --  libraries needed for the link. The gnatlink utility parses
27150 --  this b~hello.adb file to read these comment lines to generate
27151 --  the appropriate command line arguments for the call to the
27152 --  system linker. The BEGIN/END lines are used for sentinels for
27153 --  this parsing operation.
27154
27155 --  The exact file names will of course depend on the environment,
27156 --  host/target and location of files on the host system.
27157
27158 @findex Object file list
27159 -- BEGIN Object file/option list
27160    --   ./hello.o
27161    --   -L./
27162    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27163    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27164 -- END Object file/option list
27165
27166 end ada_main;
27167 @end smallexample
27168
27169 @noindent
27170 The Ada code in the above example is exactly what is generated by the
27171 binder. We have added comments to more clearly indicate the function
27172 of each part of the generated @code{Ada_Main} package.
27173
27174 The code is standard Ada in all respects, and can be processed by any
27175 tools that handle Ada. In particular, it is possible to use the debugger
27176 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27177 suppose that for reasons that you do not understand, your program is crashing
27178 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27179 you can place a breakpoint on the call:
27180
27181 @smallexample @c ada
27182 Ada.Text_Io'Elab_Body;
27183 @end smallexample
27184
27185 @noindent
27186 and trace the elaboration routine for this package to find out where
27187 the problem might be (more usually of course you would be debugging
27188 elaboration code in your own application).
27189
27190 @node Elaboration Order Handling in GNAT
27191 @appendix Elaboration Order Handling in GNAT
27192 @cindex Order of elaboration
27193 @cindex Elaboration control
27194
27195 @menu
27196 * Elaboration Code::
27197 * Checking the Elaboration Order::
27198 * Controlling the Elaboration Order::
27199 * Controlling Elaboration in GNAT - Internal Calls::
27200 * Controlling Elaboration in GNAT - External Calls::
27201 * Default Behavior in GNAT - Ensuring Safety::
27202 * Treatment of Pragma Elaborate::
27203 * Elaboration Issues for Library Tasks::
27204 * Mixing Elaboration Models::
27205 * What to Do If the Default Elaboration Behavior Fails::
27206 * Elaboration for Access-to-Subprogram Values::
27207 * Summary of Procedures for Elaboration Control::
27208 * Other Elaboration Order Considerations::
27209 @end menu
27210
27211 @noindent
27212 This chapter describes the handling of elaboration code in Ada and
27213 in GNAT, and discusses how the order of elaboration of program units can
27214 be controlled in GNAT, either automatically or with explicit programming
27215 features.
27216
27217 @node Elaboration Code
27218 @section Elaboration Code
27219
27220 @noindent
27221 Ada provides rather general mechanisms for executing code at elaboration
27222 time, that is to say before the main program starts executing. Such code arises
27223 in three contexts:
27224
27225 @table @asis
27226 @item Initializers for variables.
27227 Variables declared at the library level, in package specs or bodies, can
27228 require initialization that is performed at elaboration time, as in:
27229 @smallexample @c ada
27230 @cartouche
27231 Sqrt_Half : Float := Sqrt (0.5);
27232 @end cartouche
27233 @end smallexample
27234
27235 @item Package initialization code
27236 Code in a @code{BEGIN-END} section at the outer level of a package body is
27237 executed as part of the package body elaboration code.
27238
27239 @item Library level task allocators
27240 Tasks that are declared using task allocators at the library level
27241 start executing immediately and hence can execute at elaboration time.
27242 @end table
27243
27244 @noindent
27245 Subprogram calls are possible in any of these contexts, which means that
27246 any arbitrary part of the program may be executed as part of the elaboration
27247 code. It is even possible to write a program which does all its work at
27248 elaboration time, with a null main program, although stylistically this
27249 would usually be considered an inappropriate way to structure
27250 a program.
27251
27252 An important concern arises in the context of elaboration code:
27253 we have to be sure that it is executed in an appropriate order. What we
27254 have is a series of elaboration code sections, potentially one section
27255 for each unit in the program. It is important that these execute
27256 in the correct order. Correctness here means that, taking the above
27257 example of the declaration of @code{Sqrt_Half},
27258 if some other piece of
27259 elaboration code references @code{Sqrt_Half},
27260 then it must run after the
27261 section of elaboration code that contains the declaration of
27262 @code{Sqrt_Half}.
27263
27264 There would never be any order of elaboration problem if we made a rule
27265 that whenever you @code{with} a unit, you must elaborate both the spec and body
27266 of that unit before elaborating the unit doing the @code{with}'ing:
27267
27268 @smallexample @c ada
27269 @group
27270 @cartouche
27271 with Unit_1;
27272 package Unit_2 is @dots{}
27273 @end cartouche
27274 @end group
27275 @end smallexample
27276
27277 @noindent
27278 would require that both the body and spec of @code{Unit_1} be elaborated
27279 before the spec of @code{Unit_2}. However, a rule like that would be far too
27280 restrictive. In particular, it would make it impossible to have routines
27281 in separate packages that were mutually recursive.
27282
27283 You might think that a clever enough compiler could look at the actual
27284 elaboration code and determine an appropriate correct order of elaboration,
27285 but in the general case, this is not possible. Consider the following
27286 example.
27287
27288 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27289 that references
27290 the variable @code{Sqrt_1}, which is declared in the elaboration code
27291 of the body of @code{Unit_1}:
27292
27293 @smallexample @c ada
27294 @cartouche
27295 Sqrt_1 : Float := Sqrt (0.1);
27296 @end cartouche
27297 @end smallexample
27298
27299 @noindent
27300 The elaboration code of the body of @code{Unit_1} also contains:
27301
27302 @smallexample @c ada
27303 @group
27304 @cartouche
27305 if expression_1 = 1 then
27306    Q := Unit_2.Func_2;
27307 end if;
27308 @end cartouche
27309 @end group
27310 @end smallexample
27311
27312 @noindent
27313 @code{Unit_2} is exactly parallel,
27314 it has a procedure @code{Func_2} that references
27315 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27316 the body @code{Unit_2}:
27317
27318 @smallexample @c ada
27319 @cartouche
27320 Sqrt_2 : Float := Sqrt (0.1);
27321 @end cartouche
27322 @end smallexample
27323
27324 @noindent
27325 The elaboration code of the body of @code{Unit_2} also contains:
27326
27327 @smallexample @c ada
27328 @group
27329 @cartouche
27330 if expression_2 = 2 then
27331    Q := Unit_1.Func_1;
27332 end if;
27333 @end cartouche
27334 @end group
27335 @end smallexample
27336
27337 @noindent
27338 Now the question is, which of the following orders of elaboration is
27339 acceptable:
27340
27341 @smallexample
27342 @group
27343 Spec of Unit_1
27344 Spec of Unit_2
27345 Body of Unit_1
27346 Body of Unit_2
27347 @end group
27348 @end smallexample
27349
27350 @noindent
27351 or
27352
27353 @smallexample
27354 @group
27355 Spec of Unit_2
27356 Spec of Unit_1
27357 Body of Unit_2
27358 Body of Unit_1
27359 @end group
27360 @end smallexample
27361
27362 @noindent
27363 If you carefully analyze the flow here, you will see that you cannot tell
27364 at compile time the answer to this question.
27365 If @code{expression_1} is not equal to 1,
27366 and @code{expression_2} is not equal to 2,
27367 then either order is acceptable, because neither of the function calls is
27368 executed. If both tests evaluate to true, then neither order is acceptable
27369 and in fact there is no correct order.
27370
27371 If one of the two expressions is true, and the other is false, then one
27372 of the above orders is correct, and the other is incorrect. For example,
27373 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27374 then the call to @code{Func_1}
27375 will occur, but not the call to @code{Func_2.}
27376 This means that it is essential
27377 to elaborate the body of @code{Unit_1} before
27378 the body of @code{Unit_2}, so the first
27379 order of elaboration is correct and the second is wrong.
27380
27381 By making @code{expression_1} and @code{expression_2}
27382 depend on input data, or perhaps
27383 the time of day, we can make it impossible for the compiler or binder
27384 to figure out which of these expressions will be true, and hence it
27385 is impossible to guarantee a safe order of elaboration at run time.
27386
27387 @node Checking the Elaboration Order
27388 @section Checking the Elaboration Order
27389
27390 @noindent
27391 In some languages that involve the same kind of elaboration problems,
27392 e.g.@: Java and C++, the programmer is expected to worry about these
27393 ordering problems himself, and it is common to
27394 write a program in which an incorrect elaboration order  gives
27395 surprising results, because it references variables before they
27396 are initialized.
27397 Ada is designed to be a safe language, and a programmer-beware approach is
27398 clearly not sufficient. Consequently, the language provides three lines
27399 of defense:
27400
27401 @table @asis
27402 @item Standard rules
27403 Some standard rules restrict the possible choice of elaboration
27404 order. In particular, if you @code{with} a unit, then its spec is always
27405 elaborated before the unit doing the @code{with}. Similarly, a parent
27406 spec is always elaborated before the child spec, and finally
27407 a spec is always elaborated before its corresponding body.
27408
27409 @item Dynamic elaboration checks
27410 @cindex Elaboration checks
27411 @cindex Checks, elaboration
27412 Dynamic checks are made at run time, so that if some entity is accessed
27413 before it is elaborated (typically  by means of a subprogram call)
27414 then the exception (@code{Program_Error}) is raised.
27415
27416 @item Elaboration control
27417 Facilities are provided for the programmer to specify the desired order
27418 of elaboration.
27419 @end table
27420
27421 Let's look at these facilities in more detail. First, the rules for
27422 dynamic checking. One possible rule would be simply to say that the
27423 exception is raised if you access a variable which has not yet been
27424 elaborated. The trouble with this approach is that it could require
27425 expensive checks on every variable reference. Instead Ada has two
27426 rules which are a little more restrictive, but easier to check, and
27427 easier to state:
27428
27429 @table @asis
27430 @item Restrictions on calls
27431 A subprogram can only be called at elaboration time if its body
27432 has been elaborated. The rules for elaboration given above guarantee
27433 that the spec of the subprogram has been elaborated before the
27434 call, but not the body. If this rule is violated, then the
27435 exception @code{Program_Error} is raised.
27436
27437 @item Restrictions on instantiations
27438 A generic unit can only be instantiated if the body of the generic
27439 unit has been elaborated. Again, the rules for elaboration given above
27440 guarantee that the spec of the generic unit has been elaborated
27441 before the instantiation, but not the body. If this rule is
27442 violated, then the exception @code{Program_Error} is raised.
27443 @end table
27444
27445 @noindent
27446 The idea is that if the body has been elaborated, then any variables
27447 it references must have been elaborated; by checking for the body being
27448 elaborated we guarantee that none of its references causes any
27449 trouble. As we noted above, this is a little too restrictive, because a
27450 subprogram that has no non-local references in its body may in fact be safe
27451 to call. However, it really would be unsafe to rely on this, because
27452 it would mean that the caller was aware of details of the implementation
27453 in the body. This goes against the basic tenets of Ada.
27454
27455 A plausible implementation can be described as follows.
27456 A Boolean variable is associated with each subprogram
27457 and each generic unit. This variable is initialized to False, and is set to
27458 True at the point body is elaborated. Every call or instantiation checks the
27459 variable, and raises @code{Program_Error} if the variable is False.
27460
27461 Note that one might think that it would be good enough to have one Boolean
27462 variable for each package, but that would not deal with cases of trying
27463 to call a body in the same package as the call
27464 that has not been elaborated yet.
27465 Of course a compiler may be able to do enough analysis to optimize away
27466 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27467 does such optimizations, but still the easiest conceptual model is to
27468 think of there being one variable per subprogram.
27469
27470 @node Controlling the Elaboration Order
27471 @section Controlling the Elaboration Order
27472
27473 @noindent
27474 In the previous section we discussed the rules in Ada which ensure
27475 that @code{Program_Error} is raised if an incorrect elaboration order is
27476 chosen. This prevents erroneous executions, but we need mechanisms to
27477 specify a correct execution and avoid the exception altogether.
27478 To achieve this, Ada provides a number of features for controlling
27479 the order of elaboration. We discuss these features in this section.
27480
27481 First, there are several ways of indicating to the compiler that a given
27482 unit has no elaboration problems:
27483
27484 @table @asis
27485 @item packages that do not require a body
27486 A library package that does not require a body does not permit
27487 a body (this rule was introduced in Ada 95).
27488 Thus if we have a such a package, as in:
27489
27490 @smallexample @c ada
27491 @group
27492 @cartouche
27493 package Definitions is
27494    generic
27495       type m is new integer;
27496    package Subp is
27497       type a is array (1 .. 10) of m;
27498       type b is array (1 .. 20) of m;
27499    end Subp;
27500 end Definitions;
27501 @end cartouche
27502 @end group
27503 @end smallexample
27504
27505 @noindent
27506 A package that @code{with}'s @code{Definitions} may safely instantiate
27507 @code{Definitions.Subp} because the compiler can determine that there
27508 definitely is no package body to worry about in this case
27509
27510 @item pragma Pure
27511 @cindex pragma Pure
27512 @findex Pure
27513 Places sufficient restrictions on a unit to guarantee that
27514 no call to any subprogram in the unit can result in an
27515 elaboration problem. This means that the compiler does not need
27516 to worry about the point of elaboration of such units, and in
27517 particular, does not need to check any calls to any subprograms
27518 in this unit.
27519
27520 @item pragma Preelaborate
27521 @findex Preelaborate
27522 @cindex pragma Preelaborate
27523 This pragma places slightly less stringent restrictions on a unit than
27524 does pragma Pure,
27525 but these restrictions are still sufficient to ensure that there
27526 are no elaboration problems with any calls to the unit.
27527
27528 @item pragma Elaborate_Body
27529 @findex Elaborate_Body
27530 @cindex pragma Elaborate_Body
27531 This pragma requires that the body of a unit be elaborated immediately
27532 after its spec. Suppose a unit @code{A} has such a pragma,
27533 and unit @code{B} does
27534 a @code{with} of unit @code{A}. Recall that the standard rules require
27535 the spec of unit @code{A}
27536 to be elaborated before the @code{with}'ing unit; given the pragma in
27537 @code{A}, we also know that the body of @code{A}
27538 will be elaborated before @code{B}, so
27539 that calls to @code{A} are safe and do not need a check.
27540 @end table
27541
27542 @noindent
27543 Note that,
27544 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27545 the use of
27546 @code{Elaborate_Body} does not guarantee that the program is
27547 free of elaboration problems, because it may not be possible
27548 to satisfy the requested elaboration order.
27549 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27550 If a programmer
27551 marks @code{Unit_1} as @code{Elaborate_Body},
27552 and not @code{Unit_2,} then the order of
27553 elaboration will be:
27554
27555 @smallexample
27556 @group
27557 Spec of Unit_2
27558 Spec of Unit_1
27559 Body of Unit_1
27560 Body of Unit_2
27561 @end group
27562 @end smallexample
27563
27564 @noindent
27565 Now that means that the call to @code{Func_1} in @code{Unit_2}
27566 need not be checked,
27567 it must be safe. But the call to @code{Func_2} in
27568 @code{Unit_1} may still fail if
27569 @code{Expression_1} is equal to 1,
27570 and the programmer must still take
27571 responsibility for this not being the case.
27572
27573 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27574 eliminated, except for calls entirely within a body, which are
27575 in any case fully under programmer control. However, using the pragma
27576 everywhere is not always possible.
27577 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27578 we marked both of them as having pragma @code{Elaborate_Body}, then
27579 clearly there would be no possible elaboration order.
27580
27581 The above pragmas allow a server to guarantee safe use by clients, and
27582 clearly this is the preferable approach. Consequently a good rule
27583 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27584 and if this is not possible,
27585 mark them as @code{Elaborate_Body} if possible.
27586 As we have seen, there are situations where neither of these
27587 three pragmas can be used.
27588 So we also provide methods for clients to control the
27589 order of elaboration of the servers on which they depend:
27590
27591 @table @asis
27592 @item pragma Elaborate (unit)
27593 @findex Elaborate
27594 @cindex pragma Elaborate
27595 This pragma is placed in the context clause, after a @code{with} clause,
27596 and it requires that the body of the named unit be elaborated before
27597 the unit in which the pragma occurs. The idea is to use this pragma
27598 if the current unit calls at elaboration time, directly or indirectly,
27599 some subprogram in the named unit.
27600
27601 @item pragma Elaborate_All (unit)
27602 @findex Elaborate_All
27603 @cindex pragma Elaborate_All
27604 This is a stronger version of the Elaborate pragma. Consider the
27605 following example:
27606
27607 @smallexample
27608 Unit A @code{with}'s unit B and calls B.Func in elab code
27609 Unit B @code{with}'s unit C, and B.Func calls C.Func
27610 @end smallexample
27611
27612 @noindent
27613 Now if we put a pragma @code{Elaborate (B)}
27614 in unit @code{A}, this ensures that the
27615 body of @code{B} is elaborated before the call, but not the
27616 body of @code{C}, so
27617 the call to @code{C.Func} could still cause @code{Program_Error} to
27618 be raised.
27619
27620 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27621 not only that the body of the named unit be elaborated before the
27622 unit doing the @code{with}, but also the bodies of all units that the
27623 named unit uses, following @code{with} links transitively. For example,
27624 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27625 then it requires
27626 not only that the body of @code{B} be elaborated before @code{A},
27627 but also the
27628 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27629 @end table
27630
27631 @noindent
27632 We are now in a position to give a usage rule in Ada for avoiding
27633 elaboration problems, at least if dynamic dispatching and access to
27634 subprogram values are not used. We will handle these cases separately
27635 later.
27636
27637 The rule is simple. If a unit has elaboration code that can directly or
27638 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27639 a generic package in a @code{with}'ed unit,
27640 then if the @code{with}'ed unit does not have
27641 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27642 a pragma @code{Elaborate_All}
27643 for the @code{with}'ed unit. By following this rule a client is
27644 assured that calls can be made without risk of an exception.
27645
27646 For generic subprogram instantiations, the rule can be relaxed to
27647 require only a pragma @code{Elaborate} since elaborating the body
27648 of a subprogram cannot cause any transitive elaboration (we are
27649 not calling the subprogram in this case, just elaborating its
27650 declaration).
27651
27652 If this rule is not followed, then a program may be in one of four
27653 states:
27654
27655 @table @asis
27656 @item No order exists
27657 No order of elaboration exists which follows the rules, taking into
27658 account any @code{Elaborate}, @code{Elaborate_All},
27659 or @code{Elaborate_Body} pragmas. In
27660 this case, an Ada compiler must diagnose the situation at bind
27661 time, and refuse to build an executable program.
27662
27663 @item One or more orders exist, all incorrect
27664 One or more acceptable elaboration orders exist, and all of them
27665 generate an elaboration order problem. In this case, the binder
27666 can build an executable program, but @code{Program_Error} will be raised
27667 when the program is run.
27668
27669 @item Several orders exist, some right, some incorrect
27670 One or more acceptable elaboration orders exists, and some of them
27671 work, and some do not. The programmer has not controlled
27672 the order of elaboration, so the binder may or may not pick one of
27673 the correct orders, and the program may or may not raise an
27674 exception when it is run. This is the worst case, because it means
27675 that the program may fail when moved to another compiler, or even
27676 another version of the same compiler.
27677
27678 @item One or more orders exists, all correct
27679 One ore more acceptable elaboration orders exist, and all of them
27680 work. In this case the program runs successfully. This state of
27681 affairs can be guaranteed by following the rule we gave above, but
27682 may be true even if the rule is not followed.
27683 @end table
27684
27685 @noindent
27686 Note that one additional advantage of following our rules on the use
27687 of @code{Elaborate} and @code{Elaborate_All}
27688 is that the program continues to stay in the ideal (all orders OK) state
27689 even if maintenance
27690 changes some bodies of some units. Conversely, if a program that does
27691 not follow this rule happens to be safe at some point, this state of affairs
27692 may deteriorate silently as a result of maintenance changes.
27693
27694 You may have noticed that the above discussion did not mention
27695 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27696 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27697 code in the body makes calls to some other unit, so it is still necessary
27698 to use @code{Elaborate_All} on such units.
27699
27700 @node Controlling Elaboration in GNAT - Internal Calls
27701 @section Controlling Elaboration in GNAT - Internal Calls
27702
27703 @noindent
27704 In the case of internal calls, i.e., calls within a single package, the
27705 programmer has full control over the order of elaboration, and it is up
27706 to the programmer to elaborate declarations in an appropriate order. For
27707 example writing:
27708
27709 @smallexample @c ada
27710 @group
27711 @cartouche
27712 function One return Float;
27713
27714 Q : Float := One;
27715
27716 function One return Float is
27717 begin
27718      return 1.0;
27719 end One;
27720 @end cartouche
27721 @end group
27722 @end smallexample
27723
27724 @noindent
27725 will obviously raise @code{Program_Error} at run time, because function
27726 One will be called before its body is elaborated. In this case GNAT will
27727 generate a warning that the call will raise @code{Program_Error}:
27728
27729 @smallexample
27730 @group
27731 @cartouche
27732  1. procedure y is
27733  2.    function One return Float;
27734  3.
27735  4.    Q : Float := One;
27736                     |
27737     >>> warning: cannot call "One" before body is elaborated
27738     >>> warning: Program_Error will be raised at run time
27739
27740  5.
27741  6.    function One return Float is
27742  7.    begin
27743  8.         return 1.0;
27744  9.    end One;
27745 10.
27746 11. begin
27747 12.    null;
27748 13. end;
27749 @end cartouche
27750 @end group
27751 @end smallexample
27752
27753 @noindent
27754 Note that in this particular case, it is likely that the call is safe, because
27755 the function @code{One} does not access any global variables.
27756 Nevertheless in Ada, we do not want the validity of the check to depend on
27757 the contents of the body (think about the separate compilation case), so this
27758 is still wrong, as we discussed in the previous sections.
27759
27760 The error is easily corrected by rearranging the declarations so that the
27761 body of @code{One} appears before the declaration containing the call
27762 (note that in Ada 95 and Ada 2005,
27763 declarations can appear in any order, so there is no restriction that
27764 would prevent this reordering, and if we write:
27765
27766 @smallexample @c ada
27767 @group
27768 @cartouche
27769 function One return Float;
27770
27771 function One return Float is
27772 begin
27773      return 1.0;
27774 end One;
27775
27776 Q : Float := One;
27777 @end cartouche
27778 @end group
27779 @end smallexample
27780
27781 @noindent
27782 then all is well, no warning is generated, and no
27783 @code{Program_Error} exception
27784 will be raised.
27785 Things are more complicated when a chain of subprograms is executed:
27786
27787 @smallexample @c ada
27788 @group
27789 @cartouche
27790 function A return Integer;
27791 function B return Integer;
27792 function C return Integer;
27793
27794 function B return Integer is begin return A; end;
27795 function C return Integer is begin return B; end;
27796
27797 X : Integer := C;
27798
27799 function A return Integer is begin return 1; end;
27800 @end cartouche
27801 @end group
27802 @end smallexample
27803
27804 @noindent
27805 Now the call to @code{C}
27806 at elaboration time in the declaration of @code{X} is correct, because
27807 the body of @code{C} is already elaborated,
27808 and the call to @code{B} within the body of
27809 @code{C} is correct, but the call
27810 to @code{A} within the body of @code{B} is incorrect, because the body
27811 of @code{A} has not been elaborated, so @code{Program_Error}
27812 will be raised on the call to @code{A}.
27813 In this case GNAT will generate a
27814 warning that @code{Program_Error} may be
27815 raised at the point of the call. Let's look at the warning:
27816
27817 @smallexample
27818 @group
27819 @cartouche
27820  1. procedure x is
27821  2.    function A return Integer;
27822  3.    function B return Integer;
27823  4.    function C return Integer;
27824  5.
27825  6.    function B return Integer is begin return A; end;
27826                                                     |
27827     >>> warning: call to "A" before body is elaborated may
27828                  raise Program_Error
27829     >>> warning: "B" called at line 7
27830     >>> warning: "C" called at line 9
27831
27832  7.    function C return Integer is begin return B; end;
27833  8.
27834  9.    X : Integer := C;
27835 10.
27836 11.    function A return Integer is begin return 1; end;
27837 12.
27838 13. begin
27839 14.    null;
27840 15. end;
27841 @end cartouche
27842 @end group
27843 @end smallexample
27844
27845 @noindent
27846 Note that the message here says ``may raise'', instead of the direct case,
27847 where the message says ``will be raised''. That's because whether
27848 @code{A} is
27849 actually called depends in general on run-time flow of control.
27850 For example, if the body of @code{B} said
27851
27852 @smallexample @c ada
27853 @group
27854 @cartouche
27855 function B return Integer is
27856 begin
27857    if some-condition-depending-on-input-data then
27858       return A;
27859    else
27860       return 1;
27861    end if;
27862 end B;
27863 @end cartouche
27864 @end group
27865 @end smallexample
27866
27867 @noindent
27868 then we could not know until run time whether the incorrect call to A would
27869 actually occur, so @code{Program_Error} might
27870 or might not be raised. It is possible for a compiler to
27871 do a better job of analyzing bodies, to
27872 determine whether or not @code{Program_Error}
27873 might be raised, but it certainly
27874 couldn't do a perfect job (that would require solving the halting problem
27875 and is provably impossible), and because this is a warning anyway, it does
27876 not seem worth the effort to do the analysis. Cases in which it
27877 would be relevant are rare.
27878
27879 In practice, warnings of either of the forms given
27880 above will usually correspond to
27881 real errors, and should be examined carefully and eliminated.
27882 In the rare case where a warning is bogus, it can be suppressed by any of
27883 the following methods:
27884
27885 @itemize @bullet
27886 @item
27887 Compile with the @option{-gnatws} switch set
27888
27889 @item
27890 Suppress @code{Elaboration_Check} for the called subprogram
27891
27892 @item
27893 Use pragma @code{Warnings_Off} to turn warnings off for the call
27894 @end itemize
27895
27896 @noindent
27897 For the internal elaboration check case,
27898 GNAT by default generates the
27899 necessary run-time checks to ensure
27900 that @code{Program_Error} is raised if any
27901 call fails an elaboration check. Of course this can only happen if a
27902 warning has been issued as described above. The use of pragma
27903 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27904 some of these checks, meaning that it may be possible (but is not
27905 guaranteed) for a program to be able to call a subprogram whose body
27906 is not yet elaborated, without raising a @code{Program_Error} exception.
27907
27908 @node Controlling Elaboration in GNAT - External Calls
27909 @section Controlling Elaboration in GNAT - External Calls
27910
27911 @noindent
27912 The previous section discussed the case in which the execution of a
27913 particular thread of elaboration code occurred entirely within a
27914 single unit. This is the easy case to handle, because a programmer
27915 has direct and total control over the order of elaboration, and
27916 furthermore, checks need only be generated in cases which are rare
27917 and which the compiler can easily detect.
27918 The situation is more complex when separate compilation is taken into account.
27919 Consider the following:
27920
27921 @smallexample @c ada
27922 @cartouche
27923 @group
27924 package Math is
27925    function Sqrt (Arg : Float) return Float;
27926 end Math;
27927
27928 package body Math is
27929    function Sqrt (Arg : Float) return Float is
27930    begin
27931          @dots{}
27932    end Sqrt;
27933 end Math;
27934 @end group
27935 @group
27936 with Math;
27937 package Stuff is
27938    X : Float := Math.Sqrt (0.5);
27939 end Stuff;
27940
27941 with Stuff;
27942 procedure Main is
27943 begin
27944    @dots{}
27945 end Main;
27946 @end group
27947 @end cartouche
27948 @end smallexample
27949
27950 @noindent
27951 where @code{Main} is the main program. When this program is executed, the
27952 elaboration code must first be executed, and one of the jobs of the
27953 binder is to determine the order in which the units of a program are
27954 to be elaborated. In this case we have four units: the spec and body
27955 of @code{Math},
27956 the spec of @code{Stuff} and the body of @code{Main}).
27957 In what order should the four separate sections of elaboration code
27958 be executed?
27959
27960 There are some restrictions in the order of elaboration that the binder
27961 can choose. In particular, if unit U has a @code{with}
27962 for a package @code{X}, then you
27963 are assured that the spec of @code{X}
27964 is elaborated before U , but you are
27965 not assured that the body of @code{X}
27966 is elaborated before U.
27967 This means that in the above case, the binder is allowed to choose the
27968 order:
27969
27970 @smallexample
27971 spec of Math
27972 spec of Stuff
27973 body of Math
27974 body of Main
27975 @end smallexample
27976
27977 @noindent
27978 but that's not good, because now the call to @code{Math.Sqrt}
27979 that happens during
27980 the elaboration of the @code{Stuff}
27981 spec happens before the body of @code{Math.Sqrt} is
27982 elaborated, and hence causes @code{Program_Error} exception to be raised.
27983 At first glance, one might say that the binder is misbehaving, because
27984 obviously you want to elaborate the body of something you @code{with}
27985 first, but
27986 that is not a general rule that can be followed in all cases. Consider
27987
27988 @smallexample @c ada
27989 @group
27990 @cartouche
27991 package X is @dots{}
27992
27993 package Y is @dots{}
27994
27995 with X;
27996 package body Y is @dots{}
27997
27998 with Y;
27999 package body X is @dots{}
28000 @end cartouche
28001 @end group
28002 @end smallexample
28003
28004 @noindent
28005 This is a common arrangement, and, apart from the order of elaboration
28006 problems that might arise in connection with elaboration code, this works fine.
28007 A rule that says that you must first elaborate the body of anything you
28008 @code{with} cannot work in this case:
28009 the body of @code{X} @code{with}'s @code{Y},
28010 which means you would have to
28011 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28012 which means
28013 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28014 loop that cannot be broken.
28015
28016 It is true that the binder can in many cases guess an order of elaboration
28017 that is unlikely to cause a @code{Program_Error}
28018 exception to be raised, and it tries to do so (in the
28019 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28020 by default
28021 elaborate the body of @code{Math} right after its spec, so all will be well).
28022
28023 However, a program that blindly relies on the binder to be helpful can
28024 get into trouble, as we discussed in the previous sections, so
28025 GNAT
28026 provides a number of facilities for assisting the programmer in
28027 developing programs that are robust with respect to elaboration order.
28028
28029 @node Default Behavior in GNAT - Ensuring Safety
28030 @section Default Behavior in GNAT - Ensuring Safety
28031
28032 @noindent
28033 The default behavior in GNAT ensures elaboration safety. In its
28034 default mode GNAT implements the
28035 rule we previously described as the right approach. Let's restate it:
28036
28037 @itemize
28038 @item
28039 @emph{If a unit has elaboration code that can directly or indirectly make a
28040 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28041 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28042 does not have pragma @code{Pure} or
28043 @code{Preelaborate}, then the client should have an
28044 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28045
28046 @emph{In the case of instantiating a generic subprogram, it is always
28047 sufficient to have only an @code{Elaborate} pragma for the
28048 @code{with}'ed unit.}
28049 @end itemize
28050
28051 @noindent
28052 By following this rule a client is assured that calls and instantiations
28053 can be made without risk of an exception.
28054
28055 In this mode GNAT traces all calls that are potentially made from
28056 elaboration code, and puts in any missing implicit @code{Elaborate}
28057 and @code{Elaborate_All} pragmas.
28058 The advantage of this approach is that no elaboration problems
28059 are possible if the binder can find an elaboration order that is
28060 consistent with these implicit @code{Elaborate} and
28061 @code{Elaborate_All} pragmas. The
28062 disadvantage of this approach is that no such order may exist.
28063
28064 If the binder does not generate any diagnostics, then it means that it has
28065 found an elaboration order that is guaranteed to be safe. However, the binder
28066 may still be relying on implicitly generated @code{Elaborate} and
28067 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28068 guaranteed.
28069
28070 If it is important to guarantee portability, then the compilations should
28071 use the
28072 @option{-gnatwl}
28073 (warn on elaboration problems) switch. This will cause warning messages
28074 to be generated indicating the missing @code{Elaborate} and
28075 @code{Elaborate_All} pragmas.
28076 Consider the following source program:
28077
28078 @smallexample @c ada
28079 @group
28080 @cartouche
28081 with k;
28082 package j is
28083   m : integer := k.r;
28084 end;
28085 @end cartouche
28086 @end group
28087 @end smallexample
28088
28089 @noindent
28090 where it is clear that there
28091 should be a pragma @code{Elaborate_All}
28092 for unit @code{k}. An implicit pragma will be generated, and it is
28093 likely that the binder will be able to honor it. However, if you want
28094 to port this program to some other Ada compiler than GNAT.
28095 it is safer to include the pragma explicitly in the source. If this
28096 unit is compiled with the
28097 @option{-gnatwl}
28098 switch, then the compiler outputs a warning:
28099
28100 @smallexample
28101 @group
28102 @cartouche
28103 1. with k;
28104 2. package j is
28105 3.   m : integer := k.r;
28106                      |
28107    >>> warning: call to "r" may raise Program_Error
28108    >>> warning: missing pragma Elaborate_All for "k"
28109
28110 4. end;
28111 @end cartouche
28112 @end group
28113 @end smallexample
28114
28115 @noindent
28116 and these warnings can be used as a guide for supplying manually
28117 the missing pragmas. It is usually a bad idea to use this warning
28118 option during development. That's because it will warn you when
28119 you need to put in a pragma, but cannot warn you when it is time
28120 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28121 unnecessary dependencies and even false circularities.
28122
28123 This default mode is more restrictive than the Ada Reference
28124 Manual, and it is possible to construct programs which will compile
28125 using the dynamic model described there, but will run into a
28126 circularity using the safer static model we have described.
28127
28128 Of course any Ada compiler must be able to operate in a mode
28129 consistent with the requirements of the Ada Reference Manual,
28130 and in particular must have the capability of implementing the
28131 standard dynamic model of elaboration with run-time checks.
28132
28133 In GNAT, this standard mode can be achieved either by the use of
28134 the @option{-gnatE} switch on the compiler (@command{gcc} or
28135 @command{gnatmake}) command, or by the use of the configuration pragma:
28136
28137 @smallexample @c ada
28138 pragma Elaboration_Checks (RM);
28139 @end smallexample
28140
28141 @noindent
28142 Either approach will cause the unit affected to be compiled using the
28143 standard dynamic run-time elaboration checks described in the Ada
28144 Reference Manual. The static model is generally preferable, since it
28145 is clearly safer to rely on compile and link time checks rather than
28146 run-time checks. However, in the case of legacy code, it may be
28147 difficult to meet the requirements of the static model. This
28148 issue is further discussed in
28149 @ref{What to Do If the Default Elaboration Behavior Fails}.
28150
28151 Note that the static model provides a strict subset of the allowed
28152 behavior and programs of the Ada Reference Manual, so if you do
28153 adhere to the static model and no circularities exist,
28154 then you are assured that your program will
28155 work using the dynamic model, providing that you remove any
28156 pragma Elaborate statements from the source.
28157
28158 @node Treatment of Pragma Elaborate
28159 @section Treatment of Pragma Elaborate
28160 @cindex Pragma Elaborate
28161
28162 @noindent
28163 The use of @code{pragma Elaborate}
28164 should generally be avoided in Ada 95 and Ada 2005 programs,
28165 since there is no guarantee that transitive calls
28166 will be properly handled. Indeed at one point, this pragma was placed
28167 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28168
28169 Now that's a bit restrictive. In practice, the case in which
28170 @code{pragma Elaborate} is useful is when the caller knows that there
28171 are no transitive calls, or that the called unit contains all necessary
28172 transitive @code{pragma Elaborate} statements, and legacy code often
28173 contains such uses.
28174
28175 Strictly speaking the static mode in GNAT should ignore such pragmas,
28176 since there is no assurance at compile time that the necessary safety
28177 conditions are met. In practice, this would cause GNAT to be incompatible
28178 with correctly written Ada 83 code that had all necessary
28179 @code{pragma Elaborate} statements in place. Consequently, we made the
28180 decision that GNAT in its default mode will believe that if it encounters
28181 a @code{pragma Elaborate} then the programmer knows what they are doing,
28182 and it will trust that no elaboration errors can occur.
28183
28184 The result of this decision is two-fold. First to be safe using the
28185 static mode, you should remove all @code{pragma Elaborate} statements.
28186 Second, when fixing circularities in existing code, you can selectively
28187 use @code{pragma Elaborate} statements to convince the static mode of
28188 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28189 statement.
28190
28191 When using the static mode with @option{-gnatwl}, any use of
28192 @code{pragma Elaborate} will generate a warning about possible
28193 problems.
28194
28195 @node Elaboration Issues for Library Tasks
28196 @section Elaboration Issues for Library Tasks
28197 @cindex Library tasks, elaboration issues
28198 @cindex Elaboration of library tasks
28199
28200 @noindent
28201 In this section we examine special elaboration issues that arise for
28202 programs that declare library level tasks.
28203
28204 Generally the model of execution of an Ada program is that all units are
28205 elaborated, and then execution of the program starts. However, the
28206 declaration of library tasks definitely does not fit this model. The
28207 reason for this is that library tasks start as soon as they are declared
28208 (more precisely, as soon as the statement part of the enclosing package
28209 body is reached), that is to say before elaboration
28210 of the program is complete. This means that if such a task calls a
28211 subprogram, or an entry in another task, the callee may or may not be
28212 elaborated yet, and in the standard
28213 Reference Manual model of dynamic elaboration checks, you can even
28214 get timing dependent Program_Error exceptions, since there can be
28215 a race between the elaboration code and the task code.
28216
28217 The static model of elaboration in GNAT seeks to avoid all such
28218 dynamic behavior, by being conservative, and the conservative
28219 approach in this particular case is to assume that all the code
28220 in a task body is potentially executed at elaboration time if
28221 a task is declared at the library level.
28222
28223 This can definitely result in unexpected circularities. Consider
28224 the following example
28225
28226 @smallexample @c ada
28227 package Decls is
28228   task Lib_Task is
28229      entry Start;
28230   end Lib_Task;
28231
28232   type My_Int is new Integer;
28233
28234   function Ident (M : My_Int) return My_Int;
28235 end Decls;
28236
28237 with Utils;
28238 package body Decls is
28239   task body Lib_Task is
28240   begin
28241      accept Start;
28242      Utils.Put_Val (2);
28243   end Lib_Task;
28244
28245   function Ident (M : My_Int) return My_Int is
28246   begin
28247      return M;
28248   end Ident;
28249 end Decls;
28250
28251 with Decls;
28252 package Utils is
28253   procedure Put_Val (Arg : Decls.My_Int);
28254 end Utils;
28255
28256 with Text_IO;
28257 package body Utils is
28258   procedure Put_Val (Arg : Decls.My_Int) is
28259   begin
28260      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28261   end Put_Val;
28262 end Utils;
28263
28264 with Decls;
28265 procedure Main is
28266 begin
28267    Decls.Lib_Task.Start;
28268 end;
28269 @end smallexample
28270
28271 @noindent
28272 If the above example is compiled in the default static elaboration
28273 mode, then a circularity occurs. The circularity comes from the call
28274 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28275 this call occurs in elaboration code, we need an implicit pragma
28276 @code{Elaborate_All} for @code{Utils}. This means that not only must
28277 the spec and body of @code{Utils} be elaborated before the body
28278 of @code{Decls}, but also the spec and body of any unit that is
28279 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28280 the body of @code{Decls}. This is the transitive implication of
28281 pragma @code{Elaborate_All} and it makes sense, because in general
28282 the body of @code{Put_Val} might have a call to something in a
28283 @code{with'ed} unit.
28284
28285 In this case, the body of Utils (actually its spec) @code{with's}
28286 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28287 must be elaborated before itself, in case there is a call from the
28288 body of @code{Utils}.
28289
28290 Here is the exact chain of events we are worrying about:
28291
28292 @enumerate
28293 @item
28294 In the body of @code{Decls} a call is made from within the body of a library
28295 task to a subprogram in the package @code{Utils}. Since this call may
28296 occur at elaboration time (given that the task is activated at elaboration
28297 time), we have to assume the worst, i.e., that the
28298 call does happen at elaboration time.
28299
28300 @item
28301 This means that the body and spec of @code{Util} must be elaborated before
28302 the body of @code{Decls} so that this call does not cause an access before
28303 elaboration.
28304
28305 @item
28306 Within the body of @code{Util}, specifically within the body of
28307 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28308 by this package.
28309
28310 @item
28311 One such @code{with}'ed package is package @code{Decls}, so there
28312 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28313 In fact there is such a call in this example, but we would have to
28314 assume that there was such a call even if it were not there, since
28315 we are not supposed to write the body of @code{Decls} knowing what
28316 is in the body of @code{Utils}; certainly in the case of the
28317 static elaboration model, the compiler does not know what is in
28318 other bodies and must assume the worst.
28319
28320 @item
28321 This means that the spec and body of @code{Decls} must also be
28322 elaborated before we elaborate the unit containing the call, but
28323 that unit is @code{Decls}! This means that the body of @code{Decls}
28324 must be elaborated before itself, and that's a circularity.
28325 @end enumerate
28326
28327 @noindent
28328 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28329 the body of @code{Decls} you will get a true Ada Reference Manual
28330 circularity that makes the program illegal.
28331
28332 In practice, we have found that problems with the static model of
28333 elaboration in existing code often arise from library tasks, so
28334 we must address this particular situation.
28335
28336 Note that if we compile and run the program above, using the dynamic model of
28337 elaboration (that is to say use the @option{-gnatE} switch),
28338 then it compiles, binds,
28339 links, and runs, printing the expected result of 2. Therefore in some sense
28340 the circularity here is only apparent, and we need to capture
28341 the properties of this program that  distinguish it from other library-level
28342 tasks that have real elaboration problems.
28343
28344 We have four possible answers to this question:
28345
28346 @itemize @bullet
28347
28348 @item
28349 Use the dynamic model of elaboration.
28350
28351 If we use the @option{-gnatE} switch, then as noted above, the program works.
28352 Why is this? If we examine the task body, it is apparent that the task cannot
28353 proceed past the
28354 @code{accept} statement until after elaboration has been completed, because
28355 the corresponding entry call comes from the main program, not earlier.
28356 This is why the dynamic model works here. But that's really giving
28357 up on a precise analysis, and we prefer to take this approach only if we cannot
28358 solve the
28359 problem in any other manner. So let us examine two ways to reorganize
28360 the program to avoid the potential elaboration problem.
28361
28362 @item
28363 Split library tasks into separate packages.
28364
28365 Write separate packages, so that library tasks are isolated from
28366 other declarations as much as possible. Let us look at a variation on
28367 the above program.
28368
28369 @smallexample @c ada
28370 package Decls1 is
28371   task Lib_Task is
28372      entry Start;
28373   end Lib_Task;
28374 end Decls1;
28375
28376 with Utils;
28377 package body Decls1 is
28378   task body Lib_Task is
28379   begin
28380      accept Start;
28381      Utils.Put_Val (2);
28382   end Lib_Task;
28383 end Decls1;
28384
28385 package Decls2 is
28386   type My_Int is new Integer;
28387   function Ident (M : My_Int) return My_Int;
28388 end Decls2;
28389
28390 with Utils;
28391 package body Decls2 is
28392   function Ident (M : My_Int) return My_Int is
28393   begin
28394      return M;
28395   end Ident;
28396 end Decls2;
28397
28398 with Decls2;
28399 package Utils is
28400   procedure Put_Val (Arg : Decls2.My_Int);
28401 end Utils;
28402
28403 with Text_IO;
28404 package body Utils is
28405   procedure Put_Val (Arg : Decls2.My_Int) is
28406   begin
28407      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28408   end Put_Val;
28409 end Utils;
28410
28411 with Decls1;
28412 procedure Main is
28413 begin
28414    Decls1.Lib_Task.Start;
28415 end;
28416 @end smallexample
28417
28418 @noindent
28419 All we have done is to split @code{Decls} into two packages, one
28420 containing the library task, and one containing everything else. Now
28421 there is no cycle, and the program compiles, binds, links and executes
28422 using the default static model of elaboration.
28423
28424 @item
28425 Declare separate task types.
28426
28427 A significant part of the problem arises because of the use of the
28428 single task declaration form. This means that the elaboration of
28429 the task type, and the elaboration of the task itself (i.e.@: the
28430 creation of the task) happen at the same time. A good rule
28431 of style in Ada is to always create explicit task types. By
28432 following the additional step of placing task objects in separate
28433 packages from the task type declaration, many elaboration problems
28434 are avoided. Here is another modified example of the example program:
28435
28436 @smallexample @c ada
28437 package Decls is
28438   task type Lib_Task_Type is
28439      entry Start;
28440   end Lib_Task_Type;
28441
28442   type My_Int is new Integer;
28443
28444   function Ident (M : My_Int) return My_Int;
28445 end Decls;
28446
28447 with Utils;
28448 package body Decls is
28449   task body Lib_Task_Type is
28450   begin
28451      accept Start;
28452      Utils.Put_Val (2);
28453   end Lib_Task_Type;
28454
28455   function Ident (M : My_Int) return My_Int is
28456   begin
28457      return M;
28458   end Ident;
28459 end Decls;
28460
28461 with Decls;
28462 package Utils is
28463   procedure Put_Val (Arg : Decls.My_Int);
28464 end Utils;
28465
28466 with Text_IO;
28467 package body Utils is
28468   procedure Put_Val (Arg : Decls.My_Int) is
28469   begin
28470      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28471   end Put_Val;
28472 end Utils;
28473
28474 with Decls;
28475 package Declst is
28476    Lib_Task : Decls.Lib_Task_Type;
28477 end Declst;
28478
28479 with Declst;
28480 procedure Main is
28481 begin
28482    Declst.Lib_Task.Start;
28483 end;
28484 @end smallexample
28485
28486 @noindent
28487 What we have done here is to replace the @code{task} declaration in
28488 package @code{Decls} with a @code{task type} declaration. Then we
28489 introduce a separate package @code{Declst} to contain the actual
28490 task object. This separates the elaboration issues for
28491 the @code{task type}
28492 declaration, which causes no trouble, from the elaboration issues
28493 of the task object, which is also unproblematic, since it is now independent
28494 of the elaboration of  @code{Utils}.
28495 This separation of concerns also corresponds to
28496 a generally sound engineering principle of separating declarations
28497 from instances. This version of the program also compiles, binds, links,
28498 and executes, generating the expected output.
28499
28500 @item
28501 Use No_Entry_Calls_In_Elaboration_Code restriction.
28502 @cindex No_Entry_Calls_In_Elaboration_Code
28503
28504 The previous two approaches described how a program can be restructured
28505 to avoid the special problems caused by library task bodies. in practice,
28506 however, such restructuring may be difficult to apply to existing legacy code,
28507 so we must consider solutions that do not require massive rewriting.
28508
28509 Let us consider more carefully why our original sample program works
28510 under the dynamic model of elaboration. The reason is that the code
28511 in the task body blocks immediately on the @code{accept}
28512 statement. Now of course there is nothing to prohibit elaboration
28513 code from making entry calls (for example from another library level task),
28514 so we cannot tell in isolation that
28515 the task will not execute the accept statement  during elaboration.
28516
28517 However, in practice it is very unusual to see elaboration code
28518 make any entry calls, and the pattern of tasks starting
28519 at elaboration time and then immediately blocking on @code{accept} or
28520 @code{select} statements is very common. What this means is that
28521 the compiler is being too pessimistic when it analyzes the
28522 whole package body as though it might be executed at elaboration
28523 time.
28524
28525 If we know that the elaboration code contains no entry calls, (a very safe
28526 assumption most of the time, that could almost be made the default
28527 behavior), then we can compile all units of the program under control
28528 of the following configuration pragma:
28529
28530 @smallexample
28531 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28532 @end smallexample
28533
28534 @noindent
28535 This pragma can be placed in the @file{gnat.adc} file in the usual
28536 manner. If we take our original unmodified program and compile it
28537 in the presence of a @file{gnat.adc} containing the above pragma,
28538 then once again, we can compile, bind, link, and execute, obtaining
28539 the expected result. In the presence of this pragma, the compiler does
28540 not trace calls in a task body, that appear after the first @code{accept}
28541 or @code{select} statement, and therefore does not report a potential
28542 circularity in the original program.
28543
28544 The compiler will check to the extent it can that the above
28545 restriction is not violated, but it is not always possible to do a
28546 complete check at compile time, so it is important to use this
28547 pragma only if the stated restriction is in fact met, that is to say
28548 no task receives an entry call before elaboration of all units is completed.
28549
28550 @end itemize
28551
28552 @node Mixing Elaboration Models
28553 @section Mixing Elaboration Models
28554 @noindent
28555 So far, we have assumed that the entire program is either compiled
28556 using the dynamic model or static model, ensuring consistency. It
28557 is possible to mix the two models, but rules have to be followed
28558 if this mixing is done to ensure that elaboration checks are not
28559 omitted.
28560
28561 The basic rule is that @emph{a unit compiled with the static model cannot
28562 be @code{with'ed} by a unit compiled with the dynamic model}. The
28563 reason for this is that in the static model, a unit assumes that
28564 its clients guarantee to use (the equivalent of) pragma
28565 @code{Elaborate_All} so that no elaboration checks are required
28566 in inner subprograms, and this assumption is violated if the
28567 client is compiled with dynamic checks.
28568
28569 The precise rule is as follows. A unit that is compiled with dynamic
28570 checks can only @code{with} a unit that meets at least one of the
28571 following criteria:
28572
28573 @itemize @bullet
28574
28575 @item
28576 The @code{with'ed} unit is itself compiled with dynamic elaboration
28577 checks (that is with the @option{-gnatE} switch.
28578
28579 @item
28580 The @code{with'ed} unit is an internal GNAT implementation unit from
28581 the System, Interfaces, Ada, or GNAT hierarchies.
28582
28583 @item
28584 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28585
28586 @item
28587 The @code{with'ing} unit (that is the client) has an explicit pragma
28588 @code{Elaborate_All} for the @code{with'ed} unit.
28589
28590 @end itemize
28591
28592 @noindent
28593 If this rule is violated, that is if a unit with dynamic elaboration
28594 checks @code{with's} a unit that does not meet one of the above four
28595 criteria, then the binder (@code{gnatbind}) will issue a warning
28596 similar to that in the following example:
28597
28598 @smallexample
28599 warning: "x.ads" has dynamic elaboration checks and with's
28600 warning:   "y.ads" which has static elaboration checks
28601 @end smallexample
28602
28603 @noindent
28604 These warnings indicate that the rule has been violated, and that as a result
28605 elaboration checks may be missed in the resulting executable file.
28606 This warning may be suppressed using the @option{-ws} binder switch
28607 in the usual manner.
28608
28609 One useful application of this mixing rule is in the case of a subsystem
28610 which does not itself @code{with} units from the remainder of the
28611 application. In this case, the entire subsystem can be compiled with
28612 dynamic checks to resolve a circularity in the subsystem, while
28613 allowing the main application that uses this subsystem to be compiled
28614 using the more reliable default static model.
28615
28616 @node What to Do If the Default Elaboration Behavior Fails
28617 @section What to Do If the Default Elaboration Behavior Fails
28618
28619 @noindent
28620 If the binder cannot find an acceptable order, it outputs detailed
28621 diagnostics. For example:
28622 @smallexample
28623 @group
28624 @iftex
28625 @leftskip=0cm
28626 @end iftex
28627 error: elaboration circularity detected
28628 info:   "proc (body)" must be elaborated before "pack (body)"
28629 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28630 info:     recompile "pack (body)" with -gnatwl
28631 info:                             for full details
28632 info:       "proc (body)"
28633 info:         is needed by its spec:
28634 info:       "proc (spec)"
28635 info:         which is withed by:
28636 info:       "pack (body)"
28637 info:  "pack (body)" must be elaborated before "proc (body)"
28638 info:     reason: pragma Elaborate in unit "proc (body)"
28639 @end group
28640
28641 @end smallexample
28642
28643 @noindent
28644 In this case we have a cycle that the binder cannot break. On the one
28645 hand, there is an explicit pragma Elaborate in @code{proc} for
28646 @code{pack}. This means that the body of @code{pack} must be elaborated
28647 before the body of @code{proc}. On the other hand, there is elaboration
28648 code in @code{pack} that calls a subprogram in @code{proc}. This means
28649 that for maximum safety, there should really be a pragma
28650 Elaborate_All in @code{pack} for @code{proc} which would require that
28651 the body of @code{proc} be elaborated before the body of
28652 @code{pack}. Clearly both requirements cannot be satisfied.
28653 Faced with a circularity of this kind, you have three different options.
28654
28655 @table @asis
28656 @item Fix the program
28657 The most desirable option from the point of view of long-term maintenance
28658 is to rearrange the program so that the elaboration problems are avoided.
28659 One useful technique is to place the elaboration code into separate
28660 child packages. Another is to move some of the initialization code to
28661 explicitly called subprograms, where the program controls the order
28662 of initialization explicitly. Although this is the most desirable option,
28663 it may be impractical and involve too much modification, especially in
28664 the case of complex legacy code.
28665
28666 @item Perform dynamic checks
28667 If the compilations are done using the
28668 @option{-gnatE}
28669 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28670 manner. Dynamic checks are generated for all calls that could possibly result
28671 in raising an exception. With this switch, the compiler does not generate
28672 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28673 exactly as specified in the @cite{Ada Reference Manual}.
28674 The binder will generate
28675 an executable program that may or may not raise @code{Program_Error}, and then
28676 it is the programmer's job to ensure that it does not raise an exception. Note
28677 that it is important to compile all units with the switch, it cannot be used
28678 selectively.
28679
28680 @item Suppress checks
28681 The drawback of dynamic checks is that they generate a
28682 significant overhead at run time, both in space and time. If you
28683 are absolutely sure that your program cannot raise any elaboration
28684 exceptions, and you still want to use the dynamic elaboration model,
28685 then you can use the configuration pragma
28686 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28687 example this pragma could be placed in the @file{gnat.adc} file.
28688
28689 @item Suppress checks selectively
28690 When you know that certain calls or instantiations in elaboration code cannot
28691 possibly lead to an elaboration error, and the binder nevertheless complains
28692 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28693 elaboration circularities, it is possible to remove those warnings locally and
28694 obtain a program that will bind. Clearly this can be unsafe, and it is the
28695 responsibility of the programmer to make sure that the resulting program has no
28696 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28697 used with different granularity to suppress warnings and break elaboration
28698 circularities:
28699
28700 @itemize @bullet
28701 @item
28702 Place the pragma that names the called subprogram in the declarative part
28703 that contains the call.
28704
28705 @item
28706 Place the pragma in the declarative part, without naming an entity. This
28707 disables warnings on all calls in the corresponding  declarative region.
28708
28709 @item
28710 Place the pragma in the package spec that declares the called subprogram,
28711 and name the subprogram. This disables warnings on all elaboration calls to
28712 that subprogram.
28713
28714 @item
28715 Place the pragma in the package spec that declares the called subprogram,
28716 without naming any entity. This disables warnings on all elaboration calls to
28717 all subprograms declared in this spec.
28718
28719 @item Use Pragma Elaborate
28720 As previously described in section @xref{Treatment of Pragma Elaborate},
28721 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28722 that no elaboration checks are required on calls to the designated unit.
28723 There may be cases in which the caller knows that no transitive calls
28724 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28725 case where @code{pragma Elaborate_All} would cause a circularity.
28726 @end itemize
28727
28728 @noindent
28729 These five cases are listed in order of decreasing safety, and therefore
28730 require increasing programmer care in their application. Consider the
28731 following program:
28732
28733 @smallexample @c adanocomment
28734 package Pack1 is
28735   function F1 return Integer;
28736   X1 : Integer;
28737 end Pack1;
28738
28739 package Pack2 is
28740   function F2 return Integer;
28741   function Pure (x : integer) return integer;
28742   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28743   --  pragma Suppress (Elaboration_Check);              -- (4)
28744 end Pack2;
28745
28746 with Pack2;
28747 package body Pack1 is
28748   function F1 return Integer is
28749   begin
28750     return 100;
28751   end F1;
28752   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28753 begin
28754   declare
28755     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28756     --  pragma Suppress(Elaboration_Check);             -- (2)
28757   begin
28758     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28759   end;
28760 end Pack1;
28761
28762 with Pack1;
28763 package body Pack2 is
28764   function F2 return Integer is
28765   begin
28766      return Pack1.F1;
28767   end F2;
28768   function Pure (x : integer) return integer is
28769   begin
28770      return x ** 3 - 3 * x;
28771   end;
28772 end Pack2;
28773
28774 with Pack1, Ada.Text_IO;
28775 procedure Proc3 is
28776 begin
28777   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28778 end Proc3;
28779 @end smallexample
28780 In the absence of any pragmas, an attempt to bind this program produces
28781 the following diagnostics:
28782 @smallexample
28783 @group
28784 @iftex
28785 @leftskip=.5cm
28786 @end iftex
28787 error: elaboration circularity detected
28788 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28789 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28790 info:       recompile "pack1 (body)" with -gnatwl for full details
28791 info:          "pack1 (body)"
28792 info:             must be elaborated along with its spec:
28793 info:          "pack1 (spec)"
28794 info:             which is withed by:
28795 info:          "pack2 (body)"
28796 info:             which must be elaborated along with its spec:
28797 info:          "pack2 (spec)"
28798 info:             which is withed by:
28799 info:          "pack1 (body)"
28800 @end group
28801 @end smallexample
28802 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28803 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28804 F2 is safe, even though F2 calls F1, because the call appears after the
28805 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28806 remove the warning on the call. It is also possible to use pragma (2)
28807 because there are no other potentially unsafe calls in the block.
28808
28809 @noindent
28810 The call to @code{Pure} is safe because this function does not depend on the
28811 state of @code{Pack2}. Therefore any call to this function is safe, and it
28812 is correct to place pragma (3) in the corresponding package spec.
28813
28814 @noindent
28815 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28816 warnings on all calls to functions declared therein. Note that this is not
28817 necessarily safe, and requires more detailed examination of the subprogram
28818 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28819 be already elaborated.
28820 @end table
28821
28822 @noindent
28823 It is hard to generalize on which of these four approaches should be
28824 taken. Obviously if it is possible to fix the program so that the default
28825 treatment works, this is preferable, but this may not always be practical.
28826 It is certainly simple enough to use
28827 @option{-gnatE}
28828 but the danger in this case is that, even if the GNAT binder
28829 finds a correct elaboration order, it may not always do so,
28830 and certainly a binder from another Ada compiler might not. A
28831 combination of testing and analysis (for which the warnings generated
28832 with the
28833 @option{-gnatwl}
28834 switch can be useful) must be used to ensure that the program is free
28835 of errors. One switch that is useful in this testing is the
28836 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28837 switch for
28838 @code{gnatbind}.
28839 Normally the binder tries to find an order that has the best chance
28840 of avoiding elaboration problems. However, if this switch is used, the binder
28841 plays a devil's advocate role, and tries to choose the order that
28842 has the best chance of failing. If your program works even with this
28843 switch, then it has a better chance of being error free, but this is still
28844 not a guarantee.
28845
28846 For an example of this approach in action, consider the C-tests (executable
28847 tests) from the ACVC suite. If these are compiled and run with the default
28848 treatment, then all but one of them succeed without generating any error
28849 diagnostics from the binder. However, there is one test that fails, and
28850 this is not surprising, because the whole point of this test is to ensure
28851 that the compiler can handle cases where it is impossible to determine
28852 a correct order statically, and it checks that an exception is indeed
28853 raised at run time.
28854
28855 This one test must be compiled and run using the
28856 @option{-gnatE}
28857 switch, and then it passes. Alternatively, the entire suite can
28858 be run using this switch. It is never wrong to run with the dynamic
28859 elaboration switch if your code is correct, and we assume that the
28860 C-tests are indeed correct (it is less efficient, but efficiency is
28861 not a factor in running the ACVC tests.)
28862
28863 @node Elaboration for Access-to-Subprogram Values
28864 @section Elaboration for Access-to-Subprogram Values
28865 @cindex Access-to-subprogram
28866
28867 @noindent
28868 Access-to-subprogram types (introduced in Ada 95) complicate
28869 the handling of elaboration. The trouble is that it becomes
28870 impossible to tell at compile time which procedure
28871 is being called. This means that it is not possible for the binder
28872 to analyze the elaboration requirements in this case.
28873
28874 If at the point at which the access value is created
28875 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28876 the body of the subprogram is
28877 known to have been elaborated, then the access value is safe, and its use
28878 does not require a check. This may be achieved by appropriate arrangement
28879 of the order of declarations if the subprogram is in the current unit,
28880 or, if the subprogram is in another unit, by using pragma
28881 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28882 on the referenced unit.
28883
28884 If the referenced body is not known to have been elaborated at the point
28885 the access value is created, then any use of the access value must do a
28886 dynamic check, and this dynamic check will fail and raise a
28887 @code{Program_Error} exception if the body has not been elaborated yet.
28888 GNAT will generate the necessary checks, and in addition, if the
28889 @option{-gnatwl}
28890 switch is set, will generate warnings that such checks are required.
28891
28892 The use of dynamic dispatching for tagged types similarly generates
28893 a requirement for dynamic checks, and premature calls to any primitive
28894 operation of a tagged type before the body of the operation has been
28895 elaborated, will result in the raising of @code{Program_Error}.
28896
28897 @node Summary of Procedures for Elaboration Control
28898 @section Summary of Procedures for Elaboration Control
28899 @cindex Elaboration control
28900
28901 @noindent
28902 First, compile your program with the default options, using none of
28903 the special elaboration control switches. If the binder successfully
28904 binds your program, then you can be confident that, apart from issues
28905 raised by the use of access-to-subprogram types and dynamic dispatching,
28906 the program is free of elaboration errors. If it is important that the
28907 program be portable, then use the
28908 @option{-gnatwl}
28909 switch to generate warnings about missing @code{Elaborate} or
28910 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28911
28912 If the program fails to bind using the default static elaboration
28913 handling, then you can fix the program to eliminate the binder
28914 message, or recompile the entire program with the
28915 @option{-gnatE} switch to generate dynamic elaboration checks,
28916 and, if you are sure there really are no elaboration problems,
28917 use a global pragma @code{Suppress (Elaboration_Check)}.
28918
28919 @node Other Elaboration Order Considerations
28920 @section Other Elaboration Order Considerations
28921 @noindent
28922 This section has been entirely concerned with the issue of finding a valid
28923 elaboration order, as defined by the Ada Reference Manual. In a case
28924 where several elaboration orders are valid, the task is to find one
28925 of the possible valid elaboration orders (and the static model in GNAT
28926 will ensure that this is achieved).
28927
28928 The purpose of the elaboration rules in the Ada Reference Manual is to
28929 make sure that no entity is accessed before it has been elaborated. For
28930 a subprogram, this means that the spec and body must have been elaborated
28931 before the subprogram is called. For an object, this means that the object
28932 must have been elaborated before its value is read or written. A violation
28933 of either of these two requirements is an access before elaboration order,
28934 and this section has been all about avoiding such errors.
28935
28936 In the case where more than one order of elaboration is possible, in the
28937 sense that access before elaboration errors are avoided, then any one of
28938 the orders is ``correct'' in the sense that it meets the requirements of
28939 the Ada Reference Manual, and no such error occurs.
28940
28941 However, it may be the case for a given program, that there are
28942 constraints on the order of elaboration that come not from consideration
28943 of avoiding elaboration errors, but rather from extra-lingual logic
28944 requirements. Consider this example:
28945
28946 @smallexample @c ada
28947 with Init_Constants;
28948 package Constants is
28949    X : Integer := 0;
28950    Y : Integer := 0;
28951 end Constants;
28952
28953 package Init_Constants is
28954    procedure P; -- require a body
28955 end Init_Constants;
28956
28957 with Constants;
28958 package body Init_Constants is
28959    procedure P is begin null; end;
28960 begin
28961    Constants.X := 3;
28962    Constants.Y := 4;
28963 end Init_Constants;
28964
28965 with Constants;
28966 package Calc is
28967    Z : Integer := Constants.X + Constants.Y;
28968 end Calc;
28969
28970 with Calc;
28971 with Text_IO; use Text_IO;
28972 procedure Main is
28973 begin
28974    Put_Line (Calc.Z'Img);
28975 end Main;
28976 @end smallexample
28977
28978 @noindent
28979 In this example, there is more than one valid order of elaboration. For
28980 example both the following are correct orders:
28981
28982 @smallexample
28983 Init_Constants spec
28984 Constants spec
28985 Calc spec
28986 Init_Constants body
28987 Main body
28988
28989   and
28990
28991 Init_Constants spec
28992 Init_Constants body
28993 Constants spec
28994 Calc spec
28995 Main body
28996 @end smallexample
28997
28998 @noindent
28999 There is no language rule to prefer one or the other, both are correct
29000 from an order of elaboration point of view. But the programmatic effects
29001 of the two orders are very different. In the first, the elaboration routine
29002 of @code{Calc} initializes @code{Z} to zero, and then the main program
29003 runs with this value of zero. But in the second order, the elaboration
29004 routine of @code{Calc} runs after the body of Init_Constants has set
29005 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29006 runs.
29007
29008 One could perhaps by applying pretty clever non-artificial intelligence
29009 to the situation guess that it is more likely that the second order of
29010 elaboration is the one desired, but there is no formal linguistic reason
29011 to prefer one over the other. In fact in this particular case, GNAT will
29012 prefer the second order, because of the rule that bodies are elaborated
29013 as soon as possible, but it's just luck that this is what was wanted
29014 (if indeed the second order was preferred).
29015
29016 If the program cares about the order of elaboration routines in a case like
29017 this, it is important to specify the order required. In this particular
29018 case, that could have been achieved by adding to the spec of Calc:
29019
29020 @smallexample @c ada
29021 pragma Elaborate_All (Constants);
29022 @end smallexample
29023
29024 @noindent
29025 which requires that the body (if any) and spec of @code{Constants},
29026 as well as the body and spec of any unit @code{with}'ed by
29027 @code{Constants} be elaborated before @code{Calc} is elaborated.
29028
29029 Clearly no automatic method can always guess which alternative you require,
29030 and if you are working with legacy code that had constraints of this kind
29031 which were not properly specified by adding @code{Elaborate} or
29032 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29033 compilers can choose different orders.
29034
29035 However, GNAT does attempt to diagnose the common situation where there
29036 are uninitialized variables in the visible part of a package spec, and the
29037 corresponding package body has an elaboration block that directly or
29038 indirectly initialized one or more of these variables. This is the situation
29039 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29040 a warning that suggests this addition if it detects this situation.
29041
29042 The @code{gnatbind}
29043 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29044 out problems. This switch causes bodies to be elaborated as late as possible
29045 instead of as early as possible. In the example above, it would have forced
29046 the choice of the first elaboration order. If you get different results
29047 when using this switch, and particularly if one set of results is right,
29048 and one is wrong as far as you are concerned, it shows that you have some
29049 missing @code{Elaborate} pragmas. For the example above, we have the
29050 following output:
29051
29052 @smallexample
29053 gnatmake -f -q main
29054 main
29055  7
29056 gnatmake -f -q main -bargs -p
29057 main
29058  0
29059 @end smallexample
29060
29061 @noindent
29062 It is of course quite unlikely that both these results are correct, so
29063 it is up to you in a case like this to investigate the source of the
29064 difference, by looking at the two elaboration orders that are chosen,
29065 and figuring out which is correct, and then adding the necessary
29066 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29067
29068
29069
29070 @c *******************************
29071 @node Conditional Compilation
29072 @appendix Conditional Compilation
29073 @c *******************************
29074 @cindex Conditional compilation
29075
29076 @noindent
29077 It is often necessary to arrange for a single source program
29078 to serve multiple purposes, where it is compiled in different
29079 ways to achieve these different goals. Some examples of the
29080 need for this feature are
29081
29082 @itemize @bullet
29083 @item  Adapting a program to a different hardware environment
29084 @item  Adapting a program to a different target architecture
29085 @item  Turning debugging features on and off
29086 @item  Arranging for a program to compile with different compilers
29087 @end itemize
29088
29089 @noindent
29090 In C, or C++, the typical approach would be to use the preprocessor
29091 that is defined as part of the language. The Ada language does not
29092 contain such a feature. This is not an oversight, but rather a very
29093 deliberate design decision, based on the experience that overuse of
29094 the preprocessing features in C and C++ can result in programs that
29095 are extremely difficult to maintain. For example, if we have ten
29096 switches that can be on or off, this means that there are a thousand
29097 separate programs, any one of which might not even be syntactically
29098 correct, and even if syntactically correct, the resulting program
29099 might not work correctly. Testing all combinations can quickly become
29100 impossible.
29101
29102 Nevertheless, the need to tailor programs certainly exists, and in
29103 this Appendix we will discuss how this can
29104 be achieved using Ada in general, and GNAT in particular.
29105
29106 @menu
29107 * Use of Boolean Constants::
29108 * Debugging - A Special Case::
29109 * Conditionalizing Declarations::
29110 * Use of Alternative Implementations::
29111 * Preprocessing::
29112 @end menu
29113
29114 @node Use of Boolean Constants
29115 @section Use of Boolean Constants
29116
29117 @noindent
29118 In the case where the difference is simply which code
29119 sequence is executed, the cleanest solution is to use Boolean
29120 constants to control which code is executed.
29121
29122 @smallexample @c ada
29123 @group
29124 FP_Initialize_Required : constant Boolean := True;
29125 @dots{}
29126 if FP_Initialize_Required then
29127 @dots{}
29128 end if;
29129 @end group
29130 @end smallexample
29131
29132 @noindent
29133 Not only will the code inside the @code{if} statement not be executed if
29134 the constant Boolean is @code{False}, but it will also be completely
29135 deleted from the program.
29136 However, the code is only deleted after the @code{if} statement
29137 has been checked for syntactic and semantic correctness.
29138 (In contrast, with preprocessors the code is deleted before the
29139 compiler ever gets to see it, so it is not checked until the switch
29140 is turned on.)
29141 @cindex Preprocessors (contrasted with conditional compilation)
29142
29143 Typically the Boolean constants will be in a separate package,
29144 something like:
29145
29146 @smallexample @c ada
29147 @group
29148 package Config is
29149    FP_Initialize_Required : constant Boolean := True;
29150    Reset_Available        : constant Boolean := False;
29151    @dots{}
29152 end Config;
29153 @end group
29154 @end smallexample
29155
29156 @noindent
29157 The @code{Config} package exists in multiple forms for the various targets,
29158 with an appropriate script selecting the version of @code{Config} needed.
29159 Then any other unit requiring conditional compilation can do a @code{with}
29160 of @code{Config} to make the constants visible.
29161
29162
29163 @node Debugging - A Special Case
29164 @section Debugging - A Special Case
29165
29166 @noindent
29167 A common use of conditional code is to execute statements (for example
29168 dynamic checks, or output of intermediate results) under control of a
29169 debug switch, so that the debugging behavior can be turned on and off.
29170 This can be done using a Boolean constant to control whether the code
29171 is active:
29172
29173 @smallexample @c ada
29174 @group
29175 if Debugging then
29176    Put_Line ("got to the first stage!");
29177 end if;
29178 @end group
29179 @end smallexample
29180
29181 @noindent
29182 or
29183
29184 @smallexample @c ada
29185 @group
29186 if Debugging and then Temperature > 999.0 then
29187    raise Temperature_Crazy;
29188 end if;
29189 @end group
29190 @end smallexample
29191
29192 @noindent
29193 Since this is a common case, there are special features to deal with
29194 this in a convenient manner. For the case of tests, Ada 2005 has added
29195 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29196 @cindex pragma @code{Assert}
29197 on the @code{Assert} pragma that has always been available in GNAT, so this
29198 feature may be used with GNAT even if you are not using Ada 2005 features.
29199 The use of pragma @code{Assert} is described in
29200 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29201 example, the last test could be written:
29202
29203 @smallexample @c ada
29204 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29205 @end smallexample
29206
29207 @noindent
29208 or simply
29209
29210 @smallexample @c ada
29211 pragma Assert (Temperature <= 999.0);
29212 @end smallexample
29213
29214 @noindent
29215 In both cases, if assertions are active and the temperature is excessive,
29216 the exception @code{Assert_Failure} will be raised, with the given string in
29217 the first case or a string indicating the location of the pragma in the second
29218 case used as the exception message.
29219
29220 You can turn assertions on and off by using the @code{Assertion_Policy}
29221 pragma.
29222 @cindex pragma @code{Assertion_Policy}
29223 This is an Ada 2005 pragma which is implemented in all modes by
29224 GNAT, but only in the latest versions of GNAT which include Ada 2005
29225 capability. Alternatively, you can use the @option{-gnata} switch
29226 @cindex @option{-gnata} switch
29227 to enable assertions from the command line (this is recognized by all versions
29228 of GNAT).
29229
29230 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29231 @code{Debug} can be used:
29232 @cindex pragma @code{Debug}
29233
29234 @smallexample @c ada
29235 pragma Debug (Put_Line ("got to the first stage!"));
29236 @end smallexample
29237
29238 @noindent
29239 If debug pragmas are enabled, the argument, which must be of the form of
29240 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29241 Only one call can be present, but of course a special debugging procedure
29242 containing any code you like can be included in the program and then
29243 called in a pragma @code{Debug} argument as needed.
29244
29245 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29246 construct is that pragma @code{Debug} can appear in declarative contexts,
29247 such as at the very beginning of a procedure, before local declarations have
29248 been elaborated.
29249
29250 Debug pragmas are enabled using either the @option{-gnata} switch that also
29251 controls assertions, or with a separate Debug_Policy pragma.
29252 @cindex pragma @code{Debug_Policy}
29253 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29254 in Ada 95 and Ada 83 programs as well), and is analogous to
29255 pragma @code{Assertion_Policy} to control assertions.
29256
29257 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29258 and thus they can appear in @file{gnat.adc} if you are not using a
29259 project file, or in the file designated to contain configuration pragmas
29260 in a project file.
29261 They then apply to all subsequent compilations. In practice the use of
29262 the @option{-gnata} switch is often the most convenient method of controlling
29263 the status of these pragmas.
29264
29265 Note that a pragma is not a statement, so in contexts where a statement
29266 sequence is required, you can't just write a pragma on its own. You have
29267 to add a @code{null} statement.
29268
29269 @smallexample @c ada
29270 @group
29271 if @dots{} then
29272    @dots{} -- some statements
29273 else
29274    pragma Assert (Num_Cases < 10);
29275    null;
29276 end if;
29277 @end group
29278 @end smallexample
29279
29280
29281 @node Conditionalizing Declarations
29282 @section Conditionalizing Declarations
29283
29284 @noindent
29285 In some cases, it may be necessary to conditionalize declarations to meet
29286 different requirements. For example we might want a bit string whose length
29287 is set to meet some hardware message requirement.
29288
29289 In some cases, it may be possible to do this using declare blocks controlled
29290 by conditional constants:
29291
29292 @smallexample @c ada
29293 @group
29294 if Small_Machine then
29295    declare
29296       X : Bit_String (1 .. 10);
29297    begin
29298       @dots{}
29299    end;
29300 else
29301    declare
29302       X : Large_Bit_String (1 .. 1000);
29303    begin
29304       @dots{}
29305    end;
29306 end if;
29307 @end group
29308 @end smallexample
29309
29310 @noindent
29311 Note that in this approach, both declarations are analyzed by the
29312 compiler so this can only be used where both declarations are legal,
29313 even though one of them will not be used.
29314
29315 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29316 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29317 that are parameterized by these constants. For example
29318
29319 @smallexample @c ada
29320 @group
29321 for Rec use
29322   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29323 end record;
29324 @end group
29325 @end smallexample
29326
29327 @noindent
29328 If @code{Bits_Per_Word} is set to 32, this generates either
29329
29330 @smallexample @c ada
29331 @group
29332 for Rec use
29333   Field1 at 0 range 0 .. 32;
29334 end record;
29335 @end group
29336 @end smallexample
29337
29338 @noindent
29339 for the big endian case, or
29340
29341 @smallexample @c ada
29342 @group
29343 for Rec use record
29344   Field1 at 0 range 10 .. 32;
29345 end record;
29346 @end group
29347 @end smallexample
29348
29349 @noindent
29350 for the little endian case. Since a powerful subset of Ada expression
29351 notation is usable for creating static constants, clever use of this
29352 feature can often solve quite difficult problems in conditionalizing
29353 compilation (note incidentally that in Ada 95, the little endian
29354 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29355 need to define this one yourself).
29356
29357
29358 @node Use of Alternative Implementations
29359 @section Use of Alternative Implementations
29360
29361 @noindent
29362 In some cases, none of the approaches described above are adequate. This
29363 can occur for example if the set of declarations required is radically
29364 different for two different configurations.
29365
29366 In this situation, the official Ada way of dealing with conditionalizing
29367 such code is to write separate units for the different cases. As long as
29368 this does not result in excessive duplication of code, this can be done
29369 without creating maintenance problems. The approach is to share common
29370 code as far as possible, and then isolate the code and declarations
29371 that are different. Subunits are often a convenient method for breaking
29372 out a piece of a unit that is to be conditionalized, with separate files
29373 for different versions of the subunit for different targets, where the
29374 build script selects the right one to give to the compiler.
29375 @cindex Subunits (and conditional compilation)
29376
29377 As an example, consider a situation where a new feature in Ada 2005
29378 allows something to be done in a really nice way. But your code must be able
29379 to compile with an Ada 95 compiler. Conceptually you want to say:
29380
29381 @smallexample @c ada
29382 @group
29383 if Ada_2005 then
29384    @dots{} neat Ada 2005 code
29385 else
29386    @dots{} not quite as neat Ada 95 code
29387 end if;
29388 @end group
29389 @end smallexample
29390
29391 @noindent
29392 where @code{Ada_2005} is a Boolean constant.
29393
29394 But this won't work when @code{Ada_2005} is set to @code{False},
29395 since the @code{then} clause will be illegal for an Ada 95 compiler.
29396 (Recall that although such unreachable code would eventually be deleted
29397 by the compiler, it still needs to be legal.  If it uses features
29398 introduced in Ada 2005, it will be illegal in Ada 95.)
29399
29400 So instead we write
29401
29402 @smallexample @c ada
29403 procedure Insert is separate;
29404 @end smallexample
29405
29406 @noindent
29407 Then we have two files for the subunit @code{Insert}, with the two sets of
29408 code.
29409 If the package containing this is called @code{File_Queries}, then we might
29410 have two files
29411
29412 @itemize @bullet
29413 @item    @file{file_queries-insert-2005.adb}
29414 @item    @file{file_queries-insert-95.adb}
29415 @end itemize
29416
29417 @noindent
29418 and the build script renames the appropriate file to
29419
29420 @smallexample
29421 file_queries-insert.adb
29422 @end smallexample
29423
29424 @noindent
29425 and then carries out the compilation.
29426
29427 This can also be done with project files' naming schemes. For example:
29428
29429 @smallexample @c project
29430 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29431 @end smallexample
29432
29433 @noindent
29434 Note also that with project files it is desirable to use a different extension
29435 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29436 conflict may arise through another commonly used feature: to declare as part
29437 of the project a set of directories containing all the sources obeying the
29438 default naming scheme.
29439
29440 The use of alternative units is certainly feasible in all situations,
29441 and for example the Ada part of the GNAT run-time is conditionalized
29442 based on the target architecture using this approach. As a specific example,
29443 consider the implementation of the AST feature in VMS. There is one
29444 spec:
29445
29446 @smallexample
29447 s-asthan.ads
29448 @end smallexample
29449
29450 @noindent
29451 which is the same for all architectures, and three bodies:
29452
29453 @table @file
29454 @item    s-asthan.adb
29455 used for all non-VMS operating systems
29456 @item    s-asthan-vms-alpha.adb
29457 used for VMS on the Alpha
29458 @item    s-asthan-vms-ia64.adb
29459 used for VMS on the ia64
29460 @end table
29461
29462 @noindent
29463 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29464 this operating system feature is not available, and the two remaining
29465 versions interface with the corresponding versions of VMS to provide
29466 VMS-compatible AST handling. The GNAT build script knows the architecture
29467 and operating system, and automatically selects the right version,
29468 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29469
29470 Another style for arranging alternative implementations is through Ada's
29471 access-to-subprogram facility.
29472 In case some functionality is to be conditionally included,
29473 you can declare an access-to-procedure variable @code{Ref} that is initialized
29474 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29475 when appropriate.
29476 In some library package, set @code{Ref} to @code{Proc'Access} for some
29477 procedure @code{Proc} that performs the relevant processing.
29478 The initialization only occurs if the library package is included in the
29479 program.
29480 The same idea can also be implemented using tagged types and dispatching
29481 calls.
29482
29483
29484 @node Preprocessing
29485 @section Preprocessing
29486 @cindex Preprocessing
29487
29488 @noindent
29489 Although it is quite possible to conditionalize code without the use of
29490 C-style preprocessing, as described earlier in this section, it is
29491 nevertheless convenient in some cases to use the C approach. Moreover,
29492 older Ada compilers have often provided some preprocessing capability,
29493 so legacy code may depend on this approach, even though it is not
29494 standard.
29495
29496 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29497 extent on the various preprocessors that have been used
29498 with legacy code on other compilers, to enable easier transition).
29499
29500 The preprocessor may be used in two separate modes. It can be used quite
29501 separately from the compiler, to generate a separate output source file
29502 that is then fed to the compiler as a separate step. This is the
29503 @code{gnatprep} utility, whose use is fully described in
29504 @ref{Preprocessing Using gnatprep}.
29505 @cindex @code{gnatprep}
29506
29507 The preprocessing language allows such constructs as
29508
29509 @smallexample
29510 @group
29511 #if DEBUG or PRIORITY > 4 then
29512    bunch of declarations
29513 #else
29514    completely different bunch of declarations
29515 #end if;
29516 @end group
29517 @end smallexample
29518
29519 @noindent
29520 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29521 defined either on the command line or in a separate file.
29522
29523 The other way of running the preprocessor is even closer to the C style and
29524 often more convenient. In this approach the preprocessing is integrated into
29525 the compilation process. The compiler is fed the preprocessor input which
29526 includes @code{#if} lines etc, and then the compiler carries out the
29527 preprocessing internally and processes the resulting output.
29528 For more details on this approach, see @ref{Integrated Preprocessing}.
29529
29530
29531 @c *******************************
29532 @node Inline Assembler
29533 @appendix Inline Assembler
29534 @c *******************************
29535
29536 @noindent
29537 If you need to write low-level software that interacts directly
29538 with the hardware, Ada provides two ways to incorporate assembly
29539 language code into your program.  First, you can import and invoke
29540 external routines written in assembly language, an Ada feature fully
29541 supported by GNAT@.  However, for small sections of code it may be simpler
29542 or more efficient to include assembly language statements directly
29543 in your Ada source program, using the facilities of the implementation-defined
29544 package @code{System.Machine_Code}, which incorporates the gcc
29545 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29546 including the following:
29547
29548 @itemize @bullet
29549 @item No need to use non-Ada tools
29550 @item Consistent interface over different targets
29551 @item Automatic usage of the proper calling conventions
29552 @item Access to Ada constants and variables
29553 @item Definition of intrinsic routines
29554 @item Possibility of inlining a subprogram comprising assembler code
29555 @item Code optimizer can take Inline Assembler code into account
29556 @end itemize
29557
29558 This chapter presents a series of examples to show you how to use
29559 the Inline Assembler.  Although it focuses on the Intel x86,
29560 the general approach applies also to other processors.
29561 It is assumed that you are familiar with Ada
29562 and with assembly language programming.
29563
29564 @menu
29565 * Basic Assembler Syntax::
29566 * A Simple Example of Inline Assembler::
29567 * Output Variables in Inline Assembler::
29568 * Input Variables in Inline Assembler::
29569 * Inlining Inline Assembler Code::
29570 * Other Asm Functionality::
29571 @end menu
29572
29573 @c ---------------------------------------------------------------------------
29574 @node Basic Assembler Syntax
29575 @section Basic Assembler Syntax
29576
29577 @noindent
29578 The assembler used by GNAT and gcc is based not on the Intel assembly
29579 language, but rather on a language that descends from the AT&T Unix
29580 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29581 The following table summarizes the main features of @emph{as} syntax
29582 and points out the differences from the Intel conventions.
29583 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29584 pre-processor) documentation for further information.
29585
29586 @table @asis
29587 @item Register names
29588 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29589 @*
29590 Intel: No extra punctuation; for example @code{eax}
29591
29592 @item Immediate operand
29593 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29594 @*
29595 Intel: No extra punctuation; for example @code{4}
29596
29597 @item Address
29598 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29599 @*
29600 Intel: No extra punctuation; for example @code{loc}
29601
29602 @item Memory contents
29603 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29604 @*
29605 Intel: Square brackets; for example @code{[loc]}
29606
29607 @item Register contents
29608 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29609 @*
29610 Intel: Square brackets; for example @code{[eax]}
29611
29612 @item Hexadecimal numbers
29613 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29614 @*
29615 Intel: Trailing ``h''; for example @code{A0h}
29616
29617 @item Operand size
29618 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29619 a 16-bit word
29620 @*
29621 Intel: Implicit, deduced by assembler; for example @code{mov}
29622
29623 @item Instruction repetition
29624 gcc / @emph{as}: Split into two lines; for example
29625 @*
29626 @code{rep}
29627 @*
29628 @code{stosl}
29629 @*
29630 Intel: Keep on one line; for example @code{rep stosl}
29631
29632 @item Order of operands
29633 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29634 @*
29635 Intel: Destination first; for example @code{mov eax, 4}
29636 @end table
29637
29638 @c ---------------------------------------------------------------------------
29639 @node A Simple Example of Inline Assembler
29640 @section A Simple Example of Inline Assembler
29641
29642 @noindent
29643 The following example will generate a single assembly language statement,
29644 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29645 the example will be useful in illustrating the basics of
29646 the Inline Assembler facility.
29647
29648 @smallexample @c ada
29649 @group
29650 with System.Machine_Code; use System.Machine_Code;
29651 procedure Nothing is
29652 begin
29653    Asm ("nop");
29654 end Nothing;
29655 @end group
29656 @end smallexample
29657
29658 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29659 here it takes one parameter, a @emph{template string} that must be a static
29660 expression and that will form the generated instruction.
29661 @code{Asm} may be regarded as a compile-time procedure that parses
29662 the template string and additional parameters (none here),
29663 from which it generates a sequence of assembly language instructions.
29664
29665 The examples in this chapter will illustrate several of the forms
29666 for invoking @code{Asm}; a complete specification of the syntax
29667 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29668 Manual}.
29669
29670 Under the standard GNAT conventions, the @code{Nothing} procedure
29671 should be in a file named @file{nothing.adb}.
29672 You can build the executable in the usual way:
29673 @smallexample
29674 gnatmake nothing
29675 @end smallexample
29676 However, the interesting aspect of this example is not its run-time behavior
29677 but rather the generated assembly code.
29678 To see this output, invoke the compiler as follows:
29679 @smallexample
29680    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29681 @end smallexample
29682 where the options are:
29683
29684 @table @code
29685 @item -c
29686 compile only (no bind or link)
29687 @item -S
29688 generate assembler listing
29689 @item -fomit-frame-pointer
29690 do not set up separate stack frames
29691 @item -gnatp
29692 do not add runtime checks
29693 @end table
29694
29695 This gives a human-readable assembler version of the code. The resulting
29696 file will have the same name as the Ada source file, but with a @code{.s}
29697 extension. In our example, the file @file{nothing.s} has the following
29698 contents:
29699
29700 @smallexample
29701 @group
29702 .file "nothing.adb"
29703 gcc2_compiled.:
29704 ___gnu_compiled_ada:
29705 .text
29706    .align 4
29707 .globl __ada_nothing
29708 __ada_nothing:
29709 #APP
29710    nop
29711 #NO_APP
29712    jmp L1
29713    .align 2,0x90
29714 L1:
29715    ret
29716 @end group
29717 @end smallexample
29718
29719 The assembly code you included is clearly indicated by
29720 the compiler, between the @code{#APP} and @code{#NO_APP}
29721 delimiters. The character before the 'APP' and 'NOAPP'
29722 can differ on different targets. For example, GNU/Linux uses '#APP' while
29723 on NT you will see '/APP'.
29724
29725 If you make a mistake in your assembler code (such as using the
29726 wrong size modifier, or using a wrong operand for the instruction) GNAT
29727 will report this error in a temporary file, which will be deleted when
29728 the compilation is finished.  Generating an assembler file will help
29729 in such cases, since you can assemble this file separately using the
29730 @emph{as} assembler that comes with gcc.
29731
29732 Assembling the file using the command
29733
29734 @smallexample
29735 as @file{nothing.s}
29736 @end smallexample
29737 @noindent
29738 will give you error messages whose lines correspond to the assembler
29739 input file, so you can easily find and correct any mistakes you made.
29740 If there are no errors, @emph{as} will generate an object file
29741 @file{nothing.out}.
29742
29743 @c ---------------------------------------------------------------------------
29744 @node Output Variables in Inline Assembler
29745 @section Output Variables in Inline Assembler
29746
29747 @noindent
29748 The examples in this section, showing how to access the processor flags,
29749 illustrate how to specify the destination operands for assembly language
29750 statements.
29751
29752 @smallexample @c ada
29753 @group
29754 with Interfaces; use Interfaces;
29755 with Ada.Text_IO; use Ada.Text_IO;
29756 with System.Machine_Code; use System.Machine_Code;
29757 procedure Get_Flags is
29758    Flags : Unsigned_32;
29759    use ASCII;
29760 begin
29761    Asm ("pushfl"          & LF & HT & -- push flags on stack
29762         "popl %%eax"      & LF & HT & -- load eax with flags
29763         "movl %%eax, %0",             -- store flags in variable
29764         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29765    Put_Line ("Flags register:" & Flags'Img);
29766 end Get_Flags;
29767 @end group
29768 @end smallexample
29769
29770 In order to have a nicely aligned assembly listing, we have separated
29771 multiple assembler statements in the Asm template string with linefeed
29772 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29773 The resulting section of the assembly output file is:
29774
29775 @smallexample
29776 @group
29777 #APP
29778    pushfl
29779    popl %eax
29780    movl %eax, -40(%ebp)
29781 #NO_APP
29782 @end group
29783 @end smallexample
29784
29785 It would have been legal to write the Asm invocation as:
29786
29787 @smallexample
29788 Asm ("pushfl popl %%eax movl %%eax, %0")
29789 @end smallexample
29790
29791 but in the generated assembler file, this would come out as:
29792
29793 @smallexample
29794 #APP
29795    pushfl popl %eax movl %eax, -40(%ebp)
29796 #NO_APP
29797 @end smallexample
29798
29799 which is not so convenient for the human reader.
29800
29801 We use Ada comments
29802 at the end of each line to explain what the assembler instructions
29803 actually do.  This is a useful convention.
29804
29805 When writing Inline Assembler instructions, you need to precede each register
29806 and variable name with a percent sign.  Since the assembler already requires
29807 a percent sign at the beginning of a register name, you need two consecutive
29808 percent signs for such names in the Asm template string, thus @code{%%eax}.
29809 In the generated assembly code, one of the percent signs will be stripped off.
29810
29811 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29812 variables: operands you later define using @code{Input} or @code{Output}
29813 parameters to @code{Asm}.
29814 An output variable is illustrated in
29815 the third statement in the Asm template string:
29816 @smallexample
29817 movl %%eax, %0
29818 @end smallexample
29819 The intent is to store the contents of the eax register in a variable that can
29820 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29821 necessarily work, since the compiler might optimize by using a register
29822 to hold Flags, and the expansion of the @code{movl} instruction would not be
29823 aware of this optimization.  The solution is not to store the result directly
29824 but rather to advise the compiler to choose the correct operand form;
29825 that is the purpose of the @code{%0} output variable.
29826
29827 Information about the output variable is supplied in the @code{Outputs}
29828 parameter to @code{Asm}:
29829 @smallexample
29830 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29831 @end smallexample
29832
29833 The output is defined by the @code{Asm_Output} attribute of the target type;
29834 the general format is
29835 @smallexample
29836 Type'Asm_Output (constraint_string, variable_name)
29837 @end smallexample
29838
29839 The constraint string directs the compiler how
29840 to store/access the associated variable.  In the example
29841 @smallexample
29842 Unsigned_32'Asm_Output ("=m", Flags);
29843 @end smallexample
29844 the @code{"m"} (memory) constraint tells the compiler that the variable
29845 @code{Flags} should be stored in a memory variable, thus preventing
29846 the optimizer from keeping it in a register.  In contrast,
29847 @smallexample
29848 Unsigned_32'Asm_Output ("=r", Flags);
29849 @end smallexample
29850 uses the @code{"r"} (register) constraint, telling the compiler to
29851 store the variable in a register.
29852
29853 If the constraint is preceded by the equal character (@strong{=}), it tells
29854 the compiler that the variable will be used to store data into it.
29855
29856 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29857 allowing the optimizer to choose whatever it deems best.
29858
29859 There are a fairly large number of constraints, but the ones that are
29860 most useful (for the Intel x86 processor) are the following:
29861
29862 @table @code
29863 @item =
29864 output constraint
29865 @item g
29866 global (i.e.@: can be stored anywhere)
29867 @item m
29868 in memory
29869 @item I
29870 a constant
29871 @item a
29872 use eax
29873 @item b
29874 use ebx
29875 @item c
29876 use ecx
29877 @item d
29878 use edx
29879 @item S
29880 use esi
29881 @item D
29882 use edi
29883 @item r
29884 use one of eax, ebx, ecx or edx
29885 @item q
29886 use one of eax, ebx, ecx, edx, esi or edi
29887 @end table
29888
29889 The full set of constraints is described in the gcc and @emph{as}
29890 documentation; note that it is possible to combine certain constraints
29891 in one constraint string.
29892
29893 You specify the association of an output variable with an assembler operand
29894 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29895 integer.  Thus in
29896 @smallexample @c ada
29897 @group
29898 Asm ("pushfl"          & LF & HT & -- push flags on stack
29899      "popl %%eax"      & LF & HT & -- load eax with flags
29900      "movl %%eax, %0",             -- store flags in variable
29901      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29902 @end group
29903 @end smallexample
29904 @noindent
29905 @code{%0} will be replaced in the expanded code by the appropriate operand,
29906 whatever
29907 the compiler decided for the @code{Flags} variable.
29908
29909 In general, you may have any number of output variables:
29910 @itemize @bullet
29911 @item
29912 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29913 @item
29914 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29915 of @code{Asm_Output} attributes
29916 @end itemize
29917
29918 For example:
29919 @smallexample @c ada
29920 @group
29921 Asm ("movl %%eax, %0" & LF & HT &
29922      "movl %%ebx, %1" & LF & HT &
29923      "movl %%ecx, %2",
29924      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29925                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29926                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29927 @end group
29928 @end smallexample
29929 @noindent
29930 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29931 in the Ada program.
29932
29933 As a variation on the @code{Get_Flags} example, we can use the constraints
29934 string to direct the compiler to store the eax register into the @code{Flags}
29935 variable, instead of including the store instruction explicitly in the
29936 @code{Asm} template string:
29937
29938 @smallexample @c ada
29939 @group
29940 with Interfaces; use Interfaces;
29941 with Ada.Text_IO; use Ada.Text_IO;
29942 with System.Machine_Code; use System.Machine_Code;
29943 procedure Get_Flags_2 is
29944    Flags : Unsigned_32;
29945    use ASCII;
29946 begin
29947    Asm ("pushfl"      & LF & HT & -- push flags on stack
29948         "popl %%eax",             -- save flags in eax
29949         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29950    Put_Line ("Flags register:" & Flags'Img);
29951 end Get_Flags_2;
29952 @end group
29953 @end smallexample
29954
29955 @noindent
29956 The @code{"a"} constraint tells the compiler that the @code{Flags}
29957 variable will come from the eax register. Here is the resulting code:
29958
29959 @smallexample
29960 @group
29961 #APP
29962    pushfl
29963    popl %eax
29964 #NO_APP
29965    movl %eax,-40(%ebp)
29966 @end group
29967 @end smallexample
29968
29969 @noindent
29970 The compiler generated the store of eax into Flags after
29971 expanding the assembler code.
29972
29973 Actually, there was no need to pop the flags into the eax register;
29974 more simply, we could just pop the flags directly into the program variable:
29975
29976 @smallexample @c ada
29977 @group
29978 with Interfaces; use Interfaces;
29979 with Ada.Text_IO; use Ada.Text_IO;
29980 with System.Machine_Code; use System.Machine_Code;
29981 procedure Get_Flags_3 is
29982    Flags : Unsigned_32;
29983    use ASCII;
29984 begin
29985    Asm ("pushfl"  & LF & HT & -- push flags on stack
29986         "pop %0",             -- save flags in Flags
29987         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29988    Put_Line ("Flags register:" & Flags'Img);
29989 end Get_Flags_3;
29990 @end group
29991 @end smallexample
29992
29993 @c ---------------------------------------------------------------------------
29994 @node Input Variables in Inline Assembler
29995 @section Input Variables in Inline Assembler
29996
29997 @noindent
29998 The example in this section illustrates how to specify the source operands
29999 for assembly language statements.
30000 The program simply increments its input value by 1:
30001
30002 @smallexample @c ada
30003 @group
30004 with Interfaces; use Interfaces;
30005 with Ada.Text_IO; use Ada.Text_IO;
30006 with System.Machine_Code; use System.Machine_Code;
30007 procedure Increment is
30008
30009    function Incr (Value : Unsigned_32) return Unsigned_32 is
30010       Result : Unsigned_32;
30011    begin
30012       Asm ("incl %0",
30013            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30014            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30015       return Result;
30016    end Incr;
30017
30018    Value : Unsigned_32;
30019
30020 begin
30021    Value := 5;
30022    Put_Line ("Value before is" & Value'Img);
30023    Value := Incr (Value);
30024    Put_Line ("Value after is" & Value'Img);
30025 end Increment;
30026 @end group
30027 @end smallexample
30028
30029 The @code{Outputs} parameter to @code{Asm} specifies
30030 that the result will be in the eax register and that it is to be stored
30031 in the @code{Result} variable.
30032
30033 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30034 but with an @code{Asm_Input} attribute.
30035 The @code{"="} constraint, indicating an output value, is not present.
30036
30037 You can have multiple input variables, in the same way that you can have more
30038 than one output variable.
30039
30040 The parameter count (%0, %1) etc, now starts at the first input
30041 statement, and continues with the output statements.
30042 When both parameters use the same variable, the
30043 compiler will treat them as the same %n operand, which is the case here.
30044
30045 Just as the @code{Outputs} parameter causes the register to be stored into the
30046 target variable after execution of the assembler statements, so does the
30047 @code{Inputs} parameter cause its variable to be loaded into the register
30048 before execution of the assembler statements.
30049
30050 Thus the effect of the @code{Asm} invocation is:
30051 @enumerate
30052 @item load the 32-bit value of @code{Value} into eax
30053 @item execute the @code{incl %eax} instruction
30054 @item store the contents of eax into the @code{Result} variable
30055 @end enumerate
30056
30057 The resulting assembler file (with @option{-O2} optimization) contains:
30058 @smallexample
30059 @group
30060 _increment__incr.1:
30061    subl $4,%esp
30062    movl 8(%esp),%eax
30063 #APP
30064    incl %eax
30065 #NO_APP
30066    movl %eax,%edx
30067    movl %ecx,(%esp)
30068    addl $4,%esp
30069    ret
30070 @end group
30071 @end smallexample
30072
30073 @c ---------------------------------------------------------------------------
30074 @node Inlining Inline Assembler Code
30075 @section Inlining Inline Assembler Code
30076
30077 @noindent
30078 For a short subprogram such as the @code{Incr} function in the previous
30079 section, the overhead of the call and return (creating / deleting the stack
30080 frame) can be significant, compared to the amount of code in the subprogram
30081 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30082 which directs the compiler to expand invocations of the subprogram at the
30083 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30084 Here is the resulting program:
30085
30086 @smallexample @c ada
30087 @group
30088 with Interfaces; use Interfaces;
30089 with Ada.Text_IO; use Ada.Text_IO;
30090 with System.Machine_Code; use System.Machine_Code;
30091 procedure Increment_2 is
30092
30093    function Incr (Value : Unsigned_32) return Unsigned_32 is
30094       Result : Unsigned_32;
30095    begin
30096       Asm ("incl %0",
30097            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30098            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30099       return Result;
30100    end Incr;
30101    pragma Inline (Increment);
30102
30103    Value : Unsigned_32;
30104
30105 begin
30106    Value := 5;
30107    Put_Line ("Value before is" & Value'Img);
30108    Value := Increment (Value);
30109    Put_Line ("Value after is" & Value'Img);
30110 end Increment_2;
30111 @end group
30112 @end smallexample
30113
30114 Compile the program with both optimization (@option{-O2}) and inlining
30115 (@option{-gnatn}) enabled.
30116
30117 The @code{Incr} function is still compiled as usual, but at the
30118 point in @code{Increment} where our function used to be called:
30119
30120 @smallexample
30121 @group
30122 pushl %edi
30123 call _increment__incr.1
30124 @end group
30125 @end smallexample
30126
30127 @noindent
30128 the code for the function body directly appears:
30129
30130 @smallexample
30131 @group
30132 movl %esi,%eax
30133 #APP
30134    incl %eax
30135 #NO_APP
30136    movl %eax,%edx
30137 @end group
30138 @end smallexample
30139
30140 @noindent
30141 thus saving the overhead of stack frame setup and an out-of-line call.
30142
30143 @c ---------------------------------------------------------------------------
30144 @node Other Asm Functionality
30145 @section Other @code{Asm} Functionality
30146
30147 @noindent
30148 This section describes two important parameters to the @code{Asm}
30149 procedure: @code{Clobber}, which identifies register usage;
30150 and @code{Volatile}, which inhibits unwanted optimizations.
30151
30152 @menu
30153 * The Clobber Parameter::
30154 * The Volatile Parameter::
30155 @end menu
30156
30157 @c ---------------------------------------------------------------------------
30158 @node The Clobber Parameter
30159 @subsection The @code{Clobber} Parameter
30160
30161 @noindent
30162 One of the dangers of intermixing assembly language and a compiled language
30163 such as Ada is that the compiler needs to be aware of which registers are
30164 being used by the assembly code.  In some cases, such as the earlier examples,
30165 the constraint string is sufficient to indicate register usage (e.g.,
30166 @code{"a"} for
30167 the eax register).  But more generally, the compiler needs an explicit
30168 identification of the registers that are used by the Inline Assembly
30169 statements.
30170
30171 Using a register that the compiler doesn't know about
30172 could be a side effect of an instruction (like @code{mull}
30173 storing its result in both eax and edx).
30174 It can also arise from explicit register usage in your
30175 assembly code; for example:
30176 @smallexample
30177 @group
30178 Asm ("movl %0, %%ebx" & LF & HT &
30179      "movl %%ebx, %1",
30180      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30181      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30182 @end group
30183 @end smallexample
30184 @noindent
30185 where the compiler (since it does not analyze the @code{Asm} template string)
30186 does not know you are using the ebx register.
30187
30188 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30189 to identify the registers that will be used by your assembly code:
30190
30191 @smallexample
30192 @group
30193 Asm ("movl %0, %%ebx" & LF & HT &
30194      "movl %%ebx, %1",
30195      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30196      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30197      Clobber => "ebx");
30198 @end group
30199 @end smallexample
30200
30201 The Clobber parameter is a static string expression specifying the
30202 register(s) you are using.  Note that register names are @emph{not} prefixed
30203 by a percent sign. Also, if more than one register is used then their names
30204 are separated by commas; e.g., @code{"eax, ebx"}
30205
30206 The @code{Clobber} parameter has several additional uses:
30207 @enumerate
30208 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30209 @item Use ``register'' name @code{memory} if you changed a memory location
30210 @end enumerate
30211
30212 @c ---------------------------------------------------------------------------
30213 @node The Volatile Parameter
30214 @subsection The @code{Volatile} Parameter
30215 @cindex Volatile parameter
30216
30217 @noindent
30218 Compiler optimizations in the presence of Inline Assembler may sometimes have
30219 unwanted effects.  For example, when an @code{Asm} invocation with an input
30220 variable is inside a loop, the compiler might move the loading of the input
30221 variable outside the loop, regarding it as a one-time initialization.
30222
30223 If this effect is not desired, you can disable such optimizations by setting
30224 the @code{Volatile} parameter to @code{True}; for example:
30225
30226 @smallexample @c ada
30227 @group
30228 Asm ("movl %0, %%ebx" & LF & HT &
30229      "movl %%ebx, %1",
30230      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30231      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30232      Clobber  => "ebx",
30233      Volatile => True);
30234 @end group
30235 @end smallexample
30236
30237 By default, @code{Volatile} is set to @code{False} unless there is no
30238 @code{Outputs} parameter.
30239
30240 Although setting @code{Volatile} to @code{True} prevents unwanted
30241 optimizations, it will also disable other optimizations that might be
30242 important for efficiency. In general, you should set @code{Volatile}
30243 to @code{True} only if the compiler's optimizations have created
30244 problems.
30245 @c END OF INLINE ASSEMBLER CHAPTER
30246 @c ===============================
30247
30248 @c ***********************************
30249 @c * Compatibility and Porting Guide *
30250 @c ***********************************
30251 @node Compatibility and Porting Guide
30252 @appendix Compatibility and Porting Guide
30253
30254 @noindent
30255 This chapter describes the compatibility issues that may arise between
30256 GNAT and other Ada compilation systems (including those for Ada 83),
30257 and shows how GNAT can expedite porting
30258 applications developed in other Ada environments.
30259
30260 @menu
30261 * Compatibility with Ada 83::
30262 * Compatibility between Ada 95 and Ada 2005::
30263 * Implementation-dependent characteristics::
30264 * Compatibility with Other Ada Systems::
30265 * Representation Clauses::
30266 @ifclear vms
30267 @c Brief section is only in non-VMS version
30268 @c Full chapter is in VMS version
30269 * Compatibility with HP Ada 83::
30270 @end ifclear
30271 @ifset vms
30272 * Transitioning to 64-Bit GNAT for OpenVMS::
30273 @end ifset
30274 @end menu
30275
30276 @node Compatibility with Ada 83
30277 @section Compatibility with Ada 83
30278 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30279
30280 @noindent
30281 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30282 particular, the design intention was that the difficulties associated
30283 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30284 that occur when moving from one Ada 83 system to another.
30285
30286 However, there are a number of points at which there are minor
30287 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30288 full details of these issues,
30289 and should be consulted for a complete treatment.
30290 In practice the
30291 following subsections treat the most likely issues to be encountered.
30292
30293 @menu
30294 * Legal Ada 83 programs that are illegal in Ada 95::
30295 * More deterministic semantics::
30296 * Changed semantics::
30297 * Other language compatibility issues::
30298 @end menu
30299
30300 @node Legal Ada 83 programs that are illegal in Ada 95
30301 @subsection Legal Ada 83 programs that are illegal in Ada 95
30302
30303 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30304 Ada 95 and thus also in Ada 2005:
30305
30306 @table @emph
30307 @item Character literals
30308 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30309 @code{Wide_Character} as a new predefined character type, some uses of
30310 character literals that were legal in Ada 83 are illegal in Ada 95.
30311 For example:
30312 @smallexample @c ada
30313    for Char in 'A' .. 'Z' loop @dots{} end loop;
30314 @end smallexample
30315
30316 @noindent
30317 The problem is that @code{'A'} and @code{'Z'} could be from either
30318 @code{Character} or @code{Wide_Character}.  The simplest correction
30319 is to make the type explicit; e.g.:
30320 @smallexample @c ada
30321    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30322 @end smallexample
30323
30324 @item New reserved words
30325 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30326 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30327 Existing Ada 83 code using any of these identifiers must be edited to
30328 use some alternative name.
30329
30330 @item Freezing rules
30331 The rules in Ada 95 are slightly different with regard to the point at
30332 which entities are frozen, and representation pragmas and clauses are
30333 not permitted past the freeze point.  This shows up most typically in
30334 the form of an error message complaining that a representation item
30335 appears too late, and the appropriate corrective action is to move
30336 the item nearer to the declaration of the entity to which it refers.
30337
30338 A particular case is that representation pragmas
30339 @ifset vms
30340 (including the
30341 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30342 @end ifset
30343 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30344 declaration must be introduced to which the pragma can be applied.
30345
30346 @item Optional bodies for library packages
30347 In Ada 83, a package that did not require a package body was nevertheless
30348 allowed to have one.  This lead to certain surprises in compiling large
30349 systems (situations in which the body could be unexpectedly ignored by the
30350 binder).  In Ada 95, if a package does not require a body then it is not
30351 permitted to have a body.  To fix this problem, simply remove a redundant
30352 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30353 into the spec that makes the body required.  One approach is to add a private
30354 part to the package declaration (if necessary), and define a parameterless
30355 procedure called @code{Requires_Body}, which must then be given a dummy
30356 procedure body in the package body, which then becomes required.
30357 Another approach (assuming that this does not introduce elaboration
30358 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30359 since one effect of this pragma is to require the presence of a package body.
30360
30361 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30362 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30363 @code{Constraint_Error}.
30364 This means that it is illegal to have separate exception handlers for
30365 the two exceptions.  The fix is simply to remove the handler for the
30366 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30367 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30368
30369 @item Indefinite subtypes in generics
30370 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30371 as the actual for a generic formal private type, but then the instantiation
30372 would be illegal if there were any instances of declarations of variables
30373 of this type in the generic body.  In Ada 95, to avoid this clear violation
30374 of the methodological principle known as the ``contract model'',
30375 the generic declaration explicitly indicates whether
30376 or not such instantiations are permitted.  If a generic formal parameter
30377 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30378 type name, then it can be instantiated with indefinite types, but no
30379 stand-alone variables can be declared of this type.  Any attempt to declare
30380 such a variable will result in an illegality at the time the generic is
30381 declared.  If the @code{(<>)} notation is not used, then it is illegal
30382 to instantiate the generic with an indefinite type.
30383 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30384 It will show up as a compile time error, and
30385 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30386 @end table
30387
30388 @node More deterministic semantics
30389 @subsection More deterministic semantics
30390
30391 @table @emph
30392 @item Conversions
30393 Conversions from real types to integer types round away from 0.  In Ada 83
30394 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30395 implementation freedom was intended to support unbiased rounding in
30396 statistical applications, but in practice it interfered with portability.
30397 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30398 is required.  Numeric code may be affected by this change in semantics.
30399 Note, though, that this issue is no worse than already existed in Ada 83
30400 when porting code from one vendor to another.
30401
30402 @item Tasking
30403 The Real-Time Annex introduces a set of policies that define the behavior of
30404 features that were implementation dependent in Ada 83, such as the order in
30405 which open select branches are executed.
30406 @end table
30407
30408 @node Changed semantics
30409 @subsection Changed semantics
30410
30411 @noindent
30412 The worst kind of incompatibility is one where a program that is legal in
30413 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30414 possible in Ada 83.  Fortunately this is extremely rare, but the one
30415 situation that you should be alert to is the change in the predefined type
30416 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30417
30418 @table @emph
30419 @item Range of type @code{Character}
30420 The range of @code{Standard.Character} is now the full 256 characters
30421 of Latin-1, whereas in most Ada 83 implementations it was restricted
30422 to 128 characters. Although some of the effects of
30423 this change will be manifest in compile-time rejection of legal
30424 Ada 83 programs it is possible for a working Ada 83 program to have
30425 a different effect in Ada 95, one that was not permitted in Ada 83.
30426 As an example, the expression
30427 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30428 delivers @code{255} as its value.
30429 In general, you should look at the logic of any
30430 character-processing Ada 83 program and see whether it needs to be adapted
30431 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
30432 character handling package that may be relevant if code needs to be adapted
30433 to account for the additional Latin-1 elements.
30434 The desirable fix is to
30435 modify the program to accommodate the full character set, but in some cases
30436 it may be convenient to define a subtype or derived type of Character that
30437 covers only the restricted range.
30438 @cindex Latin-1
30439 @end table
30440
30441 @node Other language compatibility issues
30442 @subsection Other language compatibility issues
30443
30444 @table @emph
30445 @item @option{-gnat83} switch
30446 All implementations of GNAT provide a switch that causes GNAT to operate
30447 in Ada 83 mode.  In this mode, some but not all compatibility problems
30448 of the type described above are handled automatically.  For example, the
30449 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30450 as identifiers as in Ada 83.
30451 However,
30452 in practice, it is usually advisable to make the necessary modifications
30453 to the program to remove the need for using this switch.
30454 See @ref{Compiling Different Versions of Ada}.
30455
30456 @item Support for removed Ada 83 pragmas and attributes
30457 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30458 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
30459 compilers are allowed, but not required, to implement these missing
30460 elements.  In contrast with some other compilers, GNAT implements all
30461 such pragmas and attributes, eliminating this compatibility concern.  These
30462 include @code{pragma Interface} and the floating point type attributes
30463 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30464 @end table
30465
30466
30467 @node Compatibility between Ada 95 and Ada 2005
30468 @section Compatibility between Ada 95 and Ada 2005
30469 @cindex Compatibility between Ada 95 and Ada 2005
30470
30471 @noindent
30472 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30473 a number of incompatibilities. Several are enumerated below;
30474 for a complete description please see the
30475 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30476 @cite{Rationale for Ada 2005}.
30477
30478 @table @emph
30479 @item New reserved words.
30480 The words @code{interface}, @code{overriding} and @code{synchronized} are
30481 reserved in Ada 2005.
30482 A pre-Ada 2005 program that uses any of these as an identifier will be
30483 illegal.
30484
30485 @item New declarations in predefined packages.
30486 A number of packages in the predefined environment contain new declarations:
30487 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30488 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30489 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30490 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30491 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30492 If an Ada 95 program does a @code{with} and @code{use} of any of these
30493 packages, the new declarations may cause name clashes.
30494
30495 @item Access parameters.
30496 A nondispatching subprogram with an access parameter cannot be renamed
30497 as a dispatching operation.  This was permitted in Ada 95.
30498
30499 @item Access types, discriminants, and constraints.
30500 Rule changes in this area have led to some incompatibilities; for example,
30501 constrained subtypes of some access types are not permitted in Ada 2005.
30502
30503 @item Aggregates for limited types.
30504 The allowance of aggregates for limited types in Ada 2005 raises the
30505 possibility of ambiguities in legal Ada 95 programs, since additional types
30506 now need to be considered in expression resolution.
30507
30508 @item Fixed-point multiplication and division.
30509 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30510 were legal in Ada 95 and invoked the predefined versions of these operations,
30511 are now ambiguous.
30512 The ambiguity may be resolved either by applying a type conversion to the
30513 expression, or by explicitly invoking the operation from package
30514 @code{Standard}.
30515
30516 @item Return-by-reference types.
30517 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
30518 can declare a function returning a value from an anonymous access type.
30519 @end table
30520
30521
30522 @node Implementation-dependent characteristics
30523 @section Implementation-dependent characteristics
30524 @noindent
30525 Although the Ada language defines the semantics of each construct as
30526 precisely as practical, in some situations (for example for reasons of
30527 efficiency, or where the effect is heavily dependent on the host or target
30528 platform) the implementation is allowed some freedom.  In porting Ada 83
30529 code to GNAT, you need to be aware of whether / how the existing code
30530 exercised such implementation dependencies.  Such characteristics fall into
30531 several categories, and GNAT offers specific support in assisting the
30532 transition from certain Ada 83 compilers.
30533
30534 @menu
30535 * Implementation-defined pragmas::
30536 * Implementation-defined attributes::
30537 * Libraries::
30538 * Elaboration order::
30539 * Target-specific aspects::
30540 @end menu
30541
30542 @node Implementation-defined pragmas
30543 @subsection Implementation-defined pragmas
30544
30545 @noindent
30546 Ada compilers are allowed to supplement the language-defined pragmas, and
30547 these are a potential source of non-portability.  All GNAT-defined pragmas
30548 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30549 Reference Manual}, and these include several that are specifically
30550 intended to correspond to other vendors' Ada 83 pragmas.
30551 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30552 For compatibility with HP Ada 83, GNAT supplies the pragmas
30553 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30554 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30555 and @code{Volatile}.
30556 Other relevant pragmas include @code{External} and @code{Link_With}.
30557 Some vendor-specific
30558 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30559 recognized, thus
30560 avoiding compiler rejection of units that contain such pragmas; they are not
30561 relevant in a GNAT context and hence are not otherwise implemented.
30562
30563 @node Implementation-defined attributes
30564 @subsection Implementation-defined attributes
30565
30566 Analogous to pragmas, the set of attributes may be extended by an
30567 implementation.  All GNAT-defined attributes are described in
30568 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30569 Manual}, and these include several that are specifically intended
30570 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
30571 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
30572 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30573 @code{Type_Class}.
30574
30575 @node Libraries
30576 @subsection Libraries
30577 @noindent
30578 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
30579 code uses vendor-specific libraries then there are several ways to manage
30580 this in Ada 95 or Ada 2005:
30581 @enumerate
30582 @item
30583 If the source code for the libraries (specs and bodies) are
30584 available, then the libraries can be migrated in the same way as the
30585 application.
30586 @item
30587 If the source code for the specs but not the bodies are
30588 available, then you can reimplement the bodies.
30589 @item
30590 Some features introduced by Ada 95 obviate the need for library support.  For
30591 example most Ada 83 vendors supplied a package for unsigned integers.  The
30592 Ada 95 modular type feature is the preferred way to handle this need, so
30593 instead of migrating or reimplementing the unsigned integer package it may
30594 be preferable to retrofit the application using modular types.
30595 @end enumerate
30596
30597 @node Elaboration order
30598 @subsection Elaboration order
30599 @noindent
30600 The implementation can choose any elaboration order consistent with the unit
30601 dependency relationship.  This freedom means that some orders can result in
30602 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30603 to invoke a subprogram its body has been elaborated, or to instantiate a
30604 generic before the generic body has been elaborated.  By default GNAT
30605 attempts to choose a safe order (one that will not encounter access before
30606 elaboration problems) by implicitly inserting @code{Elaborate} or
30607 @code{Elaborate_All} pragmas where
30608 needed.  However, this can lead to the creation of elaboration circularities
30609 and a resulting rejection of the program by gnatbind.  This issue is
30610 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30611 In brief, there are several
30612 ways to deal with this situation:
30613
30614 @itemize @bullet
30615 @item
30616 Modify the program to eliminate the circularities, e.g.@: by moving
30617 elaboration-time code into explicitly-invoked procedures
30618 @item
30619 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30620 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30621 @code{Elaborate_All}
30622 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30623 (by selectively suppressing elaboration checks via pragma
30624 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30625 @end itemize
30626
30627 @node Target-specific aspects
30628 @subsection Target-specific aspects
30629 @noindent
30630 Low-level applications need to deal with machine addresses, data
30631 representations, interfacing with assembler code, and similar issues.  If
30632 such an Ada 83 application is being ported to different target hardware (for
30633 example where the byte endianness has changed) then you will need to
30634 carefully examine the program logic; the porting effort will heavily depend
30635 on the robustness of the original design.  Moreover, Ada 95 (and thus
30636 Ada 2005) are sometimes
30637 incompatible with typical Ada 83 compiler practices regarding implicit
30638 packing, the meaning of the Size attribute, and the size of access values.
30639 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30640
30641 @node Compatibility with Other Ada Systems
30642 @section Compatibility with Other Ada Systems
30643
30644 @noindent
30645 If programs avoid the use of implementation dependent and
30646 implementation defined features, as documented in the @cite{Ada
30647 Reference Manual}, there should be a high degree of portability between
30648 GNAT and other Ada systems.  The following are specific items which
30649 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30650 compilers, but do not affect porting code to GNAT@.
30651 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30652 the following issues may or may not arise for Ada 2005 programs
30653 when other compilers appear.)
30654
30655 @table @emph
30656 @item Ada 83 Pragmas and Attributes
30657 Ada 95 compilers are allowed, but not required, to implement the missing
30658 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30659 GNAT implements all such pragmas and attributes, eliminating this as
30660 a compatibility concern, but some other Ada 95 compilers reject these
30661 pragmas and attributes.
30662
30663 @item Specialized Needs Annexes
30664 GNAT implements the full set of special needs annexes.  At the
30665 current time, it is the only Ada 95 compiler to do so.  This means that
30666 programs making use of these features may not be portable to other Ada
30667 95 compilation systems.
30668
30669 @item Representation Clauses
30670 Some other Ada 95 compilers implement only the minimal set of
30671 representation clauses required by the Ada 95 reference manual.  GNAT goes
30672 far beyond this minimal set, as described in the next section.
30673 @end table
30674
30675 @node Representation Clauses
30676 @section Representation Clauses
30677
30678 @noindent
30679 The Ada 83 reference manual was quite vague in describing both the minimal
30680 required implementation of representation clauses, and also their precise
30681 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
30682 minimal set of capabilities required is still quite limited.
30683
30684 GNAT implements the full required set of capabilities in
30685 Ada 95 and Ada 2005, but also goes much further, and in particular
30686 an effort has been made to be compatible with existing Ada 83 usage to the
30687 greatest extent possible.
30688
30689 A few cases exist in which Ada 83 compiler behavior is incompatible with
30690 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
30691 intentional or accidental dependence on specific implementation dependent
30692 characteristics of these Ada 83 compilers.  The following is a list of
30693 the cases most likely to arise in existing Ada 83 code.
30694
30695 @table @emph
30696 @item Implicit Packing
30697 Some Ada 83 compilers allowed a Size specification to cause implicit
30698 packing of an array or record.  This could cause expensive implicit
30699 conversions for change of representation in the presence of derived
30700 types, and the Ada design intends to avoid this possibility.
30701 Subsequent AI's were issued to make it clear that such implicit
30702 change of representation in response to a Size clause is inadvisable,
30703 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30704 Reference Manuals as implementation advice that is followed by GNAT@.
30705 The problem will show up as an error
30706 message rejecting the size clause.  The fix is simply to provide
30707 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30708 a Component_Size clause.
30709
30710 @item Meaning of Size Attribute
30711 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30712 the minimal number of bits required to hold values of the type.  For example,
30713 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30714 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
30715 some 32 in this situation.  This problem will usually show up as a compile
30716 time error, but not always.  It is a good idea to check all uses of the
30717 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
30718 Object_Size can provide a useful way of duplicating the behavior of
30719 some Ada 83 compiler systems.
30720
30721 @item Size of Access Types
30722 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30723 and that therefore it will be the same size as a System.Address value.  This
30724 assumption is true for GNAT in most cases with one exception.  For the case of
30725 a pointer to an unconstrained array type (where the bounds may vary from one
30726 value of the access type to another), the default is to use a ``fat pointer'',
30727 which is represented as two separate pointers, one to the bounds, and one to
30728 the array.  This representation has a number of advantages, including improved
30729 efficiency.  However, it may cause some difficulties in porting existing Ada 83
30730 code which makes the assumption that, for example, pointers fit in 32 bits on
30731 a machine with 32-bit addressing.
30732
30733 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30734 access types in this case (where the designated type is an unconstrained array
30735 type).  These thin pointers are indeed the same size as a System.Address value.
30736 To specify a thin pointer, use a size clause for the type, for example:
30737
30738 @smallexample @c ada
30739 type X is access all String;
30740 for X'Size use Standard'Address_Size;
30741 @end smallexample
30742
30743 @noindent
30744 which will cause the type X to be represented using a single pointer.
30745 When using this representation, the bounds are right behind the array.
30746 This representation is slightly less efficient, and does not allow quite
30747 such flexibility in the use of foreign pointers or in using the
30748 Unrestricted_Access attribute to create pointers to non-aliased objects.
30749 But for any standard portable use of the access type it will work in
30750 a functionally correct manner and allow porting of existing code.
30751 Note that another way of forcing a thin pointer representation
30752 is to use a component size clause for the element size in an array,
30753 or a record representation clause for an access field in a record.
30754 @end table
30755
30756 @ifclear vms
30757 @c This brief section is only in the non-VMS version
30758 @c The complete chapter on HP Ada is in the VMS version
30759 @node Compatibility with HP Ada 83
30760 @section Compatibility with HP Ada 83
30761
30762 @noindent
30763 The VMS version of GNAT fully implements all the pragmas and attributes
30764 provided by HP Ada 83, as well as providing the standard HP Ada 83
30765 libraries, including Starlet.  In addition, data layouts and parameter
30766 passing conventions are highly compatible.  This means that porting
30767 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30768 most other porting efforts.  The following are some of the most
30769 significant differences between GNAT and HP Ada 83.
30770
30771 @table @emph
30772 @item Default floating-point representation
30773 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30774 it is VMS format.  GNAT does implement the necessary pragmas
30775 (Long_Float, Float_Representation) for changing this default.
30776
30777 @item System
30778 The package System in GNAT exactly corresponds to the definition in the
30779 Ada 95 reference manual, which means that it excludes many of the
30780 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
30781 that contains the additional definitions, and a special pragma,
30782 Extend_System allows this package to be treated transparently as an
30783 extension of package System.
30784
30785 @item To_Address
30786 The definitions provided by Aux_DEC are exactly compatible with those
30787 in the HP Ada 83 version of System, with one exception.
30788 HP Ada provides the following declarations:
30789
30790 @smallexample @c ada
30791 TO_ADDRESS (INTEGER)
30792 TO_ADDRESS (UNSIGNED_LONGWORD)
30793 TO_ADDRESS (@i{universal_integer})
30794 @end smallexample
30795
30796 @noindent
30797 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30798 an extension to Ada 83 not strictly compatible with the reference manual.
30799 In GNAT, we are constrained to be exactly compatible with the standard,
30800 and this means we cannot provide this capability.  In HP Ada 83, the
30801 point of this definition is to deal with a call like:
30802
30803 @smallexample @c ada
30804 TO_ADDRESS (16#12777#);
30805 @end smallexample
30806
30807 @noindent
30808 Normally, according to the Ada 83 standard, one would expect this to be
30809 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30810 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
30811 definition using @i{universal_integer} takes precedence.
30812
30813 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30814 is not possible to be 100% compatible.  Since there are many programs using
30815 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30816 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30817 declarations provided in the GNAT version of AUX_Dec are:
30818
30819 @smallexample @c ada
30820 function To_Address (X : Integer) return Address;
30821 pragma Pure_Function (To_Address);
30822
30823 function To_Address_Long (X : Unsigned_Longword)
30824  return Address;
30825 pragma Pure_Function (To_Address_Long);
30826 @end smallexample
30827
30828 @noindent
30829 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30830 change the name to TO_ADDRESS_LONG@.
30831
30832 @item Task_Id values
30833 The Task_Id values assigned will be different in the two systems, and GNAT
30834 does not provide a specified value for the Task_Id of the environment task,
30835 which in GNAT is treated like any other declared task.
30836 @end table
30837
30838 @noindent
30839 For full details on these and other less significant compatibility issues,
30840 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30841 Overview and Comparison on HP Platforms}.
30842
30843 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30844 attributes are recognized, although only a subset of them can sensibly
30845 be implemented.  The description of pragmas in @ref{Implementation
30846 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30847 indicates whether or not they are applicable to non-VMS systems.
30848 @end ifclear
30849
30850 @ifset vms
30851 @node Transitioning to 64-Bit GNAT for OpenVMS
30852 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30853
30854 @noindent
30855 This section is meant to assist users of pre-2006 @value{EDITION}
30856 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30857 the version of the GNAT technology supplied in 2006 and later for
30858 OpenVMS on both Alpha and I64.
30859
30860 @menu
30861 * Introduction to transitioning::
30862 * Migration of 32 bit code::
30863 * Taking advantage of 64 bit addressing::
30864 * Technical details::
30865 @end menu
30866
30867 @node Introduction to transitioning
30868 @subsection Introduction
30869
30870 @noindent
30871 64-bit @value{EDITION} for Open VMS has been designed to meet
30872 three main goals:
30873
30874 @enumerate
30875 @item
30876 Providing a full conforming implementation of Ada 95 and Ada 2005
30877
30878 @item
30879 Allowing maximum backward compatibility, thus easing migration of existing
30880 Ada source code
30881
30882 @item
30883 Supplying a path for exploiting the full 64-bit address range
30884 @end enumerate
30885
30886 @noindent
30887 Ada's strong typing semantics has made it
30888 impractical to have different 32-bit and 64-bit modes. As soon as
30889 one object could possibly be outside the 32-bit address space, this
30890 would make it necessary for the @code{System.Address} type to be 64 bits.
30891 In particular, this would cause inconsistencies if 32-bit code is
30892 called from 64-bit code that raises an exception.
30893
30894 This issue has been resolved by always using 64-bit addressing
30895 at the system level, but allowing for automatic conversions between
30896 32-bit and 64-bit addresses where required. Thus users who
30897 do not currently require 64-bit addressing capabilities, can
30898 recompile their code with only minimal changes (and indeed
30899 if the code is written in portable Ada, with no assumptions about
30900 the size of the @code{Address} type, then no changes at all are necessary).
30901 At the same time,
30902 this approach provides a simple, gradual upgrade path to future
30903 use of larger memories than available for 32-bit systems.
30904 Also, newly written applications or libraries will by default
30905 be fully compatible with future systems exploiting 64-bit
30906 addressing capabilities.
30907
30908 @ref{Migration of 32 bit code}, will focus on porting applications
30909 that do not require more than 2 GB of
30910 addressable memory. This code will be referred to as
30911 @emph{32-bit code}.
30912 For applications intending to exploit the full 64-bit address space,
30913 @ref{Taking advantage of 64 bit addressing},
30914 will consider further changes that may be required.
30915 Such code will be referred to below as @emph{64-bit code}.
30916
30917 @node Migration of 32 bit code
30918 @subsection Migration of 32-bit code
30919
30920 @menu
30921 * Address types::
30922 * Access types::
30923 * Unchecked conversions::
30924 * Predefined constants::
30925 * Interfacing with C::
30926 * Experience with source compatibility::
30927 @end menu
30928
30929 @node Address types
30930 @subsubsection Address types
30931
30932 @noindent
30933 To solve the problem of mixing 64-bit and 32-bit addressing,
30934 while maintaining maximum backward compatibility, the following
30935 approach has been taken:
30936
30937 @itemize @bullet
30938 @item
30939 @code{System.Address} always has a size of 64 bits
30940
30941 @item
30942 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30943 @end itemize
30944
30945 @noindent
30946 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30947 a @code{Short_Address}
30948 may be used where an @code{Address} is required, and vice versa, without
30949 needing explicit type conversions.
30950 By virtue of the Open VMS parameter passing conventions,
30951 even imported
30952 and exported subprograms that have 32-bit address parameters are
30953 compatible with those that have 64-bit address parameters.
30954 (See @ref{Making code 64 bit clean} for details.)
30955
30956 The areas that may need attention are those where record types have
30957 been defined that contain components of the type @code{System.Address}, and
30958 where objects of this type are passed to code expecting a record layout with
30959 32-bit addresses.
30960
30961 Different compilers on different platforms cannot be
30962 expected to represent the same type in the same way,
30963 since alignment constraints
30964 and other system-dependent properties affect the compiler's decision.
30965 For that reason, Ada code
30966 generally uses representation clauses to specify the expected
30967 layout where required.
30968
30969 If such a representation clause uses 32 bits for a component having
30970 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30971 will detect that error and produce a specific diagnostic message.
30972 The developer should then determine whether the representation
30973 should be 64 bits or not and make either of two changes:
30974 change the size to 64 bits and leave the type as @code{System.Address}, or
30975 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30976 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30977 required in any code setting or accessing the field; the compiler will
30978 automatically perform any needed conversions between address
30979 formats.
30980
30981 @node Access types
30982 @subsubsection Access types
30983
30984 @noindent
30985 By default, objects designated by access values are always
30986 allocated in the 32-bit
30987 address space. Thus legacy code will never contain
30988 any objects that are not addressable with 32-bit addresses, and
30989 the compiler will never raise exceptions as result of mixing
30990 32-bit and 64-bit addresses.
30991
30992 However, the access values themselves are represented in 64 bits, for optimum
30993 performance and future compatibility with 64-bit code. As was
30994 the case with @code{System.Address}, the compiler will give an error message
30995 if an object or record component has a representation clause that
30996 requires the access value to fit in 32 bits. In such a situation,
30997 an explicit size clause for the access type, specifying 32 bits,
30998 will have the desired effect.
30999
31000 General access types (declared with @code{access all}) can never be
31001 32 bits, as values of such types must be able to refer to any object
31002 of the  designated type,
31003 including objects residing outside the 32-bit address range.
31004 Existing Ada 83 code will not contain such type definitions,
31005 however, since general access types were introduced in Ada 95.
31006
31007 @node Unchecked conversions
31008 @subsubsection Unchecked conversions
31009
31010 @noindent
31011 In the case of an @code{Unchecked_Conversion} where the source type is a
31012 64-bit access type or the type @code{System.Address}, and the target
31013 type is a 32-bit type, the compiler will generate a warning.
31014 Even though the generated code will still perform the required
31015 conversions, it is highly recommended in these cases to use
31016 respectively a 32-bit access type or @code{System.Short_Address}
31017 as the source type.
31018
31019 @node Predefined constants
31020 @subsubsection Predefined constants
31021
31022 @noindent
31023 The following table shows the correspondence between pre-2006 versions of
31024 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31025 (``New''):
31026
31027 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31028 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31029 @item   @code{System.Word_Size}          @tab 32      @tab 64
31030 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31031 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31032 @item   @code{System.Address_Size}       @tab 32      @tab 64
31033 @end multitable
31034
31035 @noindent
31036 If you need to refer to the specific
31037 memory size of a 32-bit implementation, instead of the
31038 actual memory size, use @code{System.Short_Memory_Size}
31039 rather than @code{System.Memory_Size}.
31040 Similarly, references to @code{System.Address_Size} may need
31041 to be replaced by @code{System.Short_Address'Size}.
31042 The program @command{gnatfind} may be useful for locating
31043 references to the above constants, so that you can verify that they
31044 are still correct.
31045
31046 @node Interfacing with C
31047 @subsubsection Interfacing with C
31048
31049 @noindent
31050 In order to minimize the impact of the transition to 64-bit addresses on
31051 legacy programs, some fundamental types in the @code{Interfaces.C}
31052 package hierarchy continue to be represented in 32 bits.
31053 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31054 This eases integration with the default HP C layout choices, for example
31055 as found in the system routines in @code{DECC$SHR.EXE}.
31056 Because of this implementation choice, the type fully compatible with
31057 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31058 Depending on the context the compiler will issue a
31059 warning or an error when type @code{Address} is used, alerting the user to a
31060 potential problem. Otherwise 32-bit programs that use
31061 @code{Interfaces.C} should normally not require code modifications
31062
31063 The other issue arising with C interfacing concerns pragma @code{Convention}.
31064 For VMS 64-bit systems, there is an issue of the appropriate default size
31065 of C convention pointers in the absence of an explicit size clause. The HP
31066 C compiler can choose either 32 or 64 bits depending on compiler options.
31067 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31068 clause is given. This proves a better choice for porting 32-bit legacy
31069 applications. In order to have a 64-bit representation, it is necessary to
31070 specify a size representation clause. For example:
31071
31072 @smallexample @c ada
31073 type int_star is access Interfaces.C.int;
31074 pragma Convention(C, int_star);
31075 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31076 @end smallexample
31077
31078 @node Experience with source compatibility
31079 @subsubsection Experience with source compatibility
31080
31081 @noindent
31082 The Security Server and STARLET on I64 provide an interesting ``test case''
31083 for source compatibility issues, since it is in such system code
31084 where assumptions about @code{Address} size might be expected to occur.
31085 Indeed, there were a small number of occasions in the Security Server
31086 file @file{jibdef.ads}
31087 where a representation clause for a record type specified
31088 32 bits for a component of type @code{Address}.
31089 All of these errors were detected by the compiler.
31090 The repair was obvious and immediate; to simply replace @code{Address} by
31091 @code{Short_Address}.
31092
31093 In the case of STARLET, there were several record types that should
31094 have had representation clauses but did not.  In these record types
31095 there was an implicit assumption that an @code{Address} value occupied
31096 32 bits.
31097 These compiled without error, but their usage resulted in run-time error
31098 returns from STARLET system calls.
31099 Future GNAT technology enhancements may include a tool that detects and flags
31100 these sorts of potential source code porting problems.
31101
31102 @c ****************************************
31103 @node Taking advantage of 64 bit addressing
31104 @subsection Taking advantage of 64-bit addressing
31105
31106 @menu
31107 * Making code 64 bit clean::
31108 * Allocating memory from the 64 bit storage pool::
31109 * Restrictions on use of 64 bit objects::
31110 * Using 64 bit storage pools by default::
31111 * General access types::
31112 * STARLET and other predefined libraries::
31113 @end menu
31114
31115 @node Making code 64 bit clean
31116 @subsubsection Making code 64-bit clean
31117
31118 @noindent
31119 In order to prevent problems that may occur when (parts of) a
31120 system start using memory outside the 32-bit address range,
31121 we recommend some additional guidelines:
31122
31123 @itemize @bullet
31124 @item
31125 For imported subprograms that take parameters of the
31126 type @code{System.Address}, ensure that these subprograms can
31127 indeed handle 64-bit addresses. If not, or when in doubt,
31128 change the subprogram declaration to specify
31129 @code{System.Short_Address} instead.
31130
31131 @item
31132 Resolve all warnings related to size mismatches in
31133 unchecked conversions. Failing to do so causes
31134 erroneous execution if the source object is outside
31135 the 32-bit address space.
31136
31137 @item
31138 (optional) Explicitly use the 32-bit storage pool
31139 for access types used in a 32-bit context, or use
31140 generic access types where possible
31141 (@pxref{Restrictions on use of 64 bit objects}).
31142 @end itemize
31143
31144 @noindent
31145 If these rules are followed, the compiler will automatically insert
31146 any necessary checks to ensure that no addresses or access values
31147 passed to 32-bit code ever refer to objects outside the 32-bit
31148 address range.
31149 Any attempt to do this will raise @code{Constraint_Error}.
31150
31151 @node Allocating memory from the 64 bit storage pool
31152 @subsubsection Allocating memory from the 64-bit storage pool
31153
31154 @noindent
31155 For any access type @code{T} that potentially requires memory allocations
31156 beyond the 32-bit address space,
31157 use the following representation clause:
31158
31159 @smallexample @c ada
31160    for T'Storage_Pool use System.Pool_64;
31161 @end smallexample
31162
31163 @node Restrictions on use of 64 bit objects
31164 @subsubsection Restrictions on use of 64-bit objects
31165
31166 @noindent
31167 Taking the address of an object allocated from a 64-bit storage pool,
31168 and then passing this address to a subprogram expecting
31169 @code{System.Short_Address},
31170 or assigning it to a variable of type @code{Short_Address}, will cause
31171 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31172 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31173 no exception is raised and execution
31174 will become erroneous.
31175
31176 @node Using 64 bit storage pools by default
31177 @subsubsection Using 64-bit storage pools by default
31178
31179 @noindent
31180 In some cases it may be desirable to have the compiler allocate
31181 from 64-bit storage pools by default. This may be the case for
31182 libraries that are 64-bit clean, but may be used in both 32-bit
31183 and 64-bit contexts. For these cases the following configuration
31184 pragma may be specified:
31185
31186 @smallexample @c ada
31187   pragma Pool_64_Default;
31188 @end smallexample
31189
31190 @noindent
31191 Any code compiled in the context of this pragma will by default
31192 use the @code{System.Pool_64} storage pool. This default may be overridden
31193 for a specific access type @code{T} by the representation clause:
31194
31195 @smallexample @c ada
31196    for T'Storage_Pool use System.Pool_32;
31197 @end smallexample
31198
31199 @noindent
31200 Any object whose address may be passed to a subprogram with a
31201 @code{Short_Address} argument, or assigned to a variable of type
31202 @code{Short_Address}, needs to be allocated from this pool.
31203
31204 @node General access types
31205 @subsubsection General access types
31206
31207 @noindent
31208 Objects designated by access values from a
31209 general access type (declared with @code{access all}) are never allocated
31210 from a 64-bit storage pool. Code that uses general access types will
31211 accept objects allocated in either 32-bit or 64-bit address spaces,
31212 but never allocate objects outside the 32-bit address space.
31213 Using general access types ensures maximum compatibility with both
31214 32-bit and 64-bit code.
31215
31216 @node STARLET and other predefined libraries
31217 @subsubsection STARLET and other predefined libraries
31218
31219 @noindent
31220 All code that comes as part of GNAT is 64-bit clean, but the
31221 restrictions given in @ref{Restrictions on use of 64 bit objects},
31222 still apply. Look at the package
31223 specs to see in which contexts objects allocated
31224 in 64-bit address space are acceptable.
31225
31226 @node Technical details
31227 @subsection Technical details
31228
31229 @noindent
31230 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31231 Ada standard with respect to the type of @code{System.Address}. Previous
31232 versions of GNAT Pro have defined this type as private and implemented it as a
31233 modular type.
31234
31235 In order to allow defining @code{System.Short_Address} as a proper subtype,
31236 and to match the implicit sign extension in parameter passing,
31237 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31238 visible (i.e., non-private) integer type.
31239 Standard operations on the type, such as the binary operators ``+'', ``-'',
31240 etc., that take @code{Address} operands and return an @code{Address} result,
31241 have been hidden by declaring these
31242 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31243 ambiguities that would otherwise result from overloading.
31244 (Note that, although @code{Address} is a visible integer type,
31245 good programming practice dictates against exploiting the type's
31246 integer properties such as literals, since this will compromise
31247 code portability.)
31248
31249 Defining @code{Address} as a visible integer type helps achieve
31250 maximum compatibility for existing Ada code,
31251 without sacrificing the capabilities of the 64-bit architecture.
31252 @end ifset
31253
31254 @c ************************************************
31255 @ifset unw
31256 @node Microsoft Windows Topics
31257 @appendix Microsoft Windows Topics
31258 @cindex Windows NT
31259 @cindex Windows 95
31260 @cindex Windows 98
31261
31262 @noindent
31263 This chapter describes topics that are specific to the Microsoft Windows
31264 platforms (NT, 2000, and XP Professional).
31265
31266 @menu
31267 * Using GNAT on Windows::
31268 * Using a network installation of GNAT::
31269 * CONSOLE and WINDOWS subsystems::
31270 * Temporary Files::
31271 * Mixed-Language Programming on Windows::
31272 * Windows Calling Conventions::
31273 * Introduction to Dynamic Link Libraries (DLLs)::
31274 * Using DLLs with GNAT::
31275 * Building DLLs with GNAT::
31276 * Building DLLs with GNAT Project files::
31277 * Building DLLs with gnatdll::
31278 * GNAT and Windows Resources::
31279 * Debugging a DLL::
31280 * Setting Stack Size from gnatlink::
31281 * Setting Heap Size from gnatlink::
31282 @end menu
31283
31284 @node Using GNAT on Windows
31285 @section Using GNAT on Windows
31286
31287 @noindent
31288 One of the strengths of the GNAT technology is that its tool set
31289 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31290 @code{gdb} debugger, etc.) is used in the same way regardless of the
31291 platform.
31292
31293 On Windows this tool set is complemented by a number of Microsoft-specific
31294 tools that have been provided to facilitate interoperability with Windows
31295 when this is required. With these tools:
31296
31297 @itemize @bullet
31298
31299 @item
31300 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31301 subsystems.
31302
31303 @item
31304 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31305 relocatable and non-relocatable DLLs are supported).
31306
31307 @item
31308 You can build Ada DLLs for use in other applications. These applications
31309 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31310 relocatable and non-relocatable Ada DLLs are supported.
31311
31312 @item
31313 You can include Windows resources in your Ada application.
31314
31315 @item
31316 You can use or create COM/DCOM objects.
31317 @end itemize
31318
31319 @noindent
31320 Immediately below are listed all known general GNAT-for-Windows restrictions.
31321 Other restrictions about specific features like Windows Resources and DLLs
31322 are listed in separate sections below.
31323
31324 @itemize @bullet
31325
31326 @item
31327 It is not possible to use @code{GetLastError} and @code{SetLastError}
31328 when tasking, protected records, or exceptions are used. In these
31329 cases, in order to implement Ada semantics, the GNAT run-time system
31330 calls certain Win32 routines that set the last error variable to 0 upon
31331 success. It should be possible to use @code{GetLastError} and
31332 @code{SetLastError} when tasking, protected record, and exception
31333 features are not used, but it is not guaranteed to work.
31334
31335 @item
31336 It is not possible to link against Microsoft libraries except for
31337 import libraries. The library must be built to be compatible with
31338 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31339 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31340 not be compatible with the GNAT runtime. Even if the library is
31341 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31342
31343 @item
31344 When the compilation environment is located on FAT32 drives, users may
31345 experience recompilations of the source files that have not changed if
31346 Daylight Saving Time (DST) state has changed since the last time files
31347 were compiled. NTFS drives do not have this problem.
31348
31349 @item
31350 No components of the GNAT toolset use any entries in the Windows
31351 registry. The only entries that can be created are file associations and
31352 PATH settings, provided the user has chosen to create them at installation
31353 time, as well as some minimal book-keeping information needed to correctly
31354 uninstall or integrate different GNAT products.
31355 @end itemize
31356
31357 @node Using a network installation of GNAT
31358 @section Using a network installation of GNAT
31359
31360 @noindent
31361 Make sure the system on which GNAT is installed is accessible from the
31362 current machine, i.e., the install location is shared over the network.
31363 Shared resources are accessed on Windows by means of UNC paths, which
31364 have the format @code{\\server\sharename\path}
31365
31366 In order to use such a network installation, simply add the UNC path of the
31367 @file{bin} directory of your GNAT installation in front of your PATH. For
31368 example, if GNAT is installed in @file{\GNAT} directory of a share location
31369 called @file{c-drive} on a machine @file{LOKI}, the following command will
31370 make it available:
31371
31372 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31373
31374 Be aware that every compilation using the network installation results in the
31375 transfer of large amounts of data across the network and will likely cause
31376 serious performance penalty.
31377
31378 @node CONSOLE and WINDOWS subsystems
31379 @section CONSOLE and WINDOWS subsystems
31380 @cindex CONSOLE Subsystem
31381 @cindex WINDOWS Subsystem
31382 @cindex -mwindows
31383
31384 @noindent
31385 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31386 (which is the default subsystem) will always create a console when
31387 launching the application. This is not something desirable when the
31388 application has a Windows GUI. To get rid of this console the
31389 application must be using the @code{WINDOWS} subsystem. To do so
31390 the @option{-mwindows} linker option must be specified.
31391
31392 @smallexample
31393 $ gnatmake winprog -largs -mwindows
31394 @end smallexample
31395
31396 @node Temporary Files
31397 @section Temporary Files
31398 @cindex Temporary files
31399
31400 @noindent
31401 It is possible to control where temporary files gets created by setting
31402 the @env{TMP} environment variable. The file will be created:
31403
31404 @itemize
31405 @item Under the directory pointed to by the @env{TMP} environment variable if
31406 this directory exists.
31407
31408 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31409 set (or not pointing to a directory) and if this directory exists.
31410
31411 @item Under the current working directory otherwise.
31412 @end itemize
31413
31414 @noindent
31415 This allows you to determine exactly where the temporary
31416 file will be created. This is particularly useful in networked
31417 environments where you may not have write access to some
31418 directories.
31419
31420 @node Mixed-Language Programming on Windows
31421 @section Mixed-Language Programming on Windows
31422
31423 @noindent
31424 Developing pure Ada applications on Windows is no different than on
31425 other GNAT-supported platforms. However, when developing or porting an
31426 application that contains a mix of Ada and C/C++, the choice of your
31427 Windows C/C++ development environment conditions your overall
31428 interoperability strategy.
31429
31430 If you use @command{gcc} to compile the non-Ada part of your application,
31431 there are no Windows-specific restrictions that affect the overall
31432 interoperability with your Ada code. If you plan to use
31433 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31434 the following limitations:
31435
31436 @itemize @bullet
31437 @item
31438 You cannot link your Ada code with an object or library generated with
31439 Microsoft tools if these use the @code{.tls} section (Thread Local
31440 Storage section) since the GNAT linker does not yet support this section.
31441
31442 @item
31443 You cannot link your Ada code with an object or library generated with
31444 Microsoft tools if these use I/O routines other than those provided in
31445 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31446 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31447 libraries can cause a conflict with @code{msvcrt.dll} services. For
31448 instance Visual C++ I/O stream routines conflict with those in
31449 @code{msvcrt.dll}.
31450 @end itemize
31451
31452 @noindent
31453 If you do want to use the Microsoft tools for your non-Ada code and hit one
31454 of the above limitations, you have two choices:
31455
31456 @enumerate
31457 @item
31458 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31459 application. In this case, use the Microsoft or whatever environment to
31460 build the DLL and use GNAT to build your executable
31461 (@pxref{Using DLLs with GNAT}).
31462
31463 @item
31464 Or you can encapsulate your Ada code in a DLL to be linked with the
31465 other part of your application. In this case, use GNAT to build the DLL
31466 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31467 environment to build your executable.
31468 @end enumerate
31469
31470 @node Windows Calling Conventions
31471 @section Windows Calling Conventions
31472 @findex Stdcall
31473 @findex APIENTRY
31474
31475 @menu
31476 * C Calling Convention::
31477 * Stdcall Calling Convention::
31478 * Win32 Calling Convention::
31479 * DLL Calling Convention::
31480 @end menu
31481
31482 @noindent
31483 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31484 (callee), there are several ways to push @code{G}'s parameters on the
31485 stack and there are several possible scenarios to clean up the stack
31486 upon @code{G}'s return. A calling convention is an agreed upon software
31487 protocol whereby the responsibilities between the caller (@code{F}) and
31488 the callee (@code{G}) are clearly defined. Several calling conventions
31489 are available for Windows:
31490
31491 @itemize @bullet
31492 @item
31493 @code{C} (Microsoft defined)
31494
31495 @item
31496 @code{Stdcall} (Microsoft defined)
31497
31498 @item
31499 @code{Win32} (GNAT specific)
31500
31501 @item
31502 @code{DLL} (GNAT specific)
31503 @end itemize
31504
31505 @node C Calling Convention
31506 @subsection @code{C} Calling Convention
31507
31508 @noindent
31509 This is the default calling convention used when interfacing to C/C++
31510 routines compiled with either @command{gcc} or Microsoft Visual C++.
31511
31512 In the @code{C} calling convention subprogram parameters are pushed on the
31513 stack by the caller from right to left. The caller itself is in charge of
31514 cleaning up the stack after the call. In addition, the name of a routine
31515 with @code{C} calling convention is mangled by adding a leading underscore.
31516
31517 The name to use on the Ada side when importing (or exporting) a routine
31518 with @code{C} calling convention is the name of the routine. For
31519 instance the C function:
31520
31521 @smallexample
31522 int get_val (long);
31523 @end smallexample
31524
31525 @noindent
31526 should be imported from Ada as follows:
31527
31528 @smallexample @c ada
31529 @group
31530 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31531 pragma Import (C, Get_Val, External_Name => "get_val");
31532 @end group
31533 @end smallexample
31534
31535 @noindent
31536 Note that in this particular case the @code{External_Name} parameter could
31537 have been omitted since, when missing, this parameter is taken to be the
31538 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31539 is missing, as in the above example, this parameter is set to be the
31540 @code{External_Name} with a leading underscore.
31541
31542 When importing a variable defined in C, you should always use the @code{C}
31543 calling convention unless the object containing the variable is part of a
31544 DLL (in which case you should use the @code{Stdcall} calling
31545 convention, @pxref{Stdcall Calling Convention}).
31546
31547 @node Stdcall Calling Convention
31548 @subsection @code{Stdcall} Calling Convention
31549
31550 @noindent
31551 This convention, which was the calling convention used for Pascal
31552 programs, is used by Microsoft for all the routines in the Win32 API for
31553 efficiency reasons. It must be used to import any routine for which this
31554 convention was specified.
31555
31556 In the @code{Stdcall} calling convention subprogram parameters are pushed
31557 on the stack by the caller from right to left. The callee (and not the
31558 caller) is in charge of cleaning the stack on routine exit. In addition,
31559 the name of a routine with @code{Stdcall} calling convention is mangled by
31560 adding a leading underscore (as for the @code{C} calling convention) and a
31561 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31562 bytes) of the parameters passed to the routine.
31563
31564 The name to use on the Ada side when importing a C routine with a
31565 @code{Stdcall} calling convention is the name of the C routine. The leading
31566 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31567 the compiler. For instance the Win32 function:
31568
31569 @smallexample
31570 @b{APIENTRY} int get_val (long);
31571 @end smallexample
31572
31573 @noindent
31574 should be imported from Ada as follows:
31575
31576 @smallexample @c ada
31577 @group
31578 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31579 pragma Import (Stdcall, Get_Val);
31580 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31581 @end group
31582 @end smallexample
31583
31584 @noindent
31585 As for the @code{C} calling convention, when the @code{External_Name}
31586 parameter is missing, it is taken to be the name of the Ada entity in lower
31587 case. If instead of writing the above import pragma you write:
31588
31589 @smallexample @c ada
31590 @group
31591 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31592 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31593 @end group
31594 @end smallexample
31595
31596 @noindent
31597 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31598 of specifying the @code{External_Name} parameter you specify the
31599 @code{Link_Name} as in the following example:
31600
31601 @smallexample @c ada
31602 @group
31603 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31604 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31605 @end group
31606 @end smallexample
31607
31608 @noindent
31609 then the imported routine is @code{retrieve_val}, that is, there is no
31610 decoration at all. No leading underscore and no Stdcall suffix
31611 @code{@@}@code{@var{nn}}.
31612
31613 @noindent
31614 This is especially important as in some special cases a DLL's entry
31615 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31616 name generated for a call has it.
31617
31618 @noindent
31619 It is also possible to import variables defined in a DLL by using an
31620 import pragma for a variable. As an example, if a DLL contains a
31621 variable defined as:
31622
31623 @smallexample
31624 int my_var;
31625 @end smallexample
31626
31627 @noindent
31628 then, to access this variable from Ada you should write:
31629
31630 @smallexample @c ada
31631 @group
31632 My_Var : Interfaces.C.int;
31633 pragma Import (Stdcall, My_Var);
31634 @end group
31635 @end smallexample
31636
31637 @noindent
31638 Note that to ease building cross-platform bindings this convention
31639 will be handled as a @code{C} calling convention on non-Windows platforms.
31640
31641 @node Win32 Calling Convention
31642 @subsection @code{Win32} Calling Convention
31643
31644 @noindent
31645 This convention, which is GNAT-specific is fully equivalent to the
31646 @code{Stdcall} calling convention described above.
31647
31648 @node DLL Calling Convention
31649 @subsection @code{DLL} Calling Convention
31650
31651 @noindent
31652 This convention, which is GNAT-specific is fully equivalent to the
31653 @code{Stdcall} calling convention described above.
31654
31655 @node Introduction to Dynamic Link Libraries (DLLs)
31656 @section Introduction to Dynamic Link Libraries (DLLs)
31657 @findex DLL
31658
31659 @noindent
31660 A Dynamically Linked Library (DLL) is a library that can be shared by
31661 several applications running under Windows. A DLL can contain any number of
31662 routines and variables.
31663
31664 One advantage of DLLs is that you can change and enhance them without
31665 forcing all the applications that depend on them to be relinked or
31666 recompiled. However, you should be aware than all calls to DLL routines are
31667 slower since, as you will understand below, such calls are indirect.
31668
31669 To illustrate the remainder of this section, suppose that an application
31670 wants to use the services of a DLL @file{API.dll}. To use the services
31671 provided by @file{API.dll} you must statically link against the DLL or
31672 an import library which contains a jump table with an entry for each
31673 routine and variable exported by the DLL. In the Microsoft world this
31674 import library is called @file{API.lib}. When using GNAT this import
31675 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31676 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31677
31678 After you have linked your application with the DLL or the import library
31679 and you run your application, here is what happens:
31680
31681 @enumerate
31682 @item
31683 Your application is loaded into memory.
31684
31685 @item
31686 The DLL @file{API.dll} is mapped into the address space of your
31687 application. This means that:
31688
31689 @itemize @bullet
31690 @item
31691 The DLL will use the stack of the calling thread.
31692
31693 @item
31694 The DLL will use the virtual address space of the calling process.
31695
31696 @item
31697 The DLL will allocate memory from the virtual address space of the calling
31698 process.
31699
31700 @item
31701 Handles (pointers) can be safely exchanged between routines in the DLL
31702 routines and routines in the application using the DLL.
31703 @end itemize
31704
31705 @item
31706 The entries in the jump table (from the import library @file{libAPI.dll.a}
31707 or @file{API.lib} or automatically created when linking against a DLL)
31708 which is part of your application are initialized with the addresses
31709 of the routines and variables in @file{API.dll}.
31710
31711 @item
31712 If present in @file{API.dll}, routines @code{DllMain} or
31713 @code{DllMainCRTStartup} are invoked. These routines typically contain
31714 the initialization code needed for the well-being of the routines and
31715 variables exported by the DLL.
31716 @end enumerate
31717
31718 @noindent
31719 There is an additional point which is worth mentioning. In the Windows
31720 world there are two kind of DLLs: relocatable and non-relocatable
31721 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31722 in the target application address space. If the addresses of two
31723 non-relocatable DLLs overlap and these happen to be used by the same
31724 application, a conflict will occur and the application will run
31725 incorrectly. Hence, when possible, it is always preferable to use and
31726 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31727 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31728 User's Guide) removes the debugging symbols from the DLL but the DLL can
31729 still be relocated.
31730
31731 As a side note, an interesting difference between Microsoft DLLs and
31732 Unix shared libraries, is the fact that on most Unix systems all public
31733 routines are exported by default in a Unix shared library, while under
31734 Windows it is possible (but not required) to list exported routines in
31735 a definition file (@pxref{The Definition File}).
31736
31737 @node Using DLLs with GNAT
31738 @section Using DLLs with GNAT
31739
31740 @menu
31741 * Creating an Ada Spec for the DLL Services::
31742 * Creating an Import Library::
31743 @end menu
31744
31745 @noindent
31746 To use the services of a DLL, say @file{API.dll}, in your Ada application
31747 you must have:
31748
31749 @enumerate
31750 @item
31751 The Ada spec for the routines and/or variables you want to access in
31752 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31753 header files provided with the DLL.
31754
31755 @item
31756 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31757 mentioned an import library is a statically linked library containing the
31758 import table which will be filled at load time to point to the actual
31759 @file{API.dll} routines. Sometimes you don't have an import library for the
31760 DLL you want to use. The following sections will explain how to build
31761 one. Note that this is optional.
31762
31763 @item
31764 The actual DLL, @file{API.dll}.
31765 @end enumerate
31766
31767 @noindent
31768 Once you have all the above, to compile an Ada application that uses the
31769 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31770 you simply issue the command
31771
31772 @smallexample
31773 $ gnatmake my_ada_app -largs -lAPI
31774 @end smallexample
31775
31776 @noindent
31777 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31778 tells the GNAT linker to look first for a library named @file{API.lib}
31779 (Microsoft-style name) and if not found for a libraries named
31780 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31781 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31782 contains the following pragma
31783
31784 @smallexample @c ada
31785 pragma Linker_Options ("-lAPI");
31786 @end smallexample
31787
31788 @noindent
31789 you do not have to add @option{-largs -lAPI} at the end of the
31790 @command{gnatmake} command.
31791
31792 If any one of the items above is missing you will have to create it
31793 yourself. The following sections explain how to do so using as an
31794 example a fictitious DLL called @file{API.dll}.
31795
31796 @node Creating an Ada Spec for the DLL Services
31797 @subsection Creating an Ada Spec for the DLL Services
31798
31799 @noindent
31800 A DLL typically comes with a C/C++ header file which provides the
31801 definitions of the routines and variables exported by the DLL. The Ada
31802 equivalent of this header file is a package spec that contains definitions
31803 for the imported entities. If the DLL you intend to use does not come with
31804 an Ada spec you have to generate one such spec yourself. For example if
31805 the header file of @file{API.dll} is a file @file{api.h} containing the
31806 following two definitions:
31807
31808 @smallexample
31809 @group
31810 @cartouche
31811 int some_var;
31812 int get (char *);
31813 @end cartouche
31814 @end group
31815 @end smallexample
31816
31817 @noindent
31818 then the equivalent Ada spec could be:
31819
31820 @smallexample @c ada
31821 @group
31822 @cartouche
31823 with Interfaces.C.Strings;
31824 package API is
31825    use Interfaces;
31826
31827    Some_Var : C.int;
31828    function Get (Str : C.Strings.Chars_Ptr) return C.int;
31829
31830 private
31831    pragma Import (C, Get);
31832    pragma Import (DLL, Some_Var);
31833 end API;
31834 @end cartouche
31835 @end group
31836 @end smallexample
31837
31838 @noindent
31839 Note that a variable is
31840 @strong{always imported with a Stdcall convention}. A function
31841 can have @code{C} or @code{Stdcall} convention.
31842 (@pxref{Windows Calling Conventions}).
31843
31844 @node Creating an Import Library
31845 @subsection Creating an Import Library
31846 @cindex Import library
31847
31848 @menu
31849 * The Definition File::
31850 * GNAT-Style Import Library::
31851 * Microsoft-Style Import Library::
31852 @end menu
31853
31854 @noindent
31855 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31856 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31857 with @file{API.dll} you can skip this section. You can also skip this
31858 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31859 as in this case it is possible to link directly against the
31860 DLL. Otherwise read on.
31861
31862 @node The Definition File
31863 @subsubsection The Definition File
31864 @cindex Definition file
31865 @findex .def
31866
31867 @noindent
31868 As previously mentioned, and unlike Unix systems, the list of symbols
31869 that are exported from a DLL must be provided explicitly in Windows.
31870 The main goal of a definition file is precisely that: list the symbols
31871 exported by a DLL. A definition file (usually a file with a @code{.def}
31872 suffix) has the following structure:
31873
31874 @smallexample
31875 @group
31876 @cartouche
31877 @r{[}LIBRARY @var{name}@r{]}
31878 @r{[}DESCRIPTION @var{string}@r{]}
31879 EXPORTS
31880    @var{symbol1}
31881    @var{symbol2}
31882    @dots{}
31883 @end cartouche
31884 @end group
31885 @end smallexample
31886
31887 @table @code
31888 @item LIBRARY @var{name}
31889 This section, which is optional, gives the name of the DLL.
31890
31891 @item DESCRIPTION @var{string}
31892 This section, which is optional, gives a description string that will be
31893 embedded in the import library.
31894
31895 @item EXPORTS
31896 This section gives the list of exported symbols (procedures, functions or
31897 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31898 section of @file{API.def} looks like:
31899
31900 @smallexample
31901 @group
31902 @cartouche
31903 EXPORTS
31904    some_var
31905    get
31906 @end cartouche
31907 @end group
31908 @end smallexample
31909 @end table
31910
31911 @noindent
31912 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31913 (@pxref{Windows Calling Conventions}) for a Stdcall
31914 calling convention function in the exported symbols list.
31915
31916 @noindent
31917 There can actually be other sections in a definition file, but these
31918 sections are not relevant to the discussion at hand.
31919
31920 @node GNAT-Style Import Library
31921 @subsubsection GNAT-Style Import Library
31922
31923 @noindent
31924 To create a static import library from @file{API.dll} with the GNAT tools
31925 you should proceed as follows:
31926
31927 @enumerate
31928 @item
31929 Create the definition file @file{API.def} (@pxref{The Definition File}).
31930 For that use the @code{dll2def} tool as follows:
31931
31932 @smallexample
31933 $ dll2def API.dll > API.def
31934 @end smallexample
31935
31936 @noindent
31937 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31938 to standard output the list of entry points in the DLL. Note that if
31939 some routines in the DLL have the @code{Stdcall} convention
31940 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31941 suffix then you'll have to edit @file{api.def} to add it, and specify
31942 @option{-k} to @command{gnatdll} when creating the import library.
31943
31944 @noindent
31945 Here are some hints to find the right @code{@@}@var{nn} suffix.
31946
31947 @enumerate
31948 @item
31949 If you have the Microsoft import library (.lib), it is possible to get
31950 the right symbols by using Microsoft @code{dumpbin} tool (see the
31951 corresponding Microsoft documentation for further details).
31952
31953 @smallexample
31954 $ dumpbin /exports api.lib
31955 @end smallexample
31956
31957 @item
31958 If you have a message about a missing symbol at link time the compiler
31959 tells you what symbol is expected. You just have to go back to the
31960 definition file and add the right suffix.
31961 @end enumerate
31962
31963 @item
31964 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31965 (@pxref{Using gnatdll}) as follows:
31966
31967 @smallexample
31968 $ gnatdll -e API.def -d API.dll
31969 @end smallexample
31970
31971 @noindent
31972 @code{gnatdll} takes as input a definition file @file{API.def} and the
31973 name of the DLL containing the services listed in the definition file
31974 @file{API.dll}. The name of the static import library generated is
31975 computed from the name of the definition file as follows: if the
31976 definition file name is @var{xyz}@code{.def}, the import library name will
31977 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31978 @option{-e} could have been removed because the name of the definition
31979 file (before the ``@code{.def}'' suffix) is the same as the name of the
31980 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31981 @end enumerate
31982
31983 @node Microsoft-Style Import Library
31984 @subsubsection Microsoft-Style Import Library
31985
31986 @noindent
31987 With GNAT you can either use a GNAT-style or Microsoft-style import
31988 library. A Microsoft import library is needed only if you plan to make an
31989 Ada DLL available to applications developed with Microsoft
31990 tools (@pxref{Mixed-Language Programming on Windows}).
31991
31992 To create a Microsoft-style import library for @file{API.dll} you
31993 should proceed as follows:
31994
31995 @enumerate
31996 @item
31997 Create the definition file @file{API.def} from the DLL. For this use either
31998 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31999 tool (see the corresponding Microsoft documentation for further details).
32000
32001 @item
32002 Build the actual import library using Microsoft's @code{lib} utility:
32003
32004 @smallexample
32005 $ lib -machine:IX86 -def:API.def -out:API.lib
32006 @end smallexample
32007
32008 @noindent
32009 If you use the above command the definition file @file{API.def} must
32010 contain a line giving the name of the DLL:
32011
32012 @smallexample
32013 LIBRARY      "API"
32014 @end smallexample
32015
32016 @noindent
32017 See the Microsoft documentation for further details about the usage of
32018 @code{lib}.
32019 @end enumerate
32020
32021 @node Building DLLs with GNAT
32022 @section Building DLLs with GNAT
32023 @cindex DLLs, building
32024
32025 @noindent
32026 This section explain how to build DLLs using the GNAT built-in DLL
32027 support. With the following procedure it is straight forward to build
32028 and use DLLs with GNAT.
32029
32030 @enumerate
32031
32032 @item building object files
32033
32034 The first step is to build all objects files that are to be included
32035 into the DLL. This is done by using the standard @command{gnatmake} tool.
32036
32037 @item building the DLL
32038
32039 To build the DLL you must use @command{gcc}'s @option{-shared}
32040 option. It is quite simple to use this method:
32041
32042 @smallexample
32043 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32044 @end smallexample
32045
32046 It is important to note that in this case all symbols found in the
32047 object files are automatically exported. It is possible to restrict
32048 the set of symbols to export by passing to @command{gcc} a definition
32049 file, @pxref{The Definition File}. For example:
32050
32051 @smallexample
32052 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32053 @end smallexample
32054
32055 If you use a definition file you must export the elaboration procedures
32056 for every package that required one. Elaboration procedures are named
32057 using the package name followed by "_E".
32058
32059 @item preparing DLL to be used
32060
32061 For the DLL to be used by client programs the bodies must be hidden
32062 from it and the .ali set with read-only attribute. This is very important
32063 otherwise GNAT will recompile all packages and will not actually use
32064 the code in the DLL. For example:
32065
32066 @smallexample
32067 $ mkdir apilib
32068 $ copy *.ads *.ali api.dll apilib
32069 $ attrib +R apilib\*.ali
32070 @end smallexample
32071
32072 @end enumerate
32073
32074 At this point it is possible to use the DLL by directly linking
32075 against it. Note that you must use the GNAT shared runtime when using
32076 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32077 option.
32078
32079 @smallexample
32080 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32081 @end smallexample
32082
32083 @node Building DLLs with GNAT Project files
32084 @section Building DLLs with GNAT Project files
32085 @cindex DLLs, building
32086
32087 @noindent
32088 There is nothing specific to Windows in the build process.
32089 @pxref{Library Projects}.
32090
32091 @noindent
32092 Due to a system limitation, it is not possible under Windows to create threads
32093 when inside the @code{DllMain} routine which is used for auto-initialization
32094 of shared libraries, so it is not possible to have library level tasks in SALs.
32095
32096 @node Building DLLs with gnatdll
32097 @section Building DLLs with gnatdll
32098 @cindex DLLs, building
32099
32100 @menu
32101 * Limitations When Using Ada DLLs from Ada::
32102 * Exporting Ada Entities::
32103 * Ada DLLs and Elaboration::
32104 * Ada DLLs and Finalization::
32105 * Creating a Spec for Ada DLLs::
32106 * Creating the Definition File::
32107 * Using gnatdll::
32108 @end menu
32109
32110 @noindent
32111 Note that it is preferred to use the built-in GNAT DLL support
32112 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32113 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32114
32115 This section explains how to build DLLs containing Ada code using
32116 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32117 remainder of this section.
32118
32119 The steps required to build an Ada DLL that is to be used by Ada as well as
32120 non-Ada applications are as follows:
32121
32122 @enumerate
32123 @item
32124 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32125 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32126 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32127 skip this step if you plan to use the Ada DLL only from Ada applications.
32128
32129 @item
32130 Your Ada code must export an initialization routine which calls the routine
32131 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32132 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32133 routine exported by the Ada DLL must be invoked by the clients of the DLL
32134 to initialize the DLL.
32135
32136 @item
32137 When useful, the DLL should also export a finalization routine which calls
32138 routine @code{adafinal} generated by @command{gnatbind} to perform the
32139 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32140 The finalization routine exported by the Ada DLL must be invoked by the
32141 clients of the DLL when the DLL services are no further needed.
32142
32143 @item
32144 You must provide a spec for the services exported by the Ada DLL in each
32145 of the programming languages to which you plan to make the DLL available.
32146
32147 @item
32148 You must provide a definition file listing the exported entities
32149 (@pxref{The Definition File}).
32150
32151 @item
32152 Finally you must use @code{gnatdll} to produce the DLL and the import
32153 library (@pxref{Using gnatdll}).
32154 @end enumerate
32155
32156 @noindent
32157 Note that a relocatable DLL stripped using the @code{strip}
32158 binutils tool will not be relocatable anymore. To build a DLL without
32159 debug information pass @code{-largs -s} to @code{gnatdll}. This
32160 restriction does not apply to a DLL built using a Library Project.
32161 @pxref{Library Projects}.
32162
32163 @node Limitations When Using Ada DLLs from Ada
32164 @subsection Limitations When Using Ada DLLs from Ada
32165
32166 @noindent
32167 When using Ada DLLs from Ada applications there is a limitation users
32168 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32169 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32170 each Ada DLL includes the services of the GNAT run time that are necessary
32171 to the Ada code inside the DLL. As a result, when an Ada program uses an
32172 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32173 one in the main program.
32174
32175 It is therefore not possible to exchange GNAT run-time objects between the
32176 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32177 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32178 types, etc.
32179
32180 It is completely safe to exchange plain elementary, array or record types,
32181 Windows object handles, etc.
32182
32183 @node Exporting Ada Entities
32184 @subsection Exporting Ada Entities
32185 @cindex Export table
32186
32187 @noindent
32188 Building a DLL is a way to encapsulate a set of services usable from any
32189 application. As a result, the Ada entities exported by a DLL should be
32190 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32191 any Ada name mangling. As an example here is an Ada package
32192 @code{API}, spec and body, exporting two procedures, a function, and a
32193 variable:
32194
32195 @smallexample @c ada
32196 @group
32197 @cartouche
32198 with Interfaces.C; use Interfaces;
32199 package API is
32200    Count : C.int := 0;
32201    function Factorial (Val : C.int) return C.int;
32202
32203    procedure Initialize_API;
32204    procedure Finalize_API;
32205    --  Initialization & Finalization routines. More in the next section.
32206 private
32207    pragma Export (C, Initialize_API);
32208    pragma Export (C, Finalize_API);
32209    pragma Export (C, Count);
32210    pragma Export (C, Factorial);
32211 end API;
32212 @end cartouche
32213 @end group
32214 @end smallexample
32215
32216 @smallexample @c ada
32217 @group
32218 @cartouche
32219 package body API is
32220    function Factorial (Val : C.int) return C.int is
32221       Fact : C.int := 1;
32222    begin
32223       Count := Count + 1;
32224       for K in 1 .. Val loop
32225          Fact := Fact * K;
32226       end loop;
32227       return Fact;
32228    end Factorial;
32229
32230    procedure Initialize_API is
32231       procedure Adainit;
32232       pragma Import (C, Adainit);
32233    begin
32234       Adainit;
32235    end Initialize_API;
32236
32237    procedure Finalize_API is
32238       procedure Adafinal;
32239       pragma Import (C, Adafinal);
32240    begin
32241       Adafinal;
32242    end Finalize_API;
32243 end API;
32244 @end cartouche
32245 @end group
32246 @end smallexample
32247
32248 @noindent
32249 If the Ada DLL you are building will only be used by Ada applications
32250 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32251 convention. As an example, the previous package could be written as
32252 follows:
32253
32254 @smallexample @c ada
32255 @group
32256 @cartouche
32257 package API is
32258    Count : Integer := 0;
32259    function Factorial (Val : Integer) return Integer;
32260
32261    procedure Initialize_API;
32262    procedure Finalize_API;
32263    --  Initialization and Finalization routines.
32264 end API;
32265 @end cartouche
32266 @end group
32267 @end smallexample
32268
32269 @smallexample @c ada
32270 @group
32271 @cartouche
32272 package body API is
32273    function Factorial (Val : Integer) return Integer is
32274       Fact : Integer := 1;
32275    begin
32276       Count := Count + 1;
32277       for K in 1 .. Val loop
32278          Fact := Fact * K;
32279       end loop;
32280       return Fact;
32281    end Factorial;
32282
32283    @dots{}
32284    --  The remainder of this package body is unchanged.
32285 end API;
32286 @end cartouche
32287 @end group
32288 @end smallexample
32289
32290 @noindent
32291 Note that if you do not export the Ada entities with a @code{C} or
32292 @code{Stdcall} convention you will have to provide the mangled Ada names
32293 in the definition file of the Ada DLL
32294 (@pxref{Creating the Definition File}).
32295
32296 @node Ada DLLs and Elaboration
32297 @subsection Ada DLLs and Elaboration
32298 @cindex DLLs and elaboration
32299
32300 @noindent
32301 The DLL that you are building contains your Ada code as well as all the
32302 routines in the Ada library that are needed by it. The first thing a
32303 user of your DLL must do is elaborate the Ada code
32304 (@pxref{Elaboration Order Handling in GNAT}).
32305
32306 To achieve this you must export an initialization routine
32307 (@code{Initialize_API} in the previous example), which must be invoked
32308 before using any of the DLL services. This elaboration routine must call
32309 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32310 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32311 @code{Initialize_Api} for an example. Note that the GNAT binder is
32312 automatically invoked during the DLL build process by the @code{gnatdll}
32313 tool (@pxref{Using gnatdll}).
32314
32315 When a DLL is loaded, Windows systematically invokes a routine called
32316 @code{DllMain}. It would therefore be possible to call @code{adainit}
32317 directly from @code{DllMain} without having to provide an explicit
32318 initialization routine. Unfortunately, it is not possible to call
32319 @code{adainit} from the @code{DllMain} if your program has library level
32320 tasks because access to the @code{DllMain} entry point is serialized by
32321 the system (that is, only a single thread can execute ``through'' it at a
32322 time), which means that the GNAT run time will deadlock waiting for the
32323 newly created task to complete its initialization.
32324
32325 @node Ada DLLs and Finalization
32326 @subsection Ada DLLs and Finalization
32327 @cindex DLLs and finalization
32328
32329 @noindent
32330 When the services of an Ada DLL are no longer needed, the client code should
32331 invoke the DLL finalization routine, if available. The DLL finalization
32332 routine is in charge of releasing all resources acquired by the DLL. In the
32333 case of the Ada code contained in the DLL, this is achieved by calling
32334 routine @code{adafinal} generated by the GNAT binder
32335 (@pxref{Binding with Non-Ada Main Programs}).
32336 See the body of @code{Finalize_Api} for an
32337 example. As already pointed out the GNAT binder is automatically invoked
32338 during the DLL build process by the @code{gnatdll} tool
32339 (@pxref{Using gnatdll}).
32340
32341 @node Creating a Spec for Ada DLLs
32342 @subsection Creating a Spec for Ada DLLs
32343
32344 @noindent
32345 To use the services exported by the Ada DLL from another programming
32346 language (e.g.@: C), you have to translate the specs of the exported Ada
32347 entities in that language. For instance in the case of @code{API.dll},
32348 the corresponding C header file could look like:
32349
32350 @smallexample
32351 @group
32352 @cartouche
32353 extern int *_imp__count;
32354 #define count (*_imp__count)
32355 int factorial (int);
32356 @end cartouche
32357 @end group
32358 @end smallexample
32359
32360 @noindent
32361 It is important to understand that when building an Ada DLL to be used by
32362 other Ada applications, you need two different specs for the packages
32363 contained in the DLL: one for building the DLL and the other for using
32364 the DLL. This is because the @code{DLL} calling convention is needed to
32365 use a variable defined in a DLL, but when building the DLL, the variable
32366 must have either the @code{Ada} or @code{C} calling convention. As an
32367 example consider a DLL comprising the following package @code{API}:
32368
32369 @smallexample @c ada
32370 @group
32371 @cartouche
32372 package API is
32373    Count : Integer := 0;
32374    @dots{}
32375    --  Remainder of the package omitted.
32376 end API;
32377 @end cartouche
32378 @end group
32379 @end smallexample
32380
32381 @noindent
32382 After producing a DLL containing package @code{API}, the spec that
32383 must be used to import @code{API.Count} from Ada code outside of the
32384 DLL is:
32385
32386 @smallexample @c ada
32387 @group
32388 @cartouche
32389 package API is
32390    Count : Integer;
32391    pragma Import (DLL, Count);
32392 end API;
32393 @end cartouche
32394 @end group
32395 @end smallexample
32396
32397 @node Creating the Definition File
32398 @subsection Creating the Definition File
32399
32400 @noindent
32401 The definition file is the last file needed to build the DLL. It lists
32402 the exported symbols. As an example, the definition file for a DLL
32403 containing only package @code{API} (where all the entities are exported
32404 with a @code{C} calling convention) is:
32405
32406 @smallexample
32407 @group
32408 @cartouche
32409 EXPORTS
32410     count
32411     factorial
32412     finalize_api
32413     initialize_api
32414 @end cartouche
32415 @end group
32416 @end smallexample
32417
32418 @noindent
32419 If the @code{C} calling convention is missing from package @code{API},
32420 then the definition file contains the mangled Ada names of the above
32421 entities, which in this case are:
32422
32423 @smallexample
32424 @group
32425 @cartouche
32426 EXPORTS
32427     api__count
32428     api__factorial
32429     api__finalize_api
32430     api__initialize_api
32431 @end cartouche
32432 @end group
32433 @end smallexample
32434
32435 @node Using gnatdll
32436 @subsection Using @code{gnatdll}
32437 @findex gnatdll
32438
32439 @menu
32440 * gnatdll Example::
32441 * gnatdll behind the Scenes::
32442 * Using dlltool::
32443 @end menu
32444
32445 @noindent
32446 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32447 and non-Ada sources that make up your DLL have been compiled.
32448 @code{gnatdll} is actually in charge of two distinct tasks: build the
32449 static import library for the DLL and the actual DLL. The form of the
32450 @code{gnatdll} command is
32451
32452 @smallexample
32453 @cartouche
32454 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32455 @end cartouche
32456 @end smallexample
32457
32458 @noindent
32459 where @var{list-of-files} is a list of ALI and object files. The object
32460 file list must be the exact list of objects corresponding to the non-Ada
32461 sources whose services are to be included in the DLL. The ALI file list
32462 must be the exact list of ALI files for the corresponding Ada sources
32463 whose services are to be included in the DLL. If @var{list-of-files} is
32464 missing, only the static import library is generated.
32465
32466 @noindent
32467 You may specify any of the following switches to @code{gnatdll}:
32468
32469 @table @code
32470 @item -a@ovar{address}
32471 @cindex @option{-a} (@code{gnatdll})
32472 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32473 specified the default address @var{0x11000000} will be used. By default,
32474 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32475 advise the reader to build relocatable DLL.
32476
32477 @item -b @var{address}
32478 @cindex @option{-b} (@code{gnatdll})
32479 Set the relocatable DLL base address. By default the address is
32480 @code{0x11000000}.
32481
32482 @item -bargs @var{opts}
32483 @cindex @option{-bargs} (@code{gnatdll})
32484 Binder options. Pass @var{opts} to the binder.
32485
32486 @item -d @var{dllfile}
32487 @cindex @option{-d} (@code{gnatdll})
32488 @var{dllfile} is the name of the DLL. This switch must be present for
32489 @code{gnatdll} to do anything. The name of the generated import library is
32490 obtained algorithmically from @var{dllfile} as shown in the following
32491 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32492 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32493 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32494 as shown in the following example:
32495 if @var{dllfile} is @code{xyz.dll}, the definition
32496 file used is @code{xyz.def}.
32497
32498 @item -e @var{deffile}
32499 @cindex @option{-e} (@code{gnatdll})
32500 @var{deffile} is the name of the definition file.
32501
32502 @item -g
32503 @cindex @option{-g} (@code{gnatdll})
32504 Generate debugging information. This information is stored in the object
32505 file and copied from there to the final DLL file by the linker,
32506 where it can be read by the debugger. You must use the
32507 @option{-g} switch if you plan on using the debugger or the symbolic
32508 stack traceback.
32509
32510 @item -h
32511 @cindex @option{-h} (@code{gnatdll})
32512 Help mode. Displays @code{gnatdll} switch usage information.
32513
32514 @item -Idir
32515 @cindex @option{-I} (@code{gnatdll})
32516 Direct @code{gnatdll} to search the @var{dir} directory for source and
32517 object files needed to build the DLL.
32518 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32519
32520 @item -k
32521 @cindex @option{-k} (@code{gnatdll})
32522 Removes the @code{@@}@var{nn} suffix from the import library's exported
32523 names, but keeps them for the link names. You must specify this
32524 option if you want to use a @code{Stdcall} function in a DLL for which
32525 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32526 of the Windows NT DLL for example. This option has no effect when
32527 @option{-n} option is specified.
32528
32529 @item -l @var{file}
32530 @cindex @option{-l} (@code{gnatdll})
32531 The list of ALI and object files used to build the DLL are listed in
32532 @var{file}, instead of being given in the command line. Each line in
32533 @var{file} contains the name of an ALI or object file.
32534
32535 @item -n
32536 @cindex @option{-n} (@code{gnatdll})
32537 No Import. Do not create the import library.
32538
32539 @item -q
32540 @cindex @option{-q} (@code{gnatdll})
32541 Quiet mode. Do not display unnecessary messages.
32542
32543 @item -v
32544 @cindex @option{-v} (@code{gnatdll})
32545 Verbose mode. Display extra information.
32546
32547 @item -largs @var{opts}
32548 @cindex @option{-largs} (@code{gnatdll})
32549 Linker options. Pass @var{opts} to the linker.
32550 @end table
32551
32552 @node gnatdll Example
32553 @subsubsection @code{gnatdll} Example
32554
32555 @noindent
32556 As an example the command to build a relocatable DLL from @file{api.adb}
32557 once @file{api.adb} has been compiled and @file{api.def} created is
32558
32559 @smallexample
32560 $ gnatdll -d api.dll api.ali
32561 @end smallexample
32562
32563 @noindent
32564 The above command creates two files: @file{libapi.dll.a} (the import
32565 library) and @file{api.dll} (the actual DLL). If you want to create
32566 only the DLL, just type:
32567
32568 @smallexample
32569 $ gnatdll -d api.dll -n api.ali
32570 @end smallexample
32571
32572 @noindent
32573 Alternatively if you want to create just the import library, type:
32574
32575 @smallexample
32576 $ gnatdll -d api.dll
32577 @end smallexample
32578
32579 @node gnatdll behind the Scenes
32580 @subsubsection @code{gnatdll} behind the Scenes
32581
32582 @noindent
32583 This section details the steps involved in creating a DLL. @code{gnatdll}
32584 does these steps for you. Unless you are interested in understanding what
32585 goes on behind the scenes, you should skip this section.
32586
32587 We use the previous example of a DLL containing the Ada package @code{API},
32588 to illustrate the steps necessary to build a DLL. The starting point is a
32589 set of objects that will make up the DLL and the corresponding ALI
32590 files. In the case of this example this means that @file{api.o} and
32591 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32592 the following:
32593
32594 @enumerate
32595 @item
32596 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32597 the information necessary to generate relocation information for the
32598 DLL.
32599
32600 @smallexample
32601 @group
32602 $ gnatbind -n api
32603 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32604 @end group
32605 @end smallexample
32606
32607 @noindent
32608 In addition to the base file, the @command{gnatlink} command generates an
32609 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32610 asks @command{gnatlink} to generate the routines @code{DllMain} and
32611 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32612 is loaded into memory.
32613
32614 @item
32615 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32616 export table (@file{api.exp}). The export table contains the relocation
32617 information in a form which can be used during the final link to ensure
32618 that the Windows loader is able to place the DLL anywhere in memory.
32619
32620 @smallexample
32621 @group
32622 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32623           --output-exp api.exp
32624 @end group
32625 @end smallexample
32626
32627 @item
32628 @code{gnatdll} builds the base file using the new export table. Note that
32629 @command{gnatbind} must be called once again since the binder generated file
32630 has been deleted during the previous call to @command{gnatlink}.
32631
32632 @smallexample
32633 @group
32634 $ gnatbind -n api
32635 $ gnatlink api -o api.jnk api.exp -mdll
32636       -Wl,--base-file,api.base
32637 @end group
32638 @end smallexample
32639
32640 @item
32641 @code{gnatdll} builds the new export table using the new base file and
32642 generates the DLL import library @file{libAPI.dll.a}.
32643
32644 @smallexample
32645 @group
32646 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32647           --output-exp api.exp --output-lib libAPI.a
32648 @end group
32649 @end smallexample
32650
32651 @item
32652 Finally @code{gnatdll} builds the relocatable DLL using the final export
32653 table.
32654
32655 @smallexample
32656 @group
32657 $ gnatbind -n api
32658 $ gnatlink api api.exp -o api.dll -mdll
32659 @end group
32660 @end smallexample
32661 @end enumerate
32662
32663 @node Using dlltool
32664 @subsubsection Using @code{dlltool}
32665
32666 @noindent
32667 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32668 DLLs and static import libraries. This section summarizes the most
32669 common @code{dlltool} switches. The form of the @code{dlltool} command
32670 is
32671
32672 @smallexample
32673 $ dlltool @ovar{switches}
32674 @end smallexample
32675
32676 @noindent
32677 @code{dlltool} switches include:
32678
32679 @table @option
32680 @item --base-file @var{basefile}
32681 @cindex @option{--base-file} (@command{dlltool})
32682 Read the base file @var{basefile} generated by the linker. This switch
32683 is used to create a relocatable DLL.
32684
32685 @item --def @var{deffile}
32686 @cindex @option{--def} (@command{dlltool})
32687 Read the definition file.
32688
32689 @item --dllname @var{name}
32690 @cindex @option{--dllname} (@command{dlltool})
32691 Gives the name of the DLL. This switch is used to embed the name of the
32692 DLL in the static import library generated by @code{dlltool} with switch
32693 @option{--output-lib}.
32694
32695 @item -k
32696 @cindex @option{-k} (@command{dlltool})
32697 Kill @code{@@}@var{nn} from exported names
32698 (@pxref{Windows Calling Conventions}
32699 for a discussion about @code{Stdcall}-style symbols.
32700
32701 @item --help
32702 @cindex @option{--help} (@command{dlltool})
32703 Prints the @code{dlltool} switches with a concise description.
32704
32705 @item --output-exp @var{exportfile}
32706 @cindex @option{--output-exp} (@command{dlltool})
32707 Generate an export file @var{exportfile}. The export file contains the
32708 export table (list of symbols in the DLL) and is used to create the DLL.
32709
32710 @item --output-lib @var{libfile}
32711 @cindex @option{--output-lib} (@command{dlltool})
32712 Generate a static import library @var{libfile}.
32713
32714 @item -v
32715 @cindex @option{-v} (@command{dlltool})
32716 Verbose mode.
32717
32718 @item --as @var{assembler-name}
32719 @cindex @option{--as} (@command{dlltool})
32720 Use @var{assembler-name} as the assembler. The default is @code{as}.
32721 @end table
32722
32723 @node GNAT and Windows Resources
32724 @section GNAT and Windows Resources
32725 @cindex Resources, windows
32726
32727 @menu
32728 * Building Resources::
32729 * Compiling Resources::
32730 * Using Resources::
32731 @end menu
32732
32733 @noindent
32734 Resources are an easy way to add Windows specific objects to your
32735 application. The objects that can be added as resources include:
32736
32737 @itemize @bullet
32738 @item
32739 menus
32740
32741 @item
32742 accelerators
32743
32744 @item
32745 dialog boxes
32746
32747 @item
32748 string tables
32749
32750 @item
32751 bitmaps
32752
32753 @item
32754 cursors
32755
32756 @item
32757 icons
32758
32759 @item
32760 fonts
32761 @end itemize
32762
32763 @noindent
32764 This section explains how to build, compile and use resources.
32765
32766 @node Building Resources
32767 @subsection Building Resources
32768 @cindex Resources, building
32769
32770 @noindent
32771 A resource file is an ASCII file. By convention resource files have an
32772 @file{.rc} extension.
32773 The easiest way to build a resource file is to use Microsoft tools
32774 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32775 @code{dlgedit.exe} to build dialogs.
32776 It is always possible to build an @file{.rc} file yourself by writing a
32777 resource script.
32778
32779 It is not our objective to explain how to write a resource file. A
32780 complete description of the resource script language can be found in the
32781 Microsoft documentation.
32782
32783 @node Compiling Resources
32784 @subsection Compiling Resources
32785 @findex rc
32786 @findex windres
32787 @cindex Resources, compiling
32788
32789 @noindent
32790 This section describes how to build a GNAT-compatible (COFF) object file
32791 containing the resources. This is done using the Resource Compiler
32792 @code{windres} as follows:
32793
32794 @smallexample
32795 $ windres -i myres.rc -o myres.o
32796 @end smallexample
32797
32798 @noindent
32799 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32800 file. You can specify an alternate preprocessor (usually named
32801 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32802 parameter. A list of all possible options may be obtained by entering
32803 the command @code{windres} @option{--help}.
32804
32805 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32806 to produce a @file{.res} file (binary resource file). See the
32807 corresponding Microsoft documentation for further details. In this case
32808 you need to use @code{windres} to translate the @file{.res} file to a
32809 GNAT-compatible object file as follows:
32810
32811 @smallexample
32812 $ windres -i myres.res -o myres.o
32813 @end smallexample
32814
32815 @node Using Resources
32816 @subsection Using Resources
32817 @cindex Resources, using
32818
32819 @noindent
32820 To include the resource file in your program just add the
32821 GNAT-compatible object file for the resource(s) to the linker
32822 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32823 option:
32824
32825 @smallexample
32826 $ gnatmake myprog -largs myres.o
32827 @end smallexample
32828
32829 @node Debugging a DLL
32830 @section Debugging a DLL
32831 @cindex DLL debugging
32832
32833 @menu
32834 * Program and DLL Both Built with GCC/GNAT::
32835 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32836 @end menu
32837
32838 @noindent
32839 Debugging a DLL is similar to debugging a standard program. But
32840 we have to deal with two different executable parts: the DLL and the
32841 program that uses it. We have the following four possibilities:
32842
32843 @enumerate 1
32844 @item
32845 The program and the DLL are built with @code{GCC/GNAT}.
32846 @item
32847 The program is built with foreign tools and the DLL is built with
32848 @code{GCC/GNAT}.
32849 @item
32850 The program is built with @code{GCC/GNAT} and the DLL is built with
32851 foreign tools.
32852 @item
32853 @end enumerate
32854
32855 @noindent
32856 In this section we address only cases one and two above.
32857 There is no point in trying to debug
32858 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32859 information in it. To do so you must use a debugger compatible with the
32860 tools suite used to build the DLL.
32861
32862 @node Program and DLL Both Built with GCC/GNAT
32863 @subsection Program and DLL Both Built with GCC/GNAT
32864
32865 @noindent
32866 This is the simplest case. Both the DLL and the program have @code{GDB}
32867 compatible debugging information. It is then possible to break anywhere in
32868 the process. Let's suppose here that the main procedure is named
32869 @code{ada_main} and that in the DLL there is an entry point named
32870 @code{ada_dll}.
32871
32872 @noindent
32873 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32874 program must have been built with the debugging information (see GNAT -g
32875 switch). Here are the step-by-step instructions for debugging it:
32876
32877 @enumerate 1
32878 @item Launch @code{GDB} on the main program.
32879
32880 @smallexample
32881 $ gdb -nw ada_main
32882 @end smallexample
32883
32884 @item Start the program and stop at the beginning of the main procedure
32885
32886 @smallexample
32887 (gdb) start
32888 @end smallexample
32889
32890 @noindent
32891 This step is required to be able to set a breakpoint inside the DLL. As long
32892 as the program is not run, the DLL is not loaded. This has the
32893 consequence that the DLL debugging information is also not loaded, so it is not
32894 possible to set a breakpoint in the DLL.
32895
32896 @item Set a breakpoint inside the DLL
32897
32898 @smallexample
32899 (gdb) break ada_dll
32900 (gdb) cont
32901 @end smallexample
32902
32903 @end enumerate
32904
32905 @noindent
32906 At this stage a breakpoint is set inside the DLL. From there on
32907 you can use the standard approach to debug the whole program
32908 (@pxref{Running and Debugging Ada Programs}).
32909
32910 @ignore
32911 @c This used to work, probably because the DLLs were non-relocatable
32912 @c keep this section around until the problem is sorted out.
32913
32914 To break on the @code{DllMain} routine it is not possible to follow
32915 the procedure above. At the time the program stop on @code{ada_main}
32916 the @code{DllMain} routine as already been called. Either you can use
32917 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32918
32919 @enumerate 1
32920 @item Launch @code{GDB} on the main program.
32921
32922 @smallexample
32923 $ gdb ada_main
32924 @end smallexample
32925
32926 @item Load DLL symbols
32927
32928 @smallexample
32929 (gdb) add-sym api.dll
32930 @end smallexample
32931
32932 @item Set a breakpoint inside the DLL
32933
32934 @smallexample
32935 (gdb) break ada_dll.adb:45
32936 @end smallexample
32937
32938 Note that at this point it is not possible to break using the routine symbol
32939 directly as the program is not yet running. The solution is to break
32940 on the proper line (break in @file{ada_dll.adb} line 45).
32941
32942 @item Start the program
32943
32944 @smallexample
32945 (gdb) run
32946 @end smallexample
32947
32948 @end enumerate
32949 @end ignore
32950
32951 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32952 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32953
32954 @menu
32955 * Debugging the DLL Directly::
32956 * Attaching to a Running Process::
32957 @end menu
32958
32959 @noindent
32960 In this case things are slightly more complex because it is not possible to
32961 start the main program and then break at the beginning to load the DLL and the
32962 associated DLL debugging information. It is not possible to break at the
32963 beginning of the program because there is no @code{GDB} debugging information,
32964 and therefore there is no direct way of getting initial control. This
32965 section addresses this issue by describing some methods that can be used
32966 to break somewhere in the DLL to debug it.
32967
32968 @noindent
32969 First suppose that the main procedure is named @code{main} (this is for
32970 example some C code built with Microsoft Visual C) and that there is a
32971 DLL named @code{test.dll} containing an Ada entry point named
32972 @code{ada_dll}.
32973
32974 @noindent
32975 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32976 been built with debugging information (see GNAT -g option).
32977
32978 @node Debugging the DLL Directly
32979 @subsubsection Debugging the DLL Directly
32980
32981 @enumerate 1
32982 @item
32983 Find out the executable starting address
32984
32985 @smallexample
32986 $ objdump --file-header main.exe
32987 @end smallexample
32988
32989 The starting address is reported on the last line. For example:
32990
32991 @smallexample
32992 main.exe:     file format pei-i386
32993 architecture: i386, flags 0x0000010a:
32994 EXEC_P, HAS_DEBUG, D_PAGED
32995 start address 0x00401010
32996 @end smallexample
32997
32998 @item
32999 Launch the debugger on the executable.
33000
33001 @smallexample
33002 $ gdb main.exe
33003 @end smallexample
33004
33005 @item
33006 Set a breakpoint at the starting address, and launch the program.
33007
33008 @smallexample
33009 $ (gdb) break *0x00401010
33010 $ (gdb) run
33011 @end smallexample
33012
33013 The program will stop at the given address.
33014
33015 @item
33016 Set a breakpoint on a DLL subroutine.
33017
33018 @smallexample
33019 (gdb) break ada_dll.adb:45
33020 @end smallexample
33021
33022 Or if you want to break using a symbol on the DLL, you need first to
33023 select the Ada language (language used by the DLL).
33024
33025 @smallexample
33026 (gdb) set language ada
33027 (gdb) break ada_dll
33028 @end smallexample
33029
33030 @item
33031 Continue the program.
33032
33033 @smallexample
33034 (gdb) cont
33035 @end smallexample
33036
33037 @noindent
33038 This will run the program until it reaches the breakpoint that has been
33039 set. From that point you can use the standard way to debug a program
33040 as described in (@pxref{Running and Debugging Ada Programs}).
33041
33042 @end enumerate
33043
33044 @noindent
33045 It is also possible to debug the DLL by attaching to a running process.
33046
33047 @node Attaching to a Running Process
33048 @subsubsection Attaching to a Running Process
33049 @cindex DLL debugging, attach to process
33050
33051 @noindent
33052 With @code{GDB} it is always possible to debug a running process by
33053 attaching to it. It is possible to debug a DLL this way. The limitation
33054 of this approach is that the DLL must run long enough to perform the
33055 attach operation. It may be useful for instance to insert a time wasting
33056 loop in the code of the DLL to meet this criterion.
33057
33058 @enumerate 1
33059
33060 @item Launch the main program @file{main.exe}.
33061
33062 @smallexample
33063 $ main
33064 @end smallexample
33065
33066 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33067 that the process PID for @file{main.exe} is 208.
33068
33069 @item Launch gdb.
33070
33071 @smallexample
33072 $ gdb
33073 @end smallexample
33074
33075 @item Attach to the running process to be debugged.
33076
33077 @smallexample
33078 (gdb) attach 208
33079 @end smallexample
33080
33081 @item Load the process debugging information.
33082
33083 @smallexample
33084 (gdb) symbol-file main.exe
33085 @end smallexample
33086
33087 @item Break somewhere in the DLL.
33088
33089 @smallexample
33090 (gdb) break ada_dll
33091 @end smallexample
33092
33093 @item Continue process execution.
33094
33095 @smallexample
33096 (gdb) cont
33097 @end smallexample
33098
33099 @end enumerate
33100
33101 @noindent
33102 This last step will resume the process execution, and stop at
33103 the breakpoint we have set. From there you can use the standard
33104 approach to debug a program as described in
33105 (@pxref{Running and Debugging Ada Programs}).
33106
33107 @node Setting Stack Size from gnatlink
33108 @section Setting Stack Size from @command{gnatlink}
33109
33110 @noindent
33111 It is possible to specify the program stack size at link time. On modern
33112 versions of Windows, starting with XP, this is mostly useful to set the size of
33113 the main stack (environment task). The other task stacks are set with pragma
33114 Storage_Size or with the @command{gnatbind -d} command.
33115
33116 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33117 reserve size of individual tasks, the link-time stack size applies to all
33118 tasks, and pragma Storage_Size has no effect.
33119 In particular, Stack Overflow checks are made against this
33120 link-time specified size.
33121
33122 This setting can be done with
33123 @command{gnatlink} using either:
33124
33125 @itemize @bullet
33126
33127 @item using @option{-Xlinker} linker option
33128
33129 @smallexample
33130 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33131 @end smallexample
33132
33133 This sets the stack reserve size to 0x10000 bytes and the stack commit
33134 size to 0x1000 bytes.
33135
33136 @item using @option{-Wl} linker option
33137
33138 @smallexample
33139 $ gnatlink hello -Wl,--stack=0x1000000
33140 @end smallexample
33141
33142 This sets the stack reserve size to 0x1000000 bytes. Note that with
33143 @option{-Wl} option it is not possible to set the stack commit size
33144 because the coma is a separator for this option.
33145
33146 @end itemize
33147
33148 @node Setting Heap Size from gnatlink
33149 @section Setting Heap Size from @command{gnatlink}
33150
33151 @noindent
33152 Under Windows systems, it is possible to specify the program heap size from
33153 @command{gnatlink} using either:
33154
33155 @itemize @bullet
33156
33157 @item using @option{-Xlinker} linker option
33158
33159 @smallexample
33160 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33161 @end smallexample
33162
33163 This sets the heap reserve size to 0x10000 bytes and the heap commit
33164 size to 0x1000 bytes.
33165
33166 @item using @option{-Wl} linker option
33167
33168 @smallexample
33169 $ gnatlink hello -Wl,--heap=0x1000000
33170 @end smallexample
33171
33172 This sets the heap reserve size to 0x1000000 bytes. Note that with
33173 @option{-Wl} option it is not possible to set the heap commit size
33174 because the coma is a separator for this option.
33175
33176 @end itemize
33177
33178 @end ifset
33179
33180 @c **********************************
33181 @c * GNU Free Documentation License *
33182 @c **********************************
33183 @include fdl.texi
33184 @c GNU Free Documentation License
33185
33186 @node Index,,GNU Free Documentation License, Top
33187 @unnumbered Index
33188
33189 @printindex cp
33190
33191 @contents
33192 @c Put table of contents at end, otherwise it precedes the "title page" in
33193 @c the .txt version
33194 @c Edit the pdf file to move the contents to the beginning, after the title
33195 @c page
33196
33197 @bye