OSDN Git Service

2009-07-13 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.2 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * gnatxref Switches::
394 * gnatfind Switches::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Predefined Rules::
494
495 Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 * Converting Ada Files to html with gnathtml::
505
506 @ifclear vms
507 Code Coverage and Profiling
508
509 * Code Coverage of Ada Programs using gcov::
510 * Profiling an Ada Program using gprof::
511 @end ifclear
512
513 Running and Debugging Ada Programs
514
515 * The GNAT Debugger GDB::
516 * Running GDB::
517 * Introduction to GDB Commands::
518 * Using Ada Expressions::
519 * Calling User-Defined Subprograms::
520 * Using the Next Command in a Function::
521 * Ada Exceptions::
522 * Ada Tasks::
523 * Debugging Generic Units::
524 * GNAT Abnormal Termination or Failure to Terminate::
525 * Naming Conventions for GNAT Source Files::
526 * Getting Internal Debugging Information::
527 * Stack Traceback::
528
529 @ifset vms
530 * LSE::
531 @end ifset
532
533 @ifset vms
534 Compatibility with HP Ada
535
536 * Ada Language Compatibility::
537 * Differences in the Definition of Package System::
538 * Language-Related Features::
539 * The Package STANDARD::
540 * The Package SYSTEM::
541 * Tasking and Task-Related Features::
542 * Pragmas and Pragma-Related Features::
543 * Library of Predefined Units::
544 * Bindings::
545 * Main Program Definition::
546 * Implementation-Defined Attributes::
547 * Compiler and Run-Time Interfacing::
548 * Program Compilation and Library Management::
549 * Input-Output::
550 * Implementation Limits::
551 * Tools and Utilities::
552
553 Language-Related Features
554
555 * Integer Types and Representations::
556 * Floating-Point Types and Representations::
557 * Pragmas Float_Representation and Long_Float::
558 * Fixed-Point Types and Representations::
559 * Record and Array Component Alignment::
560 * Address Clauses::
561 * Other Representation Clauses::
562
563 Tasking and Task-Related Features
564
565 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
566 * Assigning Task IDs::
567 * Task IDs and Delays::
568 * Task-Related Pragmas::
569 * Scheduling and Task Priority::
570 * The Task Stack::
571 * External Interrupts::
572
573 Pragmas and Pragma-Related Features
574
575 * Restrictions on the Pragma INLINE::
576 * Restrictions on the Pragma INTERFACE::
577 * Restrictions on the Pragma SYSTEM_NAME::
578
579 Library of Predefined Units
580
581 * Changes to DECLIB::
582
583 Bindings
584
585 * Shared Libraries and Options Files::
586 * Interfaces to C::
587 @end ifset
588
589 Platform-Specific Information for the Run-Time Libraries
590
591 * Summary of Run-Time Configurations::
592 * Specifying a Run-Time Library::
593 * Choosing the Scheduling Policy::
594 * Solaris-Specific Considerations::
595 * Linux-Specific Considerations::
596 * AIX-Specific Considerations::
597 * Irix-Specific Considerations::
598
599 Example of Binder Output File
600
601 Elaboration Order Handling in GNAT
602
603 * Elaboration Code::
604 * Checking the Elaboration Order::
605 * Controlling the Elaboration Order::
606 * Controlling Elaboration in GNAT - Internal Calls::
607 * Controlling Elaboration in GNAT - External Calls::
608 * Default Behavior in GNAT - Ensuring Safety::
609 * Treatment of Pragma Elaborate::
610 * Elaboration Issues for Library Tasks::
611 * Mixing Elaboration Models::
612 * What to Do If the Default Elaboration Behavior Fails::
613 * Elaboration for Access-to-Subprogram Values::
614 * Summary of Procedures for Elaboration Control::
615 * Other Elaboration Order Considerations::
616
617 Conditional Compilation
618 * Use of Boolean Constants::
619 * Debugging - A Special Case::
620 * Conditionalizing Declarations::
621 * Use of Alternative Implementations::
622 * Preprocessing::
623
624 Inline Assembler
625
626 * Basic Assembler Syntax::
627 * A Simple Example of Inline Assembler::
628 * Output Variables in Inline Assembler::
629 * Input Variables in Inline Assembler::
630 * Inlining Inline Assembler Code::
631 * Other Asm Functionality::
632
633 Compatibility and Porting Guide
634
635 * Compatibility with Ada 83::
636 * Compatibility between Ada 95 and Ada 2005::
637 * Implementation-dependent characteristics::
638 @ifclear vms
639 @c This brief section is only in the non-VMS version
640 @c The complete chapter on HP Ada issues is in the VMS version
641 * Compatibility with HP Ada 83::
642 @end ifclear
643 * Compatibility with Other Ada Systems::
644 * Representation Clauses::
645 @ifset vms
646 * Transitioning to 64-Bit GNAT for OpenVMS::
647 @end ifset
648
649 @ifset unw
650 Microsoft Windows Topics
651
652 * Using GNAT on Windows::
653 * CONSOLE and WINDOWS subsystems::
654 * Temporary Files::
655 * Mixed-Language Programming on Windows::
656 * Windows Calling Conventions::
657 * Introduction to Dynamic Link Libraries (DLLs)::
658 * Using DLLs with GNAT::
659 * Building DLLs with GNAT::
660 * GNAT and Windows Resources::
661 * Debugging a DLL::
662 * Setting Stack Size from gnatlink::
663 * Setting Heap Size from gnatlink::
664 @end ifset
665
666 * Index::
667 @end menu
668 @end ifnottex
669
670 @node About This Guide
671 @unnumbered About This Guide
672
673 @noindent
674 @ifset vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development toolset for the full Ada
677 programming language, implemented on OpenVMS for HP's Alpha and
678 Integrity server (I64) platforms.
679 @end ifset
680 @ifclear vms
681 This guide describes the use of @value{EDITION},
682 a compiler and software development
683 toolset for the full Ada programming language.
684 @end ifclear
685 It documents the features of the compiler and tools, and explains
686 how to use them to build Ada applications.
687
688 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
689 Ada 83 compatibility mode.
690 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
691 but you can override with a compiler switch
692 (@pxref{Compiling Different Versions of Ada})
693 to explicitly specify the language version.
694 Throughout this manual, references to ``Ada'' without a year suffix
695 apply to both the Ada 95 and Ada 2005 versions of the language.
696
697
698 @ifclear FSFEDITION
699 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
700 ``GNAT'' in the remainder of this document.
701 @end ifclear
702
703
704
705
706 @menu
707 * What This Guide Contains::
708 * What You Should Know before Reading This Guide::
709 * Related Information::
710 * Conventions::
711 @end menu
712
713 @node What This Guide Contains
714 @unnumberedsec What This Guide Contains
715
716 @noindent
717 This guide contains the following chapters:
718 @itemize @bullet
719
720 @item
721 @ref{Getting Started with GNAT}, describes how to get started compiling
722 and running Ada programs with the GNAT Ada programming environment.
723 @item
724 @ref{The GNAT Compilation Model}, describes the compilation model used
725 by GNAT.
726
727 @item
728 @ref{Compiling Using gcc}, describes how to compile
729 Ada programs with @command{gcc}, the Ada compiler.
730
731 @item
732 @ref{Binding Using gnatbind}, describes how to
733 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 utility.
735
736 @item
737 @ref{Linking Using gnatlink},
738 describes @command{gnatlink}, a
739 program that provides for linking using the GNAT run-time library to
740 construct a program. @command{gnatlink} can also incorporate foreign language
741 object units into the executable.
742
743 @item
744 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
745 utility that automatically determines the set of sources
746 needed by an Ada compilation unit, and executes the necessary compilations
747 binding and link.
748
749 @item
750 @ref{Improving Performance}, shows various techniques for making your
751 Ada program run faster or take less space.
752 It discusses the effect of the compiler's optimization switch and
753 also describes the @command{gnatelim} tool and unused subprogram/data
754 elimination.
755
756 @item
757 @ref{Renaming Files Using gnatchop}, describes
758 @code{gnatchop}, a utility that allows you to preprocess a file that
759 contains Ada source code, and split it into one or more new files, one
760 for each compilation unit.
761
762 @item
763 @ref{Configuration Pragmas}, describes the configuration pragmas
764 handled by GNAT.
765
766 @item
767 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
768 shows how to override the default GNAT file naming conventions,
769 either for an individual unit or globally.
770
771 @item
772 @ref{GNAT Project Manager}, describes how to use project files
773 to organize large projects.
774
775 @item
776 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
777 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
778 way to navigate through sources.
779
780 @item
781 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
782 version of an Ada source file with control over casing, indentation,
783 comment placement, and other elements of program presentation style.
784
785 @item
786 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
787 metrics for an Ada source file, such as the number of types and subprograms,
788 and assorted complexity measures.
789
790 @item
791 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
792 file name krunching utility, used to handle shortened
793 file names on operating systems with a limit on the length of names.
794
795 @item
796 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
797 preprocessor utility that allows a single source file to be used to
798 generate multiple or parameterized source files by means of macro
799 substitution.
800
801 @ifset vms
802 @item
803 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
804 a tool for rebuilding the GNAT run time with user-supplied
805 configuration pragmas.
806 @end ifset
807
808 @item
809 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
810 utility that displays information about compiled units, including dependences
811 on the corresponding sources files, and consistency of compilations.
812
813 @item
814 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
815 to delete files that are produced by the compiler, binder and linker.
816
817 @ifclear vms
818 @item
819 @ref{GNAT and Libraries}, describes the process of creating and using
820 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 library.
822
823 @item
824 @ref{Using the GNU make Utility}, describes some techniques for using
825 the GNAT toolset in Makefiles.
826 @end ifclear
827
828 @item
829 @ref{Memory Management Issues}, describes some useful predefined storage pools
830 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 memory references.
832 @ifclear vms
833 It also describes @command{gnatmem}, a utility that monitors dynamic
834 allocation and deallocation and helps detect ``memory leaks''.
835 @end ifclear
836
837 @item
838 @ref{Stack Related Facilities}, describes some useful tools associated with
839 stack checking and analysis.
840
841 @item
842 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
843 a utility that checks Ada code against a set of rules.
844
845 @item
846 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
847 a utility that generates empty but compilable bodies for library units.
848
849 @item
850 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
851 generate automatically Ada bindings from C and C++ headers.
852
853 @item
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
856
857 @ifclear vms
858 @item
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
861 @end ifclear
862
863 @item
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
865 Ada programs.
866
867 @ifset vms
868 @item
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
873 @cindex DEC Ada
874 and for
875 historical compatibility reasons, the relevant libraries still use the
876 DEC prefix.
877 @end ifset
878
879 @item
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
884
885 @item
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
888
889 @item
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
892
893 @item
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
896
897 @item
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
899 in an Ada program.
900
901 @item
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
905
906 @ifset unw
907 @item
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
910 @end ifset
911 @end itemize
912
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
917
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
920 @noindent
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
923 1995.
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
926 and Amendment 1).
927 Both reference manuals are included in the GNAT documentation
928 package.
929
930 @node Related Information
931 @unnumberedsec Related Information
932
933 @noindent
934 For further information about related tools, refer to the following
935 documents:
936
937 @itemize @bullet
938 @item
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
942
943 @ifset unw
944 @item
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
947
948 @item
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
951 @end ifset
952
953 @item
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
956
957 @item
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
960
961 @item
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
963 @ifset vms
964 in the GNU:[DOCS] directory,
965 @end ifset
966 for all details on the use of the GNU source-level debugger.
967
968 @item
969 @xref{Top,, The extensible self-documenting text editor, emacs,
970 GNU Emacs Manual},
971 @ifset vms
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
973 @end ifset
974 for full information on the extensible editor and programming
975 environment Emacs.
976
977 @end itemize
978
979 @c **************
980 @node Conventions
981 @unnumberedsec Conventions
982 @cindex Conventions
983 @cindex Typographical conventions
984
985 @noindent
986 Following are examples of the typographical and graphic conventions used
987 in this guide:
988
989 @itemize @bullet
990 @item
991 @code{Functions}, @command{utility program names}, @code{standard names},
992 and @code{classes}.
993
994 @item
995 @option{Option flags}
996
997 @item
998 @file{File names}, @samp{button names}, and @samp{field names}.
999
1000 @item
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1002 variables}.
1003
1004 @item
1005 @emph{Emphasis}.
1006
1007 @item
1008 @r{[}optional information or parameters@r{]}
1009
1010 @item
1011 Examples are described by text
1012 @smallexample
1013 and then shown this way.
1014 @end smallexample
1015 @end itemize
1016
1017 @noindent
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1024
1025 @ifset unw
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1030 @end ifset
1031
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1035
1036 @noindent
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1039 @ifset unw
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1050 @end ifset
1051
1052 @menu
1053 * Running GNAT::
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1057 @ifset vms
1058 * Editing with Emacs::
1059 @end ifset
1060 @ifclear vms
1061 * Introduction to GPS::
1062 @end ifclear
1063 @end menu
1064
1065 @node Running GNAT
1066 @section Running GNAT
1067
1068 @noindent
1069 Three steps are needed to create an executable file from an Ada source
1070 file:
1071
1072 @enumerate
1073 @item
1074 The source file(s) must be compiled.
1075 @item
1076 The file(s) must be bound using the GNAT binder.
1077 @item
1078 All appropriate object files must be linked to produce an executable.
1079 @end enumerate
1080
1081 @noindent
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1085
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1088
1089 @noindent
1090 Any text editor may be used to prepare an Ada program.
1091 (If @code{Emacs} is
1092 used, the optional Ada mode may be helpful in laying out the program.)
1093 The
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1097
1098 @smallexample @c ada
1099 @cartouche
1100 with Ada.Text_IO; use Ada.Text_IO;
1101 procedure Hello is
1102 begin
1103    Put_Line ("Hello WORLD!");
1104 end Hello;
1105 @end cartouche
1106 @end smallexample
1107
1108 @noindent
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1111 that each file
1112 contain a single compilation unit whose file name is the
1113 unit name,
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1124
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1127
1128 @smallexample
1129 $ gcc -c hello.adb
1130 @end smallexample
1131
1132 @noindent
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1138
1139 @ifclear vms
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1144 @end ifclear
1145
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1159
1160 @smallexample
1161 $ gnatbind hello
1162 $ gnatlink hello
1163 @end smallexample
1164
1165 @noindent
1166 A simpler method of carrying out these steps is to use
1167 @command{gnatmake},
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1174
1175 @smallexample
1176 $ gnatmake hello.adb
1177 @end smallexample
1178
1179 @noindent
1180 The result is an executable program called @file{hello}, which can be
1181 run by entering:
1182
1183 @smallexample
1184 $ ^hello^RUN HELLO^
1185 @end smallexample
1186
1187 @noindent
1188 assuming that the current directory is on the search path
1189 for executable programs.
1190
1191 @noindent
1192 and, if all has gone well, you will see
1193
1194 @smallexample
1195 Hello WORLD!
1196 @end smallexample
1197
1198 @noindent
1199 appear in response to this command.
1200
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1204
1205 @noindent
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1208
1209 @smallexample @c ada
1210 @cartouche
1211 @group
1212 package Greetings is
1213    procedure Hello;
1214    procedure Goodbye;
1215 end Greetings;
1216
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1219    procedure Hello is
1220    begin
1221       Put_Line ("Hello WORLD!");
1222    end Hello;
1223
1224    procedure Goodbye is
1225    begin
1226       Put_Line ("Goodbye WORLD!");
1227    end Goodbye;
1228 end Greetings;
1229 @end group
1230
1231 @group
1232 with Greetings;
1233 procedure Gmain is
1234 begin
1235    Greetings.Hello;
1236    Greetings.Goodbye;
1237 end Gmain;
1238 @end group
1239 @end cartouche
1240 @end smallexample
1241
1242 @noindent
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1245
1246 @table @file
1247 @item greetings.ads
1248 spec of package @code{Greetings}
1249
1250 @item greetings.adb
1251 body of package @code{Greetings}
1252
1253 @item gmain.adb
1254 body of main program
1255 @end table
1256
1257 @noindent
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1261
1262 @smallexample
1263 $ gcc -c gmain.adb
1264 $ gcc -c greetings.adb
1265 $ gnatbind gmain
1266 $ gnatlink gmain
1267 @end smallexample
1268
1269 @noindent
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1277
1278 @smallexample
1279 $ gcc -c greetings.ads -gnatc
1280 @end smallexample
1281
1282 @noindent
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1288
1289 @smallexample
1290 $ gnatmake gmain.adb
1291 @end smallexample
1292
1293 @noindent
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1295 more detail.
1296
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1300
1301 @noindent
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1311
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1321
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1324
1325 @smallexample
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1328 @end smallexample
1329
1330 @noindent
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1339
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1349
1350 @ifset vms
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1353 @cindex Emacs
1354
1355 @noindent
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1358
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1363
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1367
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1372 prompt.
1373
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1377 @end ifset
1378
1379 @ifclear vms
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1384 @noindent
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs.  This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1392
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1396 for a program.
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1401 startup menu).
1402
1403 @menu
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1406 @end menu
1407
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1410 @noindent
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1419
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1422 programs.
1423
1424 @enumerate
1425 @item @emph{Creating a project}
1426
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1429 radio buttons:
1430
1431 @itemize @bullet
1432 @item
1433 @code{Start with default project in directory}
1434
1435 @item
1436 @code{Create new project with wizard}
1437
1438 @item
1439 @code{Open existing project}
1440 @end itemize
1441
1442 @noindent
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear.  In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1465
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1470
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}.  This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1475
1476 @item @emph{Creating and saving the source file}
1477
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1480
1481 @itemize @bullet
1482 @item
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1485
1486 @item
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1490 @end itemize
1491
1492 @noindent
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1497
1498 @smallexample @c ada
1499 @group
1500 with Ada.Text_IO; use Ada.Text_IO;
1501 procedure Hello is
1502 begin
1503   Put_Line("Hello from GPS!");
1504 end Hello;
1505 @end group
1506 @end smallexample
1507
1508 @noindent
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1510 @file{hello.adb}.
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1513
1514 @item @emph{Updating the project file}
1515
1516 You need to add the new source file to the project.
1517 To do this, select
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1520 @code{Add} button.
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1523 Click @code{OK}.
1524
1525 @item @emph{Building and running the program}
1526
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1533 message.
1534
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1539
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1545 @end enumerate
1546
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1549 @noindent
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1552
1553 @enumerate
1554 @item @emph{Opening a project}
1555
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1558 earlier example.
1559
1560 @item @emph{Creating a source file}
1561
1562 Select @code{File}, then @code{New}, and type in the following program:
1563
1564 @smallexample @c ada
1565 @group
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568    Line : String (1..80);
1569    N    : Natural;
1570 begin
1571    Put_Line("Type a line of text at each prompt; an empty line to exit");
1572    loop
1573       Put(": ");
1574       Get_Line (Line, N);
1575       Put_Line (Line (1..N) );
1576       exit when N=0;
1577    end loop;
1578 end Example;
1579 @end group
1580 @end smallexample
1581
1582 @noindent
1583 Select @code{File}, then @code{Save as}, and enter the file name
1584 @file{example.adb}.
1585
1586 @item @emph{Updating the project file}
1587
1588 Add @code{Example} as a new main unit for the project:
1589 @enumerate a
1590 @item
1591 Select @code{Project}, then @code{Edit Project Properties}.
1592
1593 @item
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1596 click @code{Open}.
1597 You will see the file name appear in the list of main units
1598
1599 @item
1600 Click @code{OK}
1601 @end enumerate
1602
1603 @item @emph{Building/running the executable}
1604
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1607
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1611
1612 @item @emph{Debugging the program}
1613
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1616 a new project.
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1619
1620 @enumerate a
1621 @item @emph{Initializing}
1622
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1624
1625 @item @emph{Setting a breakpoint}
1626
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1633
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1636
1637 @item @emph{Starting program execution}
1638
1639 Select @code{Debug}, then @code{Run}.  When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1645
1646 @item @emph{Examining a variable}
1647
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1653
1654 @item @emph{Assigning a new value to a variable}
1655
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1659 @code{OK}.
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1664
1665 @item @emph{Single stepping}
1666
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1673
1674 @item @emph{Removing a breakpoint}
1675
1676 Toggle the breakpoint icon at line 10.
1677
1678 @item @emph{Resuming execution from a breakpoint}
1679
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1686 @end enumerate
1687 @end enumerate
1688 @end ifclear
1689
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1694
1695 @menu
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1706 @ifclear vms
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1709 @end ifclear
1710 * Comparison between GNAT and Conventional Ada Library Models::
1711 @ifset vms
1712 * Placement of temporary files::
1713 @end ifset
1714 @end menu
1715
1716 @noindent
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1727
1728 @node Source Representation
1729 @section Source Representation
1730 @cindex Latin-1
1731
1732 @noindent
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1739
1740 @table @code
1741 @item VT
1742 @findex VT
1743 Vertical tab, @code{16#0B#}
1744
1745 @item HT
1746 @findex HT
1747 Horizontal tab, @code{16#09#}
1748
1749 @item CR
1750 @findex CR
1751 Carriage return, @code{16#0D#}
1752
1753 @item LF
1754 @findex LF
1755 Line feed, @code{16#0A#}
1756
1757 @item FF
1758 @findex FF
1759 Form feed, @code{16#0C#}
1760 @end table
1761
1762 @noindent
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1768
1769 @cindex End of source file
1770 @cindex Source file, end
1771 @findex SUB
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1777
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1784
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1787
1788 @noindent
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1792 @menu
1793 * Latin-1::
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1796 @end menu
1797
1798 @node Latin-1
1799 @subsection Latin-1
1800 @cindex Latin-1
1801
1802 @noindent
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1809
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1817
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1820
1821 @noindent
1822 GNAT also supports several other 8-bit coding schemes:
1823
1824 @table @asis
1825 @item ISO 8859-2 (Latin-2)
1826 @cindex Latin-2
1827 @cindex ISO 8859-2
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-3 (Latin-3)
1832 @cindex Latin-3
1833 @cindex ISO 8859-3
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-4 (Latin-4)
1838 @cindex Latin-4
1839 @cindex ISO 8859-4
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-5 (Cyrillic)
1844 @cindex ISO 8859-5
1845 @cindex Cyrillic
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1848
1849 @item ISO 8859-15 (Latin-9)
1850 @cindex ISO 8859-15
1851 @cindex Latin-9
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1854
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1862
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1869
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1876
1877 @item No Upper-Half
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1880 @end table
1881
1882 @noindent
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1887
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1890
1891 @noindent
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1895
1896 @table @asis
1897
1898 @item Hex Coding
1899 In this encoding, a wide character is represented by the following five
1900 character sequence:
1901
1902 @smallexample
1903 ESC a b c d
1904 @end smallexample
1905
1906 @noindent
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1910 @code{16#A345#}.
1911 This scheme is compatible with use of the full Wide_Character set.
1912
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1920 external coding.
1921
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1925 @code{16#ab#} and
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1931
1932 @item EUC Coding
1933 @cindex EUC Coding
1934 A wide character is represented by a two-character sequence
1935 @code{16#ab#} and
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1940
1941 @item UTF-8 Coding
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1946 @smallexample
1947 @iftex
1948 @leftskip=.7cm
1949 @end iftex
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1953
1954 @end smallexample
1955
1956 @noindent
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1966 character sequence:
1967
1968 @smallexample
1969 [ " a b c d " ]
1970 @end smallexample
1971
1972 @noindent
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1979
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1983
1984 @end table
1985
1986 @noindent
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1990
1991 @node File Naming Rules
1992 @section File Naming Rules
1993
1994 @noindent
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
1999
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2002 @ifset vms
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2004 @end ifset
2005 @ifclear vms
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2007 @end ifclear
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2013 @ifset vms
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2015 @end ifset
2016 @ifclear vms
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2018 @end ifclear
2019 respectively.
2020
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2024
2025 @table @file
2026 @item main.ads
2027 Main (spec)
2028 @item main.adb
2029 Main (body)
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2034 @item func-spec.ads
2035 Func.Spec (child package spec)
2036 @item func-spec.adb
2037 Func.Spec (child package body)
2038 @item main-sub.adb
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2042 @end table
2043
2044 @noindent
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2052
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2061
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2069
2070 @node Using Other File Names
2071 @section Using Other File Names
2072 @cindex File names
2073
2074 @noindent
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2079 the files it needs.
2080
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2087
2088 @smallexample @c ada
2089 @cartouche
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091   Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093   Body_File_Name => "myutilst.ada");
2094 @end cartouche
2095 @end smallexample
2096
2097 @noindent
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2103
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2111
2112 @ifclear vms
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2119
2120 @smallexample
2121 $ gcc -c -x ada peculiar_file_name.sim
2122 @end smallexample
2123 @end ifclear
2124
2125 @noindent
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2130 be omitted.
2131
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2135 @cindex File names
2136
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2142
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2148
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151    Spec_File_Name  => FILE_NAME_PATTERN
2152  @r{[},Casing          => CASING_SPEC@r{]}
2153  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156    Body_File_Name  => FILE_NAME_PATTERN
2157  @r{[},Casing          => CASING_SPEC@r{]}
2158  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2159
2160 pragma Source_File_Name (
2161    Subunit_File_Name  => FILE_NAME_PATTERN
2162  @r{[},Casing             => CASING_SPEC@r{]}
2163  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2164
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2167 @end smallexample
2168
2169 @noindent
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2178
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2182 file name.
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2187
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2193
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2200
2201 The file name translation works in the following steps:
2202
2203 @itemize @bullet
2204
2205 @item
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2208
2209 @item
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2214
2215 @item
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2219
2220 @end itemize
2221
2222 @noindent
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2227 two pragmas appear:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231   (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233   (Body_File_Name => "*.2.ada");
2234 @end smallexample
2235
2236 @noindent
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2239
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2245 @end smallexample
2246
2247 @noindent
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2256
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259   (Spec_File_Name => "*_.ADA",
2260    Dot_Replacement => "__",
2261    Casing = Uppercase);
2262 pragma Source_File_Name
2263   (Body_File_Name => "*.ADA",
2264    Dot_Replacement => "__",
2265    Casing = Uppercase);
2266 pragma Source_File_Name
2267   (Subunit_File_Name => "*.SEP",
2268    Dot_Replacement => "__",
2269    Casing = Uppercase);
2270 @end smallexample
2271
2272 @node Generating Object Files
2273 @section Generating Object Files
2274
2275 @noindent
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2280
2281 @itemize @bullet
2282 @item
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2285
2286 @item
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2291
2292 @item
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2296
2297 @item
2298 @cindex Subunits
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2301 subunits.
2302
2303 @item
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2307
2308 @item
2309 @cindex Generics
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2315 @end itemize
2316
2317 @noindent
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2321 @file{.o} as usual.
2322
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2329
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2334
2335 @node Source Dependencies
2336 @section Source Dependencies
2337
2338 @noindent
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2343 recompiled.
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2346
2347 @itemize @bullet
2348 @item
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2354
2355 @item
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2358 unit.
2359
2360 @item
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2364
2365 @item
2366 @findex Inline
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2374
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates  inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2380
2381 When using a gcc-based back end (in practice this means using any version
2382 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2383 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2384 Historically front end inlining was more extensive than the gcc back end
2385 inlining, but that is no longer the case.
2386
2387 @item
2388 If an object file @file{O} depends on the proper body of a subunit through
2389 inlining or instantiation, it depends on the parent unit of the subunit.
2390 This means that any modification of the parent unit or one of its subunits
2391 affects the compilation of @file{O}.
2392
2393 @item
2394 The object file for a parent unit depends on all its subunit body files.
2395
2396 @item
2397 The previous two rules meant that for purposes of computing dependencies and
2398 recompilation, a body and all its subunits are treated as an indivisible whole.
2399
2400 @noindent
2401 These rules are applied transitively: if unit @code{A} @code{with}'s
2402 unit @code{B}, whose elaboration calls an inlined procedure in package
2403 @code{C}, the object file for unit @code{A} will depend on the body of
2404 @code{C}, in file @file{c.adb}.
2405
2406 The set of dependent files described by these rules includes all the
2407 files on which the unit is semantically dependent, as dictated by the
2408 Ada language standard. However, it is a superset of what the
2409 standard describes, because it includes generic, inline, and subunit
2410 dependencies.
2411
2412 An object file must be recreated by recompiling the corresponding source
2413 file if any of the source files on which it depends are modified. For
2414 example, if the @code{make} utility is used to control compilation,
2415 the rule for an Ada object file must mention all the source files on
2416 which the object file depends, according to the above definition.
2417 The determination of the necessary
2418 recompilations is done automatically when one uses @command{gnatmake}.
2419 @end itemize
2420
2421 @node The Ada Library Information Files
2422 @section The Ada Library Information Files
2423 @cindex Ada Library Information files
2424 @cindex @file{ALI} files
2425
2426 @noindent
2427 Each compilation actually generates two output files. The first of these
2428 is the normal object file that has a @file{.o} extension. The second is a
2429 text file containing full dependency information. It has the same
2430 name as the source file, but an @file{.ali} extension.
2431 This file is known as the Ada Library Information (@file{ALI}) file.
2432 The following information is contained in the @file{ALI} file.
2433
2434 @itemize @bullet
2435 @item
2436 Version information (indicates which version of GNAT was used to compile
2437 the unit(s) in question)
2438
2439 @item
2440 Main program information (including priority and time slice settings,
2441 as well as the wide character encoding used during compilation).
2442
2443 @item
2444 List of arguments used in the @command{gcc} command for the compilation
2445
2446 @item
2447 Attributes of the unit, including configuration pragmas used, an indication
2448 of whether the compilation was successful, exception model used etc.
2449
2450 @item
2451 A list of relevant restrictions applying to the unit (used for consistency)
2452 checking.
2453
2454 @item
2455 Categorization information (e.g.@: use of pragma @code{Pure}).
2456
2457 @item
2458 Information on all @code{with}'ed units, including presence of
2459 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460
2461 @item
2462 Information from any @code{Linker_Options} pragmas used in the unit
2463
2464 @item
2465 Information on the use of @code{Body_Version} or @code{Version}
2466 attributes in the unit.
2467
2468 @item
2469 Dependency information. This is a list of files, together with
2470 time stamp and checksum information. These are files on which
2471 the unit depends in the sense that recompilation is required
2472 if any of these units are modified.
2473
2474 @item
2475 Cross-reference data. Contains information on all entities referenced
2476 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2477 provide cross-reference information.
2478
2479 @end itemize
2480
2481 @noindent
2482 For a full detailed description of the format of the @file{ALI} file,
2483 see the source of the body of unit @code{Lib.Writ}, contained in file
2484 @file{lib-writ.adb} in the GNAT compiler sources.
2485
2486 @node Binding an Ada Program
2487 @section Binding an Ada Program
2488
2489 @noindent
2490 When using languages such as C and C++, once the source files have been
2491 compiled the only remaining step in building an executable program
2492 is linking the object modules together. This means that it is possible to
2493 link an inconsistent version of a program, in which two units have
2494 included different versions of the same header.
2495
2496 The rules of Ada do not permit such an inconsistent program to be built.
2497 For example, if two clients have different versions of the same package,
2498 it is illegal to build a program containing these two clients.
2499 These rules are enforced by the GNAT binder, which also determines an
2500 elaboration order consistent with the Ada rules.
2501
2502 The GNAT binder is run after all the object files for a program have
2503 been created. It is given the name of the main program unit, and from
2504 this it determines the set of units required by the program, by reading the
2505 corresponding ALI files. It generates error messages if the program is
2506 inconsistent or if no valid order of elaboration exists.
2507
2508 If no errors are detected, the binder produces a main program, in Ada by
2509 default, that contains calls to the elaboration procedures of those
2510 compilation unit that require them, followed by
2511 a call to the main program. This Ada program is compiled to generate the
2512 object file for the main program. The name of
2513 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2514 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 main program unit.
2516
2517 Finally, the linker is used to build the resulting executable program,
2518 using the object from the main program from the bind step as well as the
2519 object files for the Ada units of the program.
2520
2521 @node Mixed Language Programming
2522 @section Mixed Language Programming
2523 @cindex Mixed Language Programming
2524
2525 @noindent
2526 This section describes how to develop a mixed-language program,
2527 specifically one that comprises units in both Ada and C.
2528
2529 @menu
2530 * Interfacing to C::
2531 * Calling Conventions::
2532 @end menu
2533
2534 @node Interfacing to C
2535 @subsection Interfacing to C
2536 @noindent
2537 Interfacing Ada with a foreign language such as C involves using
2538 compiler directives to import and/or export entity definitions in each
2539 language---using @code{extern} statements in C, for instance, and the
2540 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2541 A full treatment of these topics is provided in Appendix B, section 1
2542 of the Ada Reference Manual.
2543
2544 There are two ways to build a program using GNAT that contains some Ada
2545 sources and some foreign language sources, depending on whether or not
2546 the main subprogram is written in Ada.  Here is a source example with
2547 the main subprogram in Ada:
2548
2549 @smallexample
2550 /* file1.c */
2551 #include <stdio.h>
2552
2553 void print_num (int num)
2554 @{
2555   printf ("num is %d.\n", num);
2556   return;
2557 @}
2558
2559 /* file2.c */
2560
2561 /* num_from_Ada is declared in my_main.adb */
2562 extern int num_from_Ada;
2563
2564 int get_num (void)
2565 @{
2566   return num_from_Ada;
2567 @}
2568 @end smallexample
2569
2570 @smallexample @c ada
2571 --  my_main.adb
2572 procedure My_Main is
2573
2574    --  Declare then export an Integer entity called num_from_Ada
2575    My_Num : Integer := 10;
2576    pragma Export (C, My_Num, "num_from_Ada");
2577
2578    --  Declare an Ada function spec for Get_Num, then use
2579    --  C function get_num for the implementation.
2580    function Get_Num return Integer;
2581    pragma Import (C, Get_Num, "get_num");
2582
2583    --  Declare an Ada procedure spec for Print_Num, then use
2584    --  C function print_num for the implementation.
2585    procedure Print_Num (Num : Integer);
2586    pragma Import (C, Print_Num, "print_num");
2587
2588 begin
2589    Print_Num (Get_Num);
2590 end My_Main;
2591 @end smallexample
2592
2593 @enumerate
2594 @item
2595 To build this example, first compile the foreign language files to
2596 generate object files:
2597 @smallexample
2598 ^gcc -c file1.c^gcc -c FILE1.C^
2599 ^gcc -c file2.c^gcc -c FILE2.C^
2600 @end smallexample
2601
2602 @item
2603 Then, compile the Ada units to produce a set of object files and ALI
2604 files:
2605 @smallexample
2606 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 @end smallexample
2608
2609 @item
2610 Run the Ada binder on the Ada main program:
2611 @smallexample
2612 gnatbind my_main.ali
2613 @end smallexample
2614
2615 @item
2616 Link the Ada main program, the Ada objects and the other language
2617 objects:
2618 @smallexample
2619 gnatlink my_main.ali file1.o file2.o
2620 @end smallexample
2621 @end enumerate
2622
2623 The last three steps can be grouped in a single command:
2624 @smallexample
2625 gnatmake my_main.adb -largs file1.o file2.o
2626 @end smallexample
2627
2628 @cindex Binder output file
2629 @noindent
2630 If the main program is in a language other than Ada, then you may have
2631 more than one entry point into the Ada subsystem. You must use a special
2632 binder option to generate callable routines that initialize and
2633 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2634 Calls to the initialization and finalization routines must be inserted
2635 in the main program, or some other appropriate point in the code. The
2636 call to initialize the Ada units must occur before the first Ada
2637 subprogram is called, and the call to finalize the Ada units must occur
2638 after the last Ada subprogram returns. The binder will place the
2639 initialization and finalization subprograms into the
2640 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2641 sources.  To illustrate, we have the following example:
2642
2643 @smallexample
2644 /* main.c */
2645 extern void adainit (void);
2646 extern void adafinal (void);
2647 extern int add (int, int);
2648 extern int sub (int, int);
2649
2650 int main (int argc, char *argv[])
2651 @{
2652   int a = 21, b = 7;
2653
2654   adainit();
2655
2656   /* Should print "21 + 7 = 28" */
2657   printf ("%d + %d = %d\n", a, b, add (a, b));
2658   /* Should print "21 - 7 = 14" */
2659   printf ("%d - %d = %d\n", a, b, sub (a, b));
2660
2661   adafinal();
2662 @}
2663 @end smallexample
2664
2665 @smallexample @c ada
2666 --  unit1.ads
2667 package Unit1 is
2668    function Add (A, B : Integer) return Integer;
2669    pragma Export (C, Add, "add");
2670 end Unit1;
2671
2672 --  unit1.adb
2673 package body Unit1 is
2674    function Add (A, B : Integer) return Integer is
2675    begin
2676       return A + B;
2677    end Add;
2678 end Unit1;
2679
2680 --  unit2.ads
2681 package Unit2 is
2682    function Sub (A, B : Integer) return Integer;
2683    pragma Export (C, Sub, "sub");
2684 end Unit2;
2685
2686 --  unit2.adb
2687 package body Unit2 is
2688    function Sub (A, B : Integer) return Integer is
2689    begin
2690       return A - B;
2691    end Sub;
2692 end Unit2;
2693 @end smallexample
2694
2695 @enumerate
2696 @item
2697 The build procedure for this application is similar to the last
2698 example's.  First, compile the foreign language files to generate object
2699 files:
2700 @smallexample
2701 ^gcc -c main.c^gcc -c main.c^
2702 @end smallexample
2703
2704 @item
2705 Next, compile the Ada units to produce a set of object files and ALI
2706 files:
2707 @smallexample
2708 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 @end smallexample
2711
2712 @item
2713 Run the Ada binder on every generated ALI file.  Make sure to use the
2714 @option{-n} option to specify a foreign main program:
2715 @smallexample
2716 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 @end smallexample
2718
2719 @item
2720 Link the Ada main program, the Ada objects and the foreign language
2721 objects. You need only list the last ALI file here:
2722 @smallexample
2723 gnatlink unit2.ali main.o -o exec_file
2724 @end smallexample
2725
2726 This procedure yields a binary executable called @file{exec_file}.
2727 @end enumerate
2728
2729 @noindent
2730 Depending on the circumstances (for example when your non-Ada main object
2731 does not provide symbol @code{main}), you may also need to instruct the
2732 GNAT linker not to include the standard startup objects by passing the
2733 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2734
2735 @node Calling Conventions
2736 @subsection Calling Conventions
2737 @cindex Foreign Languages
2738 @cindex Calling Conventions
2739 GNAT follows standard calling sequence conventions and will thus interface
2740 to any other language that also follows these conventions. The following
2741 Convention identifiers are recognized by GNAT:
2742
2743 @table @code
2744 @cindex Interfacing to Ada
2745 @cindex Other Ada compilers
2746 @cindex Convention Ada
2747 @item Ada
2748 This indicates that the standard Ada calling sequence will be
2749 used and all Ada data items may be passed without any limitations in the
2750 case where GNAT is used to generate both the caller and callee. It is also
2751 possible to mix GNAT generated code and code generated by another Ada
2752 compiler. In this case, the data types should be restricted to simple
2753 cases, including primitive types. Whether complex data types can be passed
2754 depends on the situation. Probably it is safe to pass simple arrays, such
2755 as arrays of integers or floats. Records may or may not work, depending
2756 on whether both compilers lay them out identically. Complex structures
2757 involving variant records, access parameters, tasks, or protected types,
2758 are unlikely to be able to be passed.
2759
2760 Note that in the case of GNAT running
2761 on a platform that supports HP Ada 83, a higher degree of compatibility
2762 can be guaranteed, and in particular records are layed out in an identical
2763 manner in the two compilers. Note also that if output from two different
2764 compilers is mixed, the program is responsible for dealing with elaboration
2765 issues. Probably the safest approach is to write the main program in the
2766 version of Ada other than GNAT, so that it takes care of its own elaboration
2767 requirements, and then call the GNAT-generated adainit procedure to ensure
2768 elaboration of the GNAT components. Consult the documentation of the other
2769 Ada compiler for further details on elaboration.
2770
2771 However, it is not possible to mix the tasking run time of GNAT and
2772 HP Ada 83, All the tasking operations must either be entirely within
2773 GNAT compiled sections of the program, or entirely within HP Ada 83
2774 compiled sections of the program.
2775
2776 @cindex Interfacing to Assembly
2777 @cindex Convention Assembler
2778 @item Assembler
2779 Specifies assembler as the convention. In practice this has the
2780 same effect as convention Ada (but is not equivalent in the sense of being
2781 considered the same convention).
2782
2783 @cindex Convention Asm
2784 @findex Asm
2785 @item Asm
2786 Equivalent to Assembler.
2787
2788 @cindex Interfacing to COBOL
2789 @cindex Convention COBOL
2790 @findex COBOL
2791 @item COBOL
2792 Data will be passed according to the conventions described
2793 in section B.4 of the Ada Reference Manual.
2794
2795 @findex C
2796 @cindex Interfacing to C
2797 @cindex Convention C
2798 @item C
2799 Data will be passed according to the conventions described
2800 in section B.3 of the Ada Reference Manual.
2801
2802 A note on interfacing to a C ``varargs'' function:
2803 @findex C varargs function
2804 @cindex Interfacing to C varargs function
2805 @cindex varargs function interfaces
2806
2807 @itemize @bullet
2808 @item
2809 In C, @code{varargs} allows a function to take a variable number of
2810 arguments. There is no direct equivalent in this to Ada. One
2811 approach that can be used is to create a C wrapper for each
2812 different profile and then interface to this C wrapper. For
2813 example, to print an @code{int} value using @code{printf},
2814 create a C function @code{printfi} that takes two arguments, a
2815 pointer to a string and an int, and calls @code{printf}.
2816 Then in the Ada program, use pragma @code{Import} to
2817 interface to @code{printfi}.
2818
2819 @item
2820 It may work on some platforms to directly interface to
2821 a @code{varargs} function by providing a specific Ada profile
2822 for a particular call. However, this does not work on
2823 all platforms, since there is no guarantee that the
2824 calling sequence for a two argument normal C function
2825 is the same as for calling a @code{varargs} C function with
2826 the same two arguments.
2827 @end itemize
2828
2829 @cindex Convention Default
2830 @findex Default
2831 @item Default
2832 Equivalent to C.
2833
2834 @cindex Convention External
2835 @findex External
2836 @item External
2837 Equivalent to C.
2838
2839 @ifclear vms
2840 @findex C++
2841 @cindex Interfacing to C++
2842 @cindex Convention C++
2843 @item C_Plus_Plus (or CPP)
2844 This stands for C++. For most purposes this is identical to C.
2845 See the separate description of the specialized GNAT pragmas relating to
2846 C++ interfacing for further details.
2847 @end ifclear
2848
2849 @findex Fortran
2850 @cindex Interfacing to Fortran
2851 @cindex Convention Fortran
2852 @item Fortran
2853 Data will be passed according to the conventions described
2854 in section B.5 of the Ada Reference Manual.
2855
2856 @item Intrinsic
2857 This applies to an intrinsic operation, as defined in the Ada
2858 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2859 this means that the body of the subprogram is provided by the compiler itself,
2860 usually by means of an efficient code sequence, and that the user does not
2861 supply an explicit body for it. In an application program, the pragma may
2862 be applied to the following sets of names:
2863
2864 @itemize @bullet
2865 @item
2866 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2867 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2868 two formal parameters. The
2869 first one must be a signed integer type or a modular type with a binary
2870 modulus, and the second parameter must be of type Natural.
2871 The return type must be the same as the type of the first argument. The size
2872 of this type can only be 8, 16, 32, or 64.
2873
2874 @item
2875 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2876 The corresponding operator declaration must have parameters and result type
2877 that have the same root numeric type (for example, all three are long_float
2878 types). This simplifies the definition of operations that use type checking
2879 to perform dimensional checks:
2880
2881 @smallexample @c ada
2882 type Distance is new Long_Float;
2883 type Time     is new Long_Float;
2884 type Velocity is new Long_Float;
2885 function "/" (D : Distance; T : Time)
2886   return Velocity;
2887 pragma Import (Intrinsic, "/");
2888 @end smallexample
2889
2890 @noindent
2891 This common idiom is often programmed with a generic definition and an
2892 explicit body. The pragma makes it simpler to introduce such declarations.
2893 It incurs no overhead in compilation time or code size, because it is
2894 implemented as a single machine instruction.
2895
2896 @item
2897 General subprogram entities, to bind an Ada subprogram declaration to
2898 a compiler builtin by name with back-ends where such interfaces are
2899 available. A typical example is the set of ``__builtin'' functions
2900 exposed by the GCC back-end, as in the following example:
2901
2902 @smallexample @c ada
2903    function builtin_sqrt (F : Float) return Float;
2904    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 @end smallexample
2906
2907 Most of the GCC builtins are accessible this way, and as for other
2908 import conventions (e.g. C), it is the user's responsibility to ensure
2909 that the Ada subprogram profile matches the underlying builtin
2910 expectations.
2911 @end itemize
2912
2913 @noindent
2914
2915 @ifset unw
2916 @findex Stdcall
2917 @cindex Convention Stdcall
2918 @item Stdcall
2919 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2920 and specifies that the @code{Stdcall} calling sequence will be used,
2921 as defined by the NT API. Nevertheless, to ease building
2922 cross-platform bindings this convention will be handled as a @code{C} calling
2923 convention on non-Windows platforms.
2924
2925 @findex DLL
2926 @cindex Convention DLL
2927 @item DLL
2928 This is equivalent to @code{Stdcall}.
2929
2930 @findex Win32
2931 @cindex Convention Win32
2932 @item Win32
2933 This is equivalent to @code{Stdcall}.
2934 @end ifset
2935
2936 @findex Stubbed
2937 @cindex Convention Stubbed
2938 @item Stubbed
2939 This is a special convention that indicates that the compiler
2940 should provide a stub body that raises @code{Program_Error}.
2941 @end table
2942
2943 @noindent
2944 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2945 that can be used to parametrize conventions and allow additional synonyms
2946 to be specified. For example if you have legacy code in which the convention
2947 identifier Fortran77 was used for Fortran, you can use the configuration
2948 pragma:
2949
2950 @smallexample @c ada
2951 pragma Convention_Identifier (Fortran77, Fortran);
2952 @end smallexample
2953
2954 @noindent
2955 And from now on the identifier Fortran77 may be used as a convention
2956 identifier (for example in an @code{Import} pragma) with the same
2957 meaning as Fortran.
2958
2959 @ifclear vms
2960 @node Building Mixed Ada & C++ Programs
2961 @section Building Mixed Ada and C++ Programs
2962
2963 @noindent
2964 A programmer inexperienced with mixed-language development may find that
2965 building an application containing both Ada and C++ code can be a
2966 challenge.  This section gives a few
2967 hints that should make this task easier. The first section addresses
2968 the differences between interfacing with C and interfacing with C++.
2969 The second section
2970 looks into the delicate problem of linking the complete application from
2971 its Ada and C++ parts. The last section gives some hints on how the GNAT
2972 run-time library can be adapted in order to allow inter-language dispatching
2973 with a new C++ compiler.
2974
2975 @menu
2976 * Interfacing to C++::
2977 * Linking a Mixed C++ & Ada Program::
2978 * A Simple Example::
2979 * Interfacing with C++ constructors::
2980 * Interfacing with C++ at the Class Level::
2981 @end menu
2982
2983 @node Interfacing to C++
2984 @subsection Interfacing to C++
2985
2986 @noindent
2987 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2988 generating code that is compatible with the G++ Application Binary
2989 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2990
2991 @noindent
2992 Interfacing can be done at 3 levels: simple data, subprograms, and
2993 classes. In the first two cases, GNAT offers a specific @code{Convention
2994 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2995 Usually, C++ mangles the names of subprograms. To generate proper mangled
2996 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2997 This problem can also be addressed manually in two ways:
2998
2999 @itemize @bullet
3000 @item
3001 by modifying the C++ code in order to force a C convention using
3002 the @code{extern "C"} syntax.
3003
3004 @item
3005 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3006 Link_Name argument of the pragma import.
3007 @end itemize
3008
3009 @noindent
3010 Interfacing at the class level can be achieved by using the GNAT specific
3011 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3012 gnat_rm, GNAT Reference Manual}, for additional information.
3013
3014 @node Linking a Mixed C++ & Ada Program
3015 @subsection Linking a Mixed C++ & Ada Program
3016
3017 @noindent
3018 Usually the linker of the C++ development system must be used to link
3019 mixed applications because most C++ systems will resolve elaboration
3020 issues (such as calling constructors on global class instances)
3021 transparently during the link phase. GNAT has been adapted to ease the
3022 use of a foreign linker for the last phase. Three cases can be
3023 considered:
3024 @enumerate
3025
3026 @item
3027 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3028 The C++ linker can simply be called by using the C++ specific driver
3029 called @code{g++}.
3030
3031 Note that if the C++ code uses inline functions, you will need to
3032 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3033 order to provide an existing function implementation that the Ada code can
3034 link with.
3035
3036 @smallexample
3037 $ g++ -c -fkeep-inline-functions file1.C
3038 $ g++ -c -fkeep-inline-functions file2.C
3039 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3040 @end smallexample
3041
3042 @item
3043 Using GNAT and G++ from two different GCC installations: If both
3044 compilers are on the @env{PATH}, the previous method may be used. It is
3045 important to note that environment variables such as
3046 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3047 @env{GCC_ROOT} will affect both compilers
3048 at the same time and may make one of the two compilers operate
3049 improperly if set during invocation of the wrong compiler.  It is also
3050 very important that the linker uses the proper @file{libgcc.a} GCC
3051 library -- that is, the one from the C++ compiler installation. The
3052 implicit link command as suggested in the @command{gnatmake} command
3053 from the former example can be replaced by an explicit link command with
3054 the full-verbosity option in order to verify which library is used:
3055 @smallexample
3056 $ gnatbind ada_unit
3057 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3058 @end smallexample
3059 If there is a problem due to interfering environment variables, it can
3060 be worked around by using an intermediate script. The following example
3061 shows the proper script to use when GNAT has not been installed at its
3062 default location and g++ has been installed at its default location:
3063
3064 @smallexample
3065 $ cat ./my_script
3066 #!/bin/sh
3067 unset BINUTILS_ROOT
3068 unset GCC_ROOT
3069 c++ $*
3070 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3071 @end smallexample
3072
3073 @item
3074 Using a non-GNU C++ compiler: The commands previously described can be
3075 used to insure that the C++ linker is used. Nonetheless, you need to add
3076 a few more parameters to the link command line, depending on the exception
3077 mechanism used.
3078
3079 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3080 to the libgcc libraries are required:
3081
3082 @smallexample
3083 $ cat ./my_script
3084 #!/bin/sh
3085 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3086 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3087 @end smallexample
3088
3089 Where CC is the name of the non-GNU C++ compiler.
3090
3091 If the @code{zero cost} exception mechanism is used, and the platform
3092 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3093 paths to more objects are required:
3094
3095 @smallexample
3096 $ cat ./my_script
3097 #!/bin/sh
3098 CC `gcc -print-file-name=crtbegin.o` $* \
3099 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3100 `gcc -print-file-name=crtend.o`
3101 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3102 @end smallexample
3103
3104 If the @code{zero cost} exception mechanism is used, and the platform
3105 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3106 Tru64 or AIX), the simple approach described above will not work and
3107 a pre-linking phase using GNAT will be necessary.
3108
3109 @end enumerate
3110
3111 Another alternative is to use the @command{gprbuild} multi-language builder
3112 which has a large knowledge base and knows how to link Ada and C++ code
3113 together automatically in most cases.
3114
3115 @node A Simple Example
3116 @subsection  A Simple Example
3117 @noindent
3118 The following example, provided as part of the GNAT examples, shows how
3119 to achieve procedural interfacing between Ada and C++ in both
3120 directions. The C++ class A has two methods. The first method is exported
3121 to Ada by the means of an extern C wrapper function. The second method
3122 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3123 a limited record with a layout comparable to the C++ class. The Ada
3124 subprogram, in turn, calls the C++ method. So, starting from the C++
3125 main program, the process passes back and forth between the two
3126 languages.
3127
3128 @noindent
3129 Here are the compilation commands:
3130 @smallexample
3131 $ gnatmake -c simple_cpp_interface
3132 $ g++ -c cpp_main.C
3133 $ g++ -c ex7.C
3134 $ gnatbind -n simple_cpp_interface
3135 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3136       -lstdc++ ex7.o cpp_main.o
3137 @end smallexample
3138
3139 @noindent
3140 Here are the corresponding sources:
3141 @smallexample
3142
3143 //cpp_main.C
3144
3145 #include "ex7.h"
3146
3147 extern "C" @{
3148   void adainit (void);
3149   void adafinal (void);
3150   void method1 (A *t);
3151 @}
3152
3153 void method1 (A *t)
3154 @{
3155   t->method1 ();
3156 @}
3157
3158 int main ()
3159 @{
3160   A obj;
3161   adainit ();
3162   obj.method2 (3030);
3163   adafinal ();
3164 @}
3165
3166 //ex7.h
3167
3168 class Origin @{
3169  public:
3170   int o_value;
3171 @};
3172 class A : public Origin @{
3173  public:
3174   void method1 (void);
3175   void method2 (int v);
3176   A();
3177   int   a_value;
3178 @};
3179
3180 //ex7.C
3181
3182 #include "ex7.h"
3183 #include <stdio.h>
3184
3185 extern "C" @{ void ada_method2 (A *t, int v);@}
3186
3187 void A::method1 (void)
3188 @{
3189   a_value = 2020;
3190   printf ("in A::method1, a_value = %d \n",a_value);
3191
3192 @}
3193
3194 void A::method2 (int v)
3195 @{
3196    ada_method2 (this, v);
3197    printf ("in A::method2, a_value = %d \n",a_value);
3198
3199 @}
3200
3201 A::A(void)
3202 @{
3203    a_value = 1010;
3204   printf ("in A::A, a_value = %d \n",a_value);
3205 @}
3206 @end smallexample
3207
3208 @smallexample @c ada
3209 -- Ada sources
3210 package body Simple_Cpp_Interface is
3211
3212    procedure Ada_Method2 (This : in out A; V : Integer) is
3213    begin
3214       Method1 (This);
3215       This.A_Value := V;
3216    end Ada_Method2;
3217
3218 end Simple_Cpp_Interface;
3219
3220 with System;
3221 package Simple_Cpp_Interface is
3222    type A is limited
3223       record
3224          Vptr    : System.Address;
3225          O_Value : Integer;
3226          A_Value : Integer;
3227       end record;
3228    pragma Convention (C, A);
3229
3230    procedure Method1 (This : in out A);
3231    pragma Import (C, Method1);
3232
3233    procedure Ada_Method2 (This : in out A; V : Integer);
3234    pragma Export (C, Ada_Method2);
3235
3236 end Simple_Cpp_Interface;
3237 @end smallexample
3238
3239 @node Interfacing with C++ constructors
3240 @subsection Interfacing with C++ constructors
3241 @noindent
3242
3243 In order to interface with C++ constructors GNAT provides the
3244 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3245 gnat_rm, GNAT Reference Manual}, for additional information).
3246 In this section we present some common uses of C++ constructors
3247 in mixed-languages programs in GNAT.
3248
3249 Let us assume that we need to interface with the following
3250 C++ class:
3251
3252 @smallexample
3253 @b{class} Root @{
3254 @b{public}:
3255   int  a_value;
3256   int  b_value;
3257   @b{virtual} int Get_Value ();
3258   Root();              // Default constructor
3259   Root(int v);         // 1st non-default constructor
3260   Root(int v, int w);  // 2nd non-default constructor
3261 @};
3262 @end smallexample
3263
3264 For this purpose we can write the following package spec (further
3265 information on how to build this spec is available in
3266 @ref{Interfacing with C++ at the Class Level} and
3267 @ref{Generating Ada Bindings for C and C++ headers}).
3268
3269 @smallexample @c ada
3270 with Interfaces.C; use Interfaces.C;
3271 package Pkg_Root is
3272   type Root is tagged limited record
3273      A_Value : int;
3274      B_Value : int;
3275   end record;
3276   pragma Import (CPP, Root);
3277
3278   function Get_Value (Obj : Root) return int;
3279   pragma Import (CPP, Get_Value);
3280
3281   function Constructor return Root;
3282   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3283
3284   function Constructor (v : Integer) return Root;
3285   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3286
3287   function Constructor (v, w : Integer) return Root;
3288   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3289 end Pkg_Root;
3290 @end smallexample
3291
3292 On the Ada side the constructor is represented by a function (whose
3293 name is arbitrary) that returns the classwide type corresponding to
3294 the imported C++ class. Although the constructor is described as a
3295 function, it is typically a procedure with an extra implicit argument
3296 (the object being initialized) at the implementation level. GNAT
3297 issues the appropriate call, whatever it is, to get the object
3298 properly initialized.
3299
3300 Constructors can only appear in the following contexts:
3301
3302 @itemize @bullet
3303 @item
3304 On the right side of an initialization of an object of type @var{T}.
3305 @item
3306 On the right side of an initialization of a record component of type @var{T}.
3307 @item
3308 In an Ada 2005 limited aggregate.
3309 @item
3310 In an Ada 2005 nested limited aggregate.
3311 @item
3312 In an Ada 2005 limited aggregate that initializes an object built in
3313 place by an extended return statement.
3314 @end itemize
3315
3316 @noindent
3317 In a declaration of an object whose type is a class imported from C++,
3318 either the default C++ constructor is implicitly called by GNAT, or
3319 else the required C++ constructor must be explicitly called in the
3320 expression that initializes the object. For example:
3321
3322 @smallexample @c ada
3323   Obj1 : Root;
3324   Obj2 : Root := Constructor;
3325   Obj3 : Root := Constructor (v => 10);
3326   Obj4 : Root := Constructor (30, 40);
3327 @end smallexample
3328
3329 The first two declarations are equivalent: in both cases the default C++
3330 constructor is invoked (in the former case the call to the constructor is
3331 implicit, and in the latter case the call is explicit in the object
3332 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3333 that takes an integer argument, and @code{Obj4} is initialized by the
3334 non-default C++ constructor that takes two integers.
3335
3336 Let us derive the imported C++ class in the Ada side. For example:
3337
3338 @smallexample @c ada
3339   type DT is new Root with record
3340      C_Value : Natural := 2009;
3341   end record;
3342 @end smallexample
3343
3344 In this case the components DT inherited from the C++ side must be
3345 initialized by a C++ constructor, and the additional Ada components
3346 of type DT are initialized by GNAT. The initialization of such an
3347 object is done either by default, or by means of a function returning
3348 an aggregate of type DT, or by means of an extension aggregate.
3349
3350 @smallexample @c ada
3351   Obj5 : DT;
3352   Obj6 : DT := Function_Returning_DT (50);
3353   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3354 @end smallexample
3355
3356 The declaration of @code{Obj5} invokes the default constructors: the
3357 C++ default constructor of the parent type takes care of the initialization
3358 of the components inherited from Root, and GNAT takes care of the default
3359 initialization of the additional Ada components of type DT (that is,
3360 @code{C_Value} is initialized to value 2009). The order of invocation of
3361 the constructors is consistent with the order of elaboration required by
3362 Ada and C++. That is, the constructor of the parent type is always called
3363 before the constructor of the derived type.
3364
3365 Let us now consider a record that has components whose type is imported
3366 from C++. For example:
3367
3368 @smallexample @c ada
3369   type Rec1 is limited record
3370      Data1 : Root := Constructor (10);
3371      Value : Natural := 1000;
3372   end record;
3373
3374   type Rec2 (D : Integer := 20) is limited record
3375      Rec   : Rec1;
3376      Data2 : Root := Constructor (D, 30);
3377   end record;
3378 @end smallexample
3379
3380 The initialization of an object of type @code{Rec2} will call the
3381 non-default C++ constructors specified for the imported components.
3382 For example:
3383
3384 @smallexample @c ada
3385   Obj8 : Rec2 (40);
3386 @end smallexample
3387
3388 Using Ada 2005 we can use limited aggregates to initialize an object
3389 invoking C++ constructors that differ from those specified in the type
3390 declarations. For example:
3391
3392 @smallexample @c ada
3393   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3394                           others => <>),
3395                   others => <>);
3396 @end smallexample
3397
3398 The above declaration uses an Ada 2005 limited aggregate to
3399 initialize @code{Obj9}, and the C++ constructor that has two integer
3400 arguments is invoked to initialize the @code{Data1} component instead
3401 of the constructor specified in the declaration of type @code{Rec1}. In
3402 Ada 2005 the box in the aggregate indicates that unspecified components
3403 are initialized using the expression (if any) available in the component
3404 declaration. That is, in this case discriminant @code{D} is initialized
3405 to value @code{20}, @code{Value} is initialized to value 1000, and the
3406 non-default C++ constructor that handles two integers takes care of
3407 initializing component @code{Data2} with values @code{20,30}.
3408
3409 In Ada 2005 we can use the extended return statement to build the Ada
3410 equivalent to C++ non-default constructors. For example:
3411
3412 @smallexample @c ada
3413   function Constructor (V : Integer) return Rec2 is
3414   begin
3415      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3416                                    others => <>),
3417                            others => <>) do
3418         --  Further actions required for construction of
3419         --  objects of type Rec2
3420         ...
3421      end record;
3422   end Constructor;
3423 @end smallexample
3424
3425 In this example the extended return statement construct is used to
3426 build in place the returned object whose components are initialized
3427 by means of a limited aggregate. Any further action associated with
3428 the constructor can be placed inside the construct.
3429
3430 @node Interfacing with C++ at the Class Level
3431 @subsection Interfacing with C++ at the Class Level
3432 @noindent
3433 In this section we demonstrate the GNAT features for interfacing with
3434 C++ by means of an example making use of Ada 2005 abstract interface
3435 types. This example consists of a classification of animals; classes
3436 have been used to model our main classification of animals, and
3437 interfaces provide support for the management of secondary
3438 classifications. We first demonstrate a case in which the types and
3439 constructors are defined on the C++ side and imported from the Ada
3440 side, and latter the reverse case.
3441
3442 The root of our derivation will be the @code{Animal} class, with a
3443 single private attribute (the @code{Age} of the animal) and two public
3444 primitives to set and get the value of this attribute.
3445
3446 @smallexample
3447 @b{class} Animal @{
3448  @b{public}:
3449    @b{virtual} void Set_Age (int New_Age);
3450    @b{virtual} int Age ();
3451  @b{private}:
3452    int Age_Count;
3453 @};
3454 @end smallexample
3455
3456 Abstract interface types are defined in C++ by means of classes with pure
3457 virtual functions and no data members. In our example we will use two
3458 interfaces that provide support for the common management of @code{Carnivore}
3459 and @code{Domestic} animals:
3460
3461 @smallexample
3462 @b{class} Carnivore @{
3463 @b{public}:
3464    @b{virtual} int Number_Of_Teeth () = 0;
3465 @};
3466
3467 @b{class} Domestic @{
3468 @b{public}:
3469    @b{virtual void} Set_Owner (char* Name) = 0;
3470 @};
3471 @end smallexample
3472
3473 Using these declarations, we can now say that a @code{Dog} is an animal that is
3474 both Carnivore and Domestic, that is:
3475
3476 @smallexample
3477 @b{class} Dog : Animal, Carnivore, Domestic @{
3478  @b{public}:
3479    @b{virtual} int  Number_Of_Teeth ();
3480    @b{virtual} void Set_Owner (char* Name);
3481
3482    Dog(); // Constructor
3483  @b{private}:
3484    int  Tooth_Count;
3485    char *Owner;
3486 @};
3487 @end smallexample
3488
3489 In the following examples we will assume that the previous declarations are
3490 located in a file named @code{animals.h}. The following package demonstrates
3491 how to import these C++ declarations from the Ada side:
3492
3493 @smallexample @c ada
3494 with Interfaces.C.Strings; use Interfaces.C.Strings;
3495 package Animals is
3496   type Carnivore is interface;
3497   pragma Convention (C_Plus_Plus, Carnivore);
3498   function Number_Of_Teeth (X : Carnivore)
3499      return Natural is abstract;
3500
3501   type Domestic is interface;
3502   pragma Convention (C_Plus_Plus, Set_Owner);
3503   procedure Set_Owner
3504     (X    : in out Domestic;
3505      Name : Chars_Ptr) is abstract;
3506
3507   type Animal is tagged record
3508     Age : Natural := 0;
3509   end record;
3510   pragma Import (C_Plus_Plus, Animal);
3511
3512   procedure Set_Age (X : in out Animal; Age : Integer);
3513   pragma Import (C_Plus_Plus, Set_Age);
3514
3515   function Age (X : Animal) return Integer;
3516   pragma Import (C_Plus_Plus, Age);
3517
3518   type Dog is new Animal and Carnivore and Domestic with record
3519     Tooth_Count : Natural;
3520     Owner       : String (1 .. 30);
3521   end record;
3522   pragma Import (C_Plus_Plus, Dog);
3523
3524   function Number_Of_Teeth (A : Dog) return Integer;
3525   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3526
3527   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3528   pragma Import (C_Plus_Plus, Set_Owner);
3529
3530   function New_Dog return Dog;
3531   pragma CPP_Constructor (New_Dog);
3532   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3533 end Animals;
3534 @end smallexample
3535
3536 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3537 interfacing with these C++ classes is easy. The only requirement is that all
3538 the primitives and components must be declared exactly in the same order in
3539 the two languages.
3540
3541 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3542 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3543 the arguments to the called primitives will be the same as for C++. For the
3544 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3545 to indicate that they have been defined on the C++ side; this is required
3546 because the dispatch table associated with these tagged types will be built
3547 in the C++ side and therefore will not contain the predefined Ada primitives
3548 which Ada would otherwise expect.
3549
3550 As the reader can see there is no need to indicate the C++ mangled names
3551 associated with each subprogram because it is assumed that all the calls to
3552 these primitives will be dispatching calls. The only exception is the
3553 constructor, which must be registered with the compiler by means of
3554 @code{pragma CPP_Constructor} and needs to provide its associated C++
3555 mangled name because the Ada compiler generates direct calls to it.
3556
3557 With the above packages we can now declare objects of type Dog on the Ada side
3558 and dispatch calls to the corresponding subprograms on the C++ side. We can
3559 also extend the tagged type Dog with further fields and primitives, and
3560 override some of its C++ primitives on the Ada side. For example, here we have
3561 a type derivation defined on the Ada side that inherits all the dispatching
3562 primitives of the ancestor from the C++ side.
3563
3564 @smallexample
3565 @b{with} Animals; @b{use} Animals;
3566 @b{package} Vaccinated_Animals @b{is}
3567   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3568   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3569 @b{end} Vaccinated_Animals;
3570 @end smallexample
3571
3572 It is important to note that, because of the ABI compatibility, the programmer
3573 does not need to add any further information to indicate either the object
3574 layout or the dispatch table entry associated with each dispatching operation.
3575
3576 Now let us define all the types and constructors on the Ada side and export
3577 them to C++, using the same hierarchy of our previous example:
3578
3579 @smallexample @c ada
3580 with Interfaces.C.Strings;
3581 use Interfaces.C.Strings;
3582 package Animals is
3583   type Carnivore is interface;
3584   pragma Convention (C_Plus_Plus, Carnivore);
3585   function Number_Of_Teeth (X : Carnivore)
3586      return Natural is abstract;
3587
3588   type Domestic is interface;
3589   pragma Convention (C_Plus_Plus, Set_Owner);
3590   procedure Set_Owner
3591     (X    : in out Domestic;
3592      Name : Chars_Ptr) is abstract;
3593
3594   type Animal is tagged record
3595     Age : Natural := 0;
3596   end record;
3597   pragma Convention (C_Plus_Plus, Animal);
3598
3599   procedure Set_Age (X : in out Animal; Age : Integer);
3600   pragma Export (C_Plus_Plus, Set_Age);
3601
3602   function Age (X : Animal) return Integer;
3603   pragma Export (C_Plus_Plus, Age);
3604
3605   type Dog is new Animal and Carnivore and Domestic with record
3606     Tooth_Count : Natural;
3607     Owner       : String (1 .. 30);
3608   end record;
3609   pragma Convention (C_Plus_Plus, Dog);
3610
3611   function Number_Of_Teeth (A : Dog) return Integer;
3612   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3613
3614   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3615   pragma Export (C_Plus_Plus, Set_Owner);
3616
3617   function New_Dog return Dog'Class;
3618   pragma Export (C_Plus_Plus, New_Dog);
3619 end Animals;
3620 @end smallexample
3621
3622 Compared with our previous example the only difference is the use of
3623 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3624 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3625 nothing else to be done; as explained above, the only requirement is that all
3626 the primitives and components are declared in exactly the same order.
3627
3628 For completeness, let us see a brief C++ main program that uses the
3629 declarations available in @code{animals.h} (presented in our first example) to
3630 import and use the declarations from the Ada side, properly initializing and
3631 finalizing the Ada run-time system along the way:
3632
3633 @smallexample
3634 @b{#include} "animals.h"
3635 @b{#include} <iostream>
3636 @b{using namespace} std;
3637
3638 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3639 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3640 void Check_Animal (Animal *obj)       @{@dots{}@}
3641 void Check_Dog (Dog *obj)             @{@dots{}@}
3642
3643 @b{extern} "C" @{
3644   void adainit (void);
3645   void adafinal (void);
3646   Dog* new_dog ();
3647 @}
3648
3649 void test ()
3650 @{
3651   Dog *obj = new_dog();  // Ada constructor
3652   Check_Carnivore (obj); // Check secondary DT
3653   Check_Domestic (obj);  // Check secondary DT
3654   Check_Animal (obj);    // Check primary DT
3655   Check_Dog (obj);       // Check primary DT
3656 @}
3657
3658 int main ()
3659 @{
3660   adainit ();  test();  adafinal ();
3661   return 0;
3662 @}
3663 @end smallexample
3664
3665 @node Comparison between GNAT and C/C++ Compilation Models
3666 @section Comparison between GNAT and C/C++ Compilation Models
3667
3668 @noindent
3669 The GNAT model of compilation is close to the C and C++ models. You can
3670 think of Ada specs as corresponding to header files in C. As in C, you
3671 don't need to compile specs; they are compiled when they are used. The
3672 Ada @code{with} is similar in effect to the @code{#include} of a C
3673 header.
3674
3675 One notable difference is that, in Ada, you may compile specs separately
3676 to check them for semantic and syntactic accuracy. This is not always
3677 possible with C headers because they are fragments of programs that have
3678 less specific syntactic or semantic rules.
3679
3680 The other major difference is the requirement for running the binder,
3681 which performs two important functions. First, it checks for
3682 consistency. In C or C++, the only defense against assembling
3683 inconsistent programs lies outside the compiler, in a makefile, for
3684 example. The binder satisfies the Ada requirement that it be impossible
3685 to construct an inconsistent program when the compiler is used in normal
3686 mode.
3687
3688 @cindex Elaboration order control
3689 The other important function of the binder is to deal with elaboration
3690 issues. There are also elaboration issues in C++ that are handled
3691 automatically. This automatic handling has the advantage of being
3692 simpler to use, but the C++ programmer has no control over elaboration.
3693 Where @code{gnatbind} might complain there was no valid order of
3694 elaboration, a C++ compiler would simply construct a program that
3695 malfunctioned at run time.
3696 @end ifclear
3697
3698 @node Comparison between GNAT and Conventional Ada Library Models
3699 @section Comparison between GNAT and Conventional Ada Library Models
3700
3701 @noindent
3702 This section is intended for Ada programmers who have
3703 used an Ada compiler implementing the traditional Ada library
3704 model, as described in the Ada Reference Manual.
3705
3706 @cindex GNAT library
3707 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3708 source files themselves acts as the library. Compiling Ada programs does
3709 not generate any centralized information, but rather an object file and
3710 a ALI file, which are of interest only to the binder and linker.
3711 In a traditional system, the compiler reads information not only from
3712 the source file being compiled, but also from the centralized library.
3713 This means that the effect of a compilation depends on what has been
3714 previously compiled. In particular:
3715
3716 @itemize @bullet
3717 @item
3718 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3719 to the version of the unit most recently compiled into the library.
3720
3721 @item
3722 Inlining is effective only if the necessary body has already been
3723 compiled into the library.
3724
3725 @item
3726 Compiling a unit may obsolete other units in the library.
3727 @end itemize
3728
3729 @noindent
3730 In GNAT, compiling one unit never affects the compilation of any other
3731 units because the compiler reads only source files. Only changes to source
3732 files can affect the results of a compilation. In particular:
3733
3734 @itemize @bullet
3735 @item
3736 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3737 to the source version of the unit that is currently accessible to the
3738 compiler.
3739
3740 @item
3741 @cindex Inlining
3742 Inlining requires the appropriate source files for the package or
3743 subprogram bodies to be available to the compiler. Inlining is always
3744 effective, independent of the order in which units are complied.
3745
3746 @item
3747 Compiling a unit never affects any other compilations. The editing of
3748 sources may cause previous compilations to be out of date if they
3749 depended on the source file being modified.
3750 @end itemize
3751
3752 @noindent
3753 The most important result of these differences is that order of compilation
3754 is never significant in GNAT. There is no situation in which one is
3755 required to do one compilation before another. What shows up as order of
3756 compilation requirements in the traditional Ada library becomes, in
3757 GNAT, simple source dependencies; in other words, there is only a set
3758 of rules saying what source files must be present when a file is
3759 compiled.
3760
3761 @ifset vms
3762 @node Placement of temporary files
3763 @section Placement of temporary files
3764 @cindex Temporary files (user control over placement)
3765
3766 @noindent
3767 GNAT creates temporary files in the directory designated by the environment
3768 variable @env{TMPDIR}.
3769 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3770 for detailed information on how environment variables are resolved.
3771 For most users the easiest way to make use of this feature is to simply
3772 define @env{TMPDIR} as a job level logical name).
3773 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3774 for compiler temporary files, then you can include something like the
3775 following command in your @file{LOGIN.COM} file:
3776
3777 @smallexample
3778 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3779 @end smallexample
3780
3781 @noindent
3782 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3783 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3784 designated by @env{TEMP}.
3785 If none of these environment variables are defined then GNAT uses the
3786 directory designated by the logical name @code{SYS$SCRATCH:}
3787 (by default the user's home directory). If all else fails
3788 GNAT uses the current directory for temporary files.
3789 @end ifset
3790
3791 @c *************************
3792 @node Compiling Using gcc
3793 @chapter Compiling Using @command{gcc}
3794
3795 @noindent
3796 This chapter discusses how to compile Ada programs using the @command{gcc}
3797 command. It also describes the set of switches
3798 that can be used to control the behavior of the compiler.
3799 @menu
3800 * Compiling Programs::
3801 * Switches for gcc::
3802 * Search Paths and the Run-Time Library (RTL)::
3803 * Order of Compilation Issues::
3804 * Examples::
3805 @end menu
3806
3807 @node Compiling Programs
3808 @section Compiling Programs
3809
3810 @noindent
3811 The first step in creating an executable program is to compile the units
3812 of the program using the @command{gcc} command. You must compile the
3813 following files:
3814
3815 @itemize @bullet
3816 @item
3817 the body file (@file{.adb}) for a library level subprogram or generic
3818 subprogram
3819
3820 @item
3821 the spec file (@file{.ads}) for a library level package or generic
3822 package that has no body
3823
3824 @item
3825 the body file (@file{.adb}) for a library level package
3826 or generic package that has a body
3827
3828 @end itemize
3829
3830 @noindent
3831 You need @emph{not} compile the following files
3832
3833 @itemize @bullet
3834
3835 @item
3836 the spec of a library unit which has a body
3837
3838 @item
3839 subunits
3840 @end itemize
3841
3842 @noindent
3843 because they are compiled as part of compiling related units. GNAT
3844 package specs
3845 when the corresponding body is compiled, and subunits when the parent is
3846 compiled.
3847
3848 @cindex cannot generate code
3849 If you attempt to compile any of these files, you will get one of the
3850 following error messages (where @var{fff} is the name of the file you compiled):
3851
3852 @smallexample
3853 cannot generate code for file @var{fff} (package spec)
3854 to check package spec, use -gnatc
3855
3856 cannot generate code for file @var{fff} (missing subunits)
3857 to check parent unit, use -gnatc
3858
3859 cannot generate code for file @var{fff} (subprogram spec)
3860 to check subprogram spec, use -gnatc
3861
3862 cannot generate code for file @var{fff} (subunit)
3863 to check subunit, use -gnatc
3864 @end smallexample
3865
3866 @noindent
3867 As indicated by the above error messages, if you want to submit
3868 one of these files to the compiler to check for correct semantics
3869 without generating code, then use the @option{-gnatc} switch.
3870
3871 The basic command for compiling a file containing an Ada unit is
3872
3873 @smallexample
3874 $ gcc -c @ovar{switches} @file{file name}
3875 @end smallexample
3876
3877 @noindent
3878 where @var{file name} is the name of the Ada file (usually
3879 having an extension
3880 @file{.ads} for a spec or @file{.adb} for a body).
3881 @ifclear vms
3882 You specify the
3883 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3884 @end ifclear
3885 The result of a successful compilation is an object file, which has the
3886 same name as the source file but an extension of @file{.o} and an Ada
3887 Library Information (ALI) file, which also has the same name as the
3888 source file, but with @file{.ali} as the extension. GNAT creates these
3889 two output files in the current directory, but you may specify a source
3890 file in any directory using an absolute or relative path specification
3891 containing the directory information.
3892
3893 @findex gnat1
3894 @command{gcc} is actually a driver program that looks at the extensions of
3895 the file arguments and loads the appropriate compiler. For example, the
3896 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3897 These programs are in directories known to the driver program (in some
3898 configurations via environment variables you set), but need not be in
3899 your path. The @command{gcc} driver also calls the assembler and any other
3900 utilities needed to complete the generation of the required object
3901 files.
3902
3903 It is possible to supply several file names on the same @command{gcc}
3904 command. This causes @command{gcc} to call the appropriate compiler for
3905 each file. For example, the following command lists three separate
3906 files to be compiled:
3907
3908 @smallexample
3909 $ gcc -c x.adb y.adb z.c
3910 @end smallexample
3911
3912 @noindent
3913 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3914 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3915 The compiler generates three object files @file{x.o}, @file{y.o} and
3916 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3917 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3918 @ifclear vms
3919 except for
3920 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3921 @end ifclear
3922
3923 @node Switches for gcc
3924 @section Switches for @command{gcc}
3925
3926 @noindent
3927 The @command{gcc} command accepts switches that control the
3928 compilation process. These switches are fully described in this section.
3929 First we briefly list all the switches, in alphabetical order, then we
3930 describe the switches in more detail in functionally grouped sections.
3931
3932 More switches exist for GCC than those documented here, especially
3933 for specific targets. However, their use is not recommended as
3934 they may change code generation in ways that are incompatible with
3935 the Ada run-time library, or can cause inconsistencies between
3936 compilation units.
3937
3938 @menu
3939 * Output and Error Message Control::
3940 * Warning Message Control::
3941 * Debugging and Assertion Control::
3942 * Validity Checking::
3943 * Style Checking::
3944 * Run-Time Checks::
3945 * Using gcc for Syntax Checking::
3946 * Using gcc for Semantic Checking::
3947 * Compiling Different Versions of Ada::
3948 * Character Set Control::
3949 * File Naming Control::
3950 * Subprogram Inlining Control::
3951 * Auxiliary Output Control::
3952 * Debugging Control::
3953 * Exception Handling Control::
3954 * Units to Sources Mapping Files::
3955 * Integrated Preprocessing::
3956 * Code Generation Control::
3957 @ifset vms
3958 * Return Codes::
3959 @end ifset
3960 @end menu
3961
3962 @table @option
3963 @c !sort!
3964 @ifclear vms
3965 @cindex @option{-b} (@command{gcc})
3966 @item -b @var{target}
3967 Compile your program to run on @var{target}, which is the name of a
3968 system configuration. You must have a GNAT cross-compiler built if
3969 @var{target} is not the same as your host system.
3970
3971 @item -B@var{dir}
3972 @cindex @option{-B} (@command{gcc})
3973 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3974 from @var{dir} instead of the default location. Only use this switch
3975 when multiple versions of the GNAT compiler are available.
3976 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3977 GNU Compiler Collection (GCC)}, for further details. You would normally
3978 use the @option{-b} or @option{-V} switch instead.
3979
3980 @item -c
3981 @cindex @option{-c} (@command{gcc})
3982 Compile. Always use this switch when compiling Ada programs.
3983
3984 Note: for some other languages when using @command{gcc}, notably in
3985 the case of C and C++, it is possible to use
3986 use @command{gcc} without a @option{-c} switch to
3987 compile and link in one step. In the case of GNAT, you
3988 cannot use this approach, because the binder must be run
3989 and @command{gcc} cannot be used to run the GNAT binder.
3990 @end ifclear
3991
3992 @item -fno-inline
3993 @cindex @option{-fno-inline} (@command{gcc})
3994 Suppresses all back-end inlining, even if other optimization or inlining
3995 switches are set.
3996 This includes suppression of inlining that results
3997 from the use of the pragma @code{Inline_Always}.
3998 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3999 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4000 effect if this switch is present.
4001
4002 @item -fno-inline-functions
4003 @cindex @option{-fno-inline-functions} (@command{gcc})
4004 Suppresses automatic inlining of simple subprograms, which is enabled
4005 if @option{-O3} is used.
4006
4007 @item -fno-inline-small-functions
4008 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4009 Suppresses automatic inlining of small subprograms, which is enabled
4010 if @option{-O2} is used.
4011
4012 @item -fno-inline-functions-called-once
4013 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4014 Suppresses inlining of subprograms local to the unit and called once
4015 from within it, which is enabled if @option{-O1} is used.
4016
4017 @item -fno-ivopts
4018 @cindex @option{-fno-ivopts} (@command{gcc})
4019 Suppresses high-level loop induction variable optimizations, which are
4020 enabled if @option{-O1} is used. These optimizations are generally
4021 profitable but, for some specific cases of loops with numerous uses
4022 of the iteration variable that follow a common pattern, they may end
4023 up destroying the regularity that could be exploited at a lower level
4024 and thus producing inferior code.
4025
4026 @item -fno-strict-aliasing
4027 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4028 Causes the compiler to avoid assumptions regarding non-aliasing
4029 of objects of different types. See
4030 @ref{Optimization and Strict Aliasing} for details.
4031
4032 @item -fstack-check
4033 @cindex @option{-fstack-check} (@command{gcc})
4034 Activates stack checking.
4035 See @ref{Stack Overflow Checking} for details.
4036
4037 @item -fstack-usage
4038 @cindex @option{-fstack-usage} (@command{gcc})
4039 Makes the compiler output stack usage information for the program, on a
4040 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4041
4042 @item -fcallgraph-info@r{[}=su@r{]}
4043 @cindex @option{-fcallgraph-info} (@command{gcc})
4044 Makes the compiler output callgraph information for the program, on a
4045 per-file basis.  The information is generated in the VCG format.  It can
4046 be decorated with stack-usage per-node information.
4047
4048 @item ^-g^/DEBUG^
4049 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4050 Generate debugging information. This information is stored in the object
4051 file and copied from there to the final executable file by the linker,
4052 where it can be read by the debugger. You must use the
4053 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4054
4055 @item -gnat83
4056 @cindex @option{-gnat83} (@command{gcc})
4057 Enforce Ada 83 restrictions.
4058
4059 @item -gnat95
4060 @cindex @option{-gnat95} (@command{gcc})
4061 Enforce Ada 95 restrictions.
4062
4063 @item -gnat05
4064 @cindex @option{-gnat05} (@command{gcc})
4065 Allow full Ada 2005 features.
4066
4067 @item -gnata
4068 @cindex @option{-gnata} (@command{gcc})
4069 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4070 activated. Note that these pragmas can also be controlled using the
4071 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4072 It also activates pragmas @code{Check}, @code{Precondition}, and
4073 @code{Postcondition}. Note that these pragmas can also be controlled
4074 using the configuration pragma @code{Check_Policy}.
4075
4076 @item -gnatA
4077 @cindex @option{-gnatA} (@command{gcc})
4078 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4079 it will be ignored.
4080
4081 @item -gnatb
4082 @cindex @option{-gnatb} (@command{gcc})
4083 Generate brief messages to @file{stderr} even if verbose mode set.
4084
4085 @item -gnatB
4086 @cindex @option{-gnatB} (@command{gcc})
4087 Assume no invalid (bad) values except for 'Valid attribute use.
4088
4089 @item -gnatc
4090 @cindex @option{-gnatc} (@command{gcc})
4091 Check syntax and semantics only (no code generation attempted).
4092
4093 @item -gnatd
4094 @cindex @option{-gnatd} (@command{gcc})
4095 Specify debug options for the compiler. The string of characters after
4096 the @option{-gnatd} specify the specific debug options. The possible
4097 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4098 compiler source file @file{debug.adb} for details of the implemented
4099 debug options. Certain debug options are relevant to applications
4100 programmers, and these are documented at appropriate points in this
4101 users guide.
4102
4103 @ifclear vms
4104 @item -gnatD
4105 @cindex @option{-gnatD[nn]} (@command{gcc})
4106 @end ifclear
4107 @ifset vms
4108 @item /XDEBUG /LXDEBUG=nnn
4109 @end ifset
4110 Create expanded source files for source level debugging. This switch
4111 also suppress generation of cross-reference information
4112 (see @option{-gnatx}).
4113
4114 @item -gnatec=@var{path}
4115 @cindex @option{-gnatec} (@command{gcc})
4116 Specify a configuration pragma file
4117 @ifclear vms
4118 (the equal sign is optional)
4119 @end ifclear
4120 (@pxref{The Configuration Pragmas Files}).
4121
4122 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4123 @cindex @option{-gnateD} (@command{gcc})
4124 Defines a symbol, associated with @var{value}, for preprocessing.
4125 (@pxref{Integrated Preprocessing}).
4126
4127 @item -gnatef
4128 @cindex @option{-gnatef} (@command{gcc})
4129 Display full source path name in brief error messages.
4130
4131 @item -gnateG
4132 @cindex @option{-gnateG} (@command{gcc})
4133 Save result of preprocessing in a text file.
4134
4135 @item -gnatem=@var{path}
4136 @cindex @option{-gnatem} (@command{gcc})
4137 Specify a mapping file
4138 @ifclear vms
4139 (the equal sign is optional)
4140 @end ifclear
4141 (@pxref{Units to Sources Mapping Files}).
4142
4143 @item -gnatep=@var{file}
4144 @cindex @option{-gnatep} (@command{gcc})
4145 Specify a preprocessing data file
4146 @ifclear vms
4147 (the equal sign is optional)
4148 @end ifclear
4149 (@pxref{Integrated Preprocessing}).
4150
4151 @item -gnatE
4152 @cindex @option{-gnatE} (@command{gcc})
4153 Full dynamic elaboration checks.
4154
4155 @item -gnatf
4156 @cindex @option{-gnatf} (@command{gcc})
4157 Full errors. Multiple errors per line, all undefined references, do not
4158 attempt to suppress cascaded errors.
4159
4160 @item -gnatF
4161 @cindex @option{-gnatF} (@command{gcc})
4162 Externals names are folded to all uppercase.
4163
4164 @item ^-gnatg^/GNAT_INTERNAL^
4165 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4166 Internal GNAT implementation mode. This should not be used for
4167 applications programs, it is intended only for use by the compiler
4168 and its run-time library. For documentation, see the GNAT sources.
4169 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4170 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4171 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4172 so that all standard warnings and all standard style options are turned on.
4173 All warnings and style error messages are treated as errors.
4174
4175 @ifclear vms
4176 @item -gnatG=nn
4177 @cindex @option{-gnatG[nn]} (@command{gcc})
4178 @end ifclear
4179 @ifset vms
4180 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4181 @end ifset
4182 List generated expanded code in source form.
4183
4184 @item ^-gnath^/HELP^
4185 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4186 Output usage information. The output is written to @file{stdout}.
4187
4188 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4189 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4190 Identifier character set
4191 @ifclear vms
4192 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4193 @end ifclear
4194 For details of the possible selections for @var{c},
4195 see @ref{Character Set Control}.
4196
4197 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4198 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4199 Ignore representation clauses. When this switch is used,
4200 representation clauses are treated as comments. This is useful
4201 when initially porting code where you want to ignore rep clause
4202 problems, and also for compiling foreign code (particularly
4203 for use with ASIS). The representation clauses that are ignored
4204 are: enumeration_representation_clause, record_representation_clause,
4205 and attribute_definition_clause for the following attributes:
4206 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4207 Object_Size, Size, Small, Stream_Size, and Value_Size.
4208 Note that this option should be used only for compiling -- the
4209 code is likely to malfunction at run time.
4210
4211 @item -gnatjnn
4212 @cindex @option{-gnatjnn} (@command{gcc})
4213 Reformat error messages to fit on nn character lines
4214
4215 @item -gnatk=@var{n}
4216 @cindex @option{-gnatk} (@command{gcc})
4217 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4218
4219 @item -gnatl
4220 @cindex @option{-gnatl} (@command{gcc})
4221 Output full source listing with embedded error messages.
4222
4223 @item -gnatL
4224 @cindex @option{-gnatL} (@command{gcc})
4225 Used in conjunction with -gnatG or -gnatD to intersperse original
4226 source lines (as comment lines with line numbers) in the expanded
4227 source output.
4228
4229 @item -gnatm=@var{n}
4230 @cindex @option{-gnatm} (@command{gcc})
4231 Limit number of detected error or warning messages to @var{n}
4232 where @var{n} is in the range 1..999999. The default setting if
4233 no switch is given is 9999. If the number of warnings reaches this
4234 limit, then a message is output and further warnings are suppressed,
4235 but the compilation is continued. If the number of error messages
4236 reaches this limit, then a message is output and the compilation
4237 is abandoned. The equal sign here is optional. A value of zero
4238 means that no limit applies.
4239
4240 @item -gnatn
4241 @cindex @option{-gnatn} (@command{gcc})
4242 Activate inlining for subprograms for which
4243 pragma @code{inline} is specified. This inlining is performed
4244 by the GCC back-end.
4245
4246 @item -gnatN
4247 @cindex @option{-gnatN} (@command{gcc})
4248 Activate front end inlining for subprograms for which
4249 pragma @code{Inline} is specified. This inlining is performed
4250 by the front end and will be visible in the
4251 @option{-gnatG} output.
4252
4253 When using a gcc-based back end (in practice this means using any version
4254 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4255 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4256 Historically front end inlining was more extensive than the gcc back end
4257 inlining, but that is no longer the case.
4258
4259 @item -gnato
4260 @cindex @option{-gnato} (@command{gcc})
4261 Enable numeric overflow checking (which is not normally enabled by
4262 default). Note that division by zero is a separate check that is not
4263 controlled by this switch (division by zero checking is on by default).
4264
4265 @item -gnatp
4266 @cindex @option{-gnatp} (@command{gcc})
4267 Suppress all checks. See @ref{Run-Time Checks} for details.
4268
4269 @item -gnatP
4270 @cindex @option{-gnatP} (@command{gcc})
4271 Enable polling. This is required on some systems (notably Windows NT) to
4272 obtain asynchronous abort and asynchronous transfer of control capability.
4273 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4274 details.
4275
4276 @item -gnatq
4277 @cindex @option{-gnatq} (@command{gcc})
4278 Don't quit. Try semantics, even if parse errors.
4279
4280 @item -gnatQ
4281 @cindex @option{-gnatQ} (@command{gcc})
4282 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4283
4284 @item -gnatr
4285 @cindex @option{-gnatr} (@command{gcc})
4286 Treat pragma Restrictions as Restriction_Warnings.
4287
4288 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4289 @cindex @option{-gnatR} (@command{gcc})
4290 Output representation information for declared types and objects.
4291
4292 @item -gnats
4293 @cindex @option{-gnats} (@command{gcc})
4294 Syntax check only.
4295
4296 @item -gnatS
4297 @cindex @option{-gnatS} (@command{gcc})
4298 Print package Standard.
4299
4300 @item -gnatt
4301 @cindex @option{-gnatt} (@command{gcc})
4302 Generate tree output file.
4303
4304 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4305 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4306 All compiler tables start at @var{nnn} times usual starting size.
4307
4308 @item -gnatu
4309 @cindex @option{-gnatu} (@command{gcc})
4310 List units for this compilation.
4311
4312 @item -gnatU
4313 @cindex @option{-gnatU} (@command{gcc})
4314 Tag all error messages with the unique string ``error:''
4315
4316 @item -gnatv
4317 @cindex @option{-gnatv} (@command{gcc})
4318 Verbose mode. Full error output with source lines to @file{stdout}.
4319
4320 @item -gnatV
4321 @cindex @option{-gnatV} (@command{gcc})
4322 Control level of validity checking. See separate section describing
4323 this feature.
4324
4325 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4326 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4327 Warning mode where
4328 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4329 the exact warnings that
4330 are enabled or disabled (@pxref{Warning Message Control}).
4331
4332 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4333 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4334 Wide character encoding method
4335 @ifclear vms
4336 (@var{e}=n/h/u/s/e/8).
4337 @end ifclear
4338 @ifset vms
4339 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4340 @end ifset
4341
4342 @item -gnatx
4343 @cindex @option{-gnatx} (@command{gcc})
4344 Suppress generation of cross-reference information.
4345
4346 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4347 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4348 Enable built-in style checks (@pxref{Style Checking}).
4349
4350 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4351 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4352 Distribution stub generation and compilation
4353 @ifclear vms
4354 (@var{m}=r/c for receiver/caller stubs).
4355 @end ifclear
4356 @ifset vms
4357 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4358 to be generated and compiled).
4359 @end ifset
4360
4361 @item ^-I^/SEARCH=^@var{dir}
4362 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4363 @cindex RTL
4364 Direct GNAT to search the @var{dir} directory for source files needed by
4365 the current compilation
4366 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4367
4368 @item ^-I-^/NOCURRENT_DIRECTORY^
4369 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4370 @cindex RTL
4371 Except for the source file named in the command line, do not look for source
4372 files in the directory containing the source file named in the command line
4373 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4374
4375 @ifclear vms
4376 @item -mbig-switch
4377 @cindex @option{-mbig-switch} (@command{gcc})
4378 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4379 This standard gcc switch causes the compiler to use larger offsets in its
4380 jump table representation for @code{case} statements.
4381 This may result in less efficient code, but is sometimes necessary
4382 (for example on HP-UX targets)
4383 @cindex HP-UX and @option{-mbig-switch} option
4384 in order to compile large and/or nested @code{case} statements.
4385
4386 @item -o @var{file}
4387 @cindex @option{-o} (@command{gcc})
4388 This switch is used in @command{gcc} to redirect the generated object file
4389 and its associated ALI file. Beware of this switch with GNAT, because it may
4390 cause the object file and ALI file to have different names which in turn
4391 may confuse the binder and the linker.
4392 @end ifclear
4393
4394 @item -nostdinc
4395 @cindex @option{-nostdinc} (@command{gcc})
4396 Inhibit the search of the default location for the GNAT Run Time
4397 Library (RTL) source files.
4398
4399 @item -nostdlib
4400 @cindex @option{-nostdlib} (@command{gcc})
4401 Inhibit the search of the default location for the GNAT Run Time
4402 Library (RTL) ALI files.
4403
4404 @ifclear vms
4405 @item -O@ovar{n}
4406 @cindex @option{-O} (@command{gcc})
4407 @var{n} controls the optimization level.
4408
4409 @table @asis
4410 @item n = 0
4411 No optimization, the default setting if no @option{-O} appears
4412
4413 @item n = 1
4414 Normal optimization, the default if you specify @option{-O} without
4415 an operand. A good compromise between code quality and compilation
4416 time.
4417
4418 @item n = 2
4419 Extensive optimization, may improve execution time, possibly at the cost of
4420 substantially increased compilation time.
4421
4422 @item n = 3
4423 Same as @option{-O2}, and also includes inline expansion for small subprograms
4424 in the same unit.
4425
4426 @item n = s
4427 Optimize space usage
4428 @end table
4429
4430 @noindent
4431 See also @ref{Optimization Levels}.
4432 @end ifclear
4433
4434 @ifset vms
4435 @item  /NOOPTIMIZE
4436 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4437 Equivalent to @option{/OPTIMIZE=NONE}.
4438 This is the default behavior in the absence of an @option{/OPTIMIZE}
4439 qualifier.
4440
4441 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4442 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4443 Selects the level of optimization for your program. The supported
4444 keywords are as follows:
4445 @table @code
4446 @item   ALL
4447 Perform most optimizations, including those that
4448 are expensive.
4449 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4450 without keyword options.
4451
4452 @item   NONE
4453 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4454
4455 @item SOME
4456 Perform some optimizations, but omit ones that are costly.
4457
4458 @item   DEVELOPMENT
4459 Same as @code{SOME}.
4460
4461 @item INLINING
4462 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4463 automatic inlining of small subprograms within a unit
4464
4465 @item   UNROLL_LOOPS
4466 Try to unroll loops. This keyword may be specified together with
4467 any keyword above other than @code{NONE}. Loop unrolling
4468 usually, but not always, improves the performance of programs.
4469
4470 @item SPACE
4471 Optimize space usage
4472 @end table
4473
4474 @noindent
4475 See also @ref{Optimization Levels}.
4476 @end ifset
4477
4478 @ifclear vms
4479 @item -pass-exit-codes
4480 @cindex @option{-pass-exit-codes} (@command{gcc})
4481 Catch exit codes from the compiler and use the most meaningful as
4482 exit status.
4483 @end ifclear
4484
4485 @item --RTS=@var{rts-path}
4486 @cindex @option{--RTS} (@command{gcc})
4487 Specifies the default location of the runtime library. Same meaning as the
4488 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4489
4490 @item ^-S^/ASM^
4491 @cindex @option{^-S^/ASM^} (@command{gcc})
4492 ^Used in place of @option{-c} to^Used to^
4493 cause the assembler source file to be
4494 generated, using @file{^.s^.S^} as the extension,
4495 instead of the object file.
4496 This may be useful if you need to examine the generated assembly code.
4497
4498 @item ^-fverbose-asm^/VERBOSE_ASM^
4499 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4500 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4501 to cause the generated assembly code file to be annotated with variable
4502 names, making it significantly easier to follow.
4503
4504 @item ^-v^/VERBOSE^
4505 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4506 Show commands generated by the @command{gcc} driver. Normally used only for
4507 debugging purposes or if you need to be sure what version of the
4508 compiler you are executing.
4509
4510 @ifclear vms
4511 @item -V @var{ver}
4512 @cindex @option{-V} (@command{gcc})
4513 Execute @var{ver} version of the compiler. This is the @command{gcc}
4514 version, not the GNAT version.
4515 @end ifclear
4516
4517 @item ^-w^/NO_BACK_END_WARNINGS^
4518 @cindex @option{-w} (@command{gcc})
4519 Turn off warnings generated by the back end of the compiler. Use of
4520 this switch also causes the default for front end warnings to be set
4521 to suppress (as though @option{-gnatws} had appeared at the start of
4522 the options).
4523
4524 @end table
4525
4526 @ifclear vms
4527 @c Combining qualifiers does not work on VMS
4528 You may combine a sequence of GNAT switches into a single switch. For
4529 example, the combined switch
4530
4531 @cindex Combining GNAT switches
4532 @smallexample
4533 -gnatofi3
4534 @end smallexample
4535
4536 @noindent
4537 is equivalent to specifying the following sequence of switches:
4538
4539 @smallexample
4540 -gnato -gnatf -gnati3
4541 @end smallexample
4542 @end ifclear
4543
4544 @noindent
4545 The following restrictions apply to the combination of switches
4546 in this manner:
4547
4548 @itemize @bullet
4549 @item
4550 The switch @option{-gnatc} if combined with other switches must come
4551 first in the string.
4552
4553 @item
4554 The switch @option{-gnats} if combined with other switches must come
4555 first in the string.
4556
4557 @item
4558 The switches
4559 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4560 may not be combined with any other switches.
4561
4562 @ifclear vms
4563 @item
4564 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4565 switch), then all further characters in the switch are interpreted
4566 as style modifiers (see description of @option{-gnaty}).
4567
4568 @item
4569 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4570 switch), then all further characters in the switch are interpreted
4571 as debug flags (see description of @option{-gnatd}).
4572
4573 @item
4574 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4575 switch), then all further characters in the switch are interpreted
4576 as warning mode modifiers (see description of @option{-gnatw}).
4577
4578 @item
4579 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4580 switch), then all further characters in the switch are interpreted
4581 as validity checking options (see description of @option{-gnatV}).
4582 @end ifclear
4583 @end itemize
4584
4585 @node Output and Error Message Control
4586 @subsection Output and Error Message Control
4587 @findex stderr
4588
4589 @noindent
4590 The standard default format for error messages is called ``brief format''.
4591 Brief format messages are written to @file{stderr} (the standard error
4592 file) and have the following form:
4593
4594 @smallexample
4595 e.adb:3:04: Incorrect spelling of keyword "function"
4596 e.adb:4:20: ";" should be "is"
4597 @end smallexample
4598
4599 @noindent
4600 The first integer after the file name is the line number in the file,
4601 and the second integer is the column number within the line.
4602 @ifclear vms
4603 @code{GPS} can parse the error messages
4604 and point to the referenced character.
4605 @end ifclear
4606 The following switches provide control over the error message
4607 format:
4608
4609 @table @option
4610 @c !sort!
4611 @item -gnatv
4612 @cindex @option{-gnatv} (@command{gcc})
4613 @findex stdout
4614 @ifclear vms
4615 The v stands for verbose.
4616 @end ifclear
4617 The effect of this setting is to write long-format error
4618 messages to @file{stdout} (the standard output file.
4619 The same program compiled with the
4620 @option{-gnatv} switch would generate:
4621
4622 @smallexample
4623 @cartouche
4624 3. funcion X (Q : Integer)
4625    |
4626 >>> Incorrect spelling of keyword "function"
4627 4. return Integer;
4628                  |
4629 >>> ";" should be "is"
4630 @end cartouche
4631 @end smallexample
4632
4633 @noindent
4634 The vertical bar indicates the location of the error, and the @samp{>>>}
4635 prefix can be used to search for error messages. When this switch is
4636 used the only source lines output are those with errors.
4637
4638 @item -gnatl
4639 @cindex @option{-gnatl} (@command{gcc})
4640 @ifclear vms
4641 The @code{l} stands for list.
4642 @end ifclear
4643 This switch causes a full listing of
4644 the file to be generated. In the case where a body is
4645 compiled, the corresponding spec is also listed, along
4646 with any subunits. Typical output from compiling a package
4647 body @file{p.adb} might look like:
4648
4649 @smallexample @c ada
4650 @cartouche
4651  Compiling: p.adb
4652
4653      1. package body p is
4654      2.    procedure a;
4655      3.    procedure a is separate;
4656      4. begin
4657      5.    null
4658                |
4659         >>> missing ";"
4660
4661      6. end;
4662
4663 Compiling: p.ads
4664
4665      1. package p is
4666      2.    pragma Elaborate_Body
4667                                 |
4668         >>> missing ";"
4669
4670      3. end p;
4671
4672 Compiling: p-a.adb
4673
4674      1. separate p
4675                 |
4676         >>> missing "("
4677
4678      2. procedure a is
4679      3. begin
4680      4.    null
4681                |
4682         >>> missing ";"
4683
4684      5. end;
4685 @end cartouche
4686 @end smallexample
4687
4688 @noindent
4689 @findex stderr
4690 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4691 standard output is redirected, a brief summary is written to
4692 @file{stderr} (standard error) giving the number of error messages and
4693 warning messages generated.
4694
4695 @item -^gnatl^OUTPUT_FILE^=file
4696 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4697 This has the same effect as @option{-gnatl} except that the output is
4698 written to a file instead of to standard output. If the given name
4699 @file{fname} does not start with a period, then it is the full name
4700 of the file to be written. If @file{fname} is an extension, it is
4701 appended to the name of the file being compiled. For example, if
4702 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4703 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4704
4705 @item -gnatU
4706 @cindex @option{-gnatU} (@command{gcc})
4707 This switch forces all error messages to be preceded by the unique
4708 string ``error:''. This means that error messages take a few more
4709 characters in space, but allows easy searching for and identification
4710 of error messages.
4711
4712 @item -gnatb
4713 @cindex @option{-gnatb} (@command{gcc})
4714 @ifclear vms
4715 The @code{b} stands for brief.
4716 @end ifclear
4717 This switch causes GNAT to generate the
4718 brief format error messages to @file{stderr} (the standard error
4719 file) as well as the verbose
4720 format message or full listing (which as usual is written to
4721 @file{stdout} (the standard output file).
4722
4723 @item -gnatm=@var{n}
4724 @cindex @option{-gnatm} (@command{gcc})
4725 @ifclear vms
4726 The @code{m} stands for maximum.
4727 @end ifclear
4728 @var{n} is a decimal integer in the
4729 range of 1 to 999999 and limits the number of error or warning
4730 messages to be generated. For example, using
4731 @option{-gnatm2} might yield
4732
4733 @smallexample
4734 e.adb:3:04: Incorrect spelling of keyword "function"
4735 e.adb:5:35: missing ".."
4736 fatal error: maximum number of errors detected
4737 compilation abandoned
4738 @end smallexample
4739
4740 @noindent
4741 The default setting if
4742 no switch is given is 9999. If the number of warnings reaches this
4743 limit, then a message is output and further warnings are suppressed,
4744 but the compilation is continued. If the number of error messages
4745 reaches this limit, then a message is output and the compilation
4746 is abandoned. A value of zero means that no limit applies.
4747
4748 @noindent
4749 Note that the equal sign is optional, so the switches
4750 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4751
4752 @item -gnatf
4753 @cindex @option{-gnatf} (@command{gcc})
4754 @cindex Error messages, suppressing
4755 @ifclear vms
4756 The @code{f} stands for full.
4757 @end ifclear
4758 Normally, the compiler suppresses error messages that are likely to be
4759 redundant. This switch causes all error
4760 messages to be generated. In particular, in the case of
4761 references to undefined variables. If a given variable is referenced
4762 several times, the normal format of messages is
4763 @smallexample
4764 e.adb:7:07: "V" is undefined (more references follow)
4765 @end smallexample
4766
4767 @noindent
4768 where the parenthetical comment warns that there are additional
4769 references to the variable @code{V}. Compiling the same program with the
4770 @option{-gnatf} switch yields
4771
4772 @smallexample
4773 e.adb:7:07: "V" is undefined
4774 e.adb:8:07: "V" is undefined
4775 e.adb:8:12: "V" is undefined
4776 e.adb:8:16: "V" is undefined
4777 e.adb:9:07: "V" is undefined
4778 e.adb:9:12: "V" is undefined
4779 @end smallexample
4780
4781 @noindent
4782 The @option{-gnatf} switch also generates additional information for
4783 some error messages.  Some examples are:
4784
4785 @itemize @bullet
4786 @item
4787 Full details on entities not available in high integrity mode
4788 @item
4789 Details on possibly non-portable unchecked conversion
4790 @item
4791 List possible interpretations for ambiguous calls
4792 @item
4793 Additional details on incorrect parameters
4794 @end itemize
4795
4796 @item -gnatjnn
4797 @cindex @option{-gnatjnn} (@command{gcc})
4798 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4799 with continuation lines are treated as though the continuation lines were
4800 separate messages (and so a warning with two continuation lines counts as
4801 three warnings, and is listed as three separate messages).
4802
4803 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4804 messages are output in a different manner. A message and all its continuation
4805 lines are treated as a unit, and count as only one warning or message in the
4806 statistics totals. Furthermore, the message is reformatted so that no line
4807 is longer than nn characters.
4808
4809 @item -gnatq
4810 @cindex @option{-gnatq} (@command{gcc})
4811 @ifclear vms
4812 The @code{q} stands for quit (really ``don't quit'').
4813 @end ifclear
4814 In normal operation mode, the compiler first parses the program and
4815 determines if there are any syntax errors. If there are, appropriate
4816 error messages are generated and compilation is immediately terminated.
4817 This switch tells
4818 GNAT to continue with semantic analysis even if syntax errors have been
4819 found. This may enable the detection of more errors in a single run. On
4820 the other hand, the semantic analyzer is more likely to encounter some
4821 internal fatal error when given a syntactically invalid tree.
4822
4823 @item -gnatQ
4824 @cindex @option{-gnatQ} (@command{gcc})
4825 In normal operation mode, the @file{ALI} file is not generated if any
4826 illegalities are detected in the program. The use of @option{-gnatQ} forces
4827 generation of the @file{ALI} file. This file is marked as being in
4828 error, so it cannot be used for binding purposes, but it does contain
4829 reasonably complete cross-reference information, and thus may be useful
4830 for use by tools (e.g., semantic browsing tools or integrated development
4831 environments) that are driven from the @file{ALI} file. This switch
4832 implies @option{-gnatq}, since the semantic phase must be run to get a
4833 meaningful ALI file.
4834
4835 In addition, if @option{-gnatt} is also specified, then the tree file is
4836 generated even if there are illegalities. It may be useful in this case
4837 to also specify @option{-gnatq} to ensure that full semantic processing
4838 occurs. The resulting tree file can be processed by ASIS, for the purpose
4839 of providing partial information about illegal units, but if the error
4840 causes the tree to be badly malformed, then ASIS may crash during the
4841 analysis.
4842
4843 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4844 being in error, @command{gnatmake} will attempt to recompile the source when it
4845 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4846
4847 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4848 since ALI files are never generated if @option{-gnats} is set.
4849
4850 @end table
4851
4852 @node Warning Message Control
4853 @subsection Warning Message Control
4854 @cindex Warning messages
4855 @noindent
4856 In addition to error messages, which correspond to illegalities as defined
4857 in the Ada Reference Manual, the compiler detects two kinds of warning
4858 situations.
4859
4860 First, the compiler considers some constructs suspicious and generates a
4861 warning message to alert you to a possible error. Second, if the
4862 compiler detects a situation that is sure to raise an exception at
4863 run time, it generates a warning message. The following shows an example
4864 of warning messages:
4865 @smallexample
4866 e.adb:4:24: warning: creation of object may raise Storage_Error
4867 e.adb:10:17: warning: static value out of range
4868 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4869 @end smallexample
4870
4871 @noindent
4872 GNAT considers a large number of situations as appropriate
4873 for the generation of warning messages. As always, warnings are not
4874 definite indications of errors. For example, if you do an out-of-range
4875 assignment with the deliberate intention of raising a
4876 @code{Constraint_Error} exception, then the warning that may be
4877 issued does not indicate an error. Some of the situations for which GNAT
4878 issues warnings (at least some of the time) are given in the following
4879 list. This list is not complete, and new warnings are often added to
4880 subsequent versions of GNAT. The list is intended to give a general idea
4881 of the kinds of warnings that are generated.
4882
4883 @itemize @bullet
4884 @item
4885 Possible infinitely recursive calls
4886
4887 @item
4888 Out-of-range values being assigned
4889
4890 @item
4891 Possible order of elaboration problems
4892
4893 @item
4894 Assertions (pragma Assert) that are sure to fail
4895
4896 @item
4897 Unreachable code
4898
4899 @item
4900 Address clauses with possibly unaligned values, or where an attempt is
4901 made to overlay a smaller variable with a larger one.
4902
4903 @item
4904 Fixed-point type declarations with a null range
4905
4906 @item
4907 Direct_IO or Sequential_IO instantiated with a type that has access values
4908
4909 @item
4910 Variables that are never assigned a value
4911
4912 @item
4913 Variables that are referenced before being initialized
4914
4915 @item
4916 Task entries with no corresponding @code{accept} statement
4917
4918 @item
4919 Duplicate accepts for the same task entry in a @code{select}
4920
4921 @item
4922 Objects that take too much storage
4923
4924 @item
4925 Unchecked conversion between types of differing sizes
4926
4927 @item
4928 Missing @code{return} statement along some execution path in a function
4929
4930 @item
4931 Incorrect (unrecognized) pragmas
4932
4933 @item
4934 Incorrect external names
4935
4936 @item
4937 Allocation from empty storage pool
4938
4939 @item
4940 Potentially blocking operation in protected type
4941
4942 @item
4943 Suspicious parenthesization of expressions
4944
4945 @item
4946 Mismatching bounds in an aggregate
4947
4948 @item
4949 Attempt to return local value by reference
4950
4951 @item
4952 Premature instantiation of a generic body
4953
4954 @item
4955 Attempt to pack aliased components
4956
4957 @item
4958 Out of bounds array subscripts
4959
4960 @item
4961 Wrong length on string assignment
4962
4963 @item
4964 Violations of style rules if style checking is enabled
4965
4966 @item
4967 Unused @code{with} clauses
4968
4969 @item
4970 @code{Bit_Order} usage that does not have any effect
4971
4972 @item
4973 @code{Standard.Duration} used to resolve universal fixed expression
4974
4975 @item
4976 Dereference of possibly null value
4977
4978 @item
4979 Declaration that is likely to cause storage error
4980
4981 @item
4982 Internal GNAT unit @code{with}'ed by application unit
4983
4984 @item
4985 Values known to be out of range at compile time
4986
4987 @item
4988 Unreferenced labels and variables
4989
4990 @item
4991 Address overlays that could clobber memory
4992
4993 @item
4994 Unexpected initialization when address clause present
4995
4996 @item
4997 Bad alignment for address clause
4998
4999 @item
5000 Useless type conversions
5001
5002 @item
5003 Redundant assignment statements and other redundant constructs
5004
5005 @item
5006 Useless exception handlers
5007
5008 @item
5009 Accidental hiding of name by child unit
5010
5011 @item
5012 Access before elaboration detected at compile time
5013
5014 @item
5015 A range in a @code{for} loop that is known to be null or might be null
5016
5017 @end itemize
5018
5019 @noindent
5020 The following section lists compiler switches that are available
5021 to control the handling of warning messages. It is also possible
5022 to exercise much finer control over what warnings are issued and
5023 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5024 gnat_rm, GNAT Reference manual}.
5025
5026 @table @option
5027 @c !sort!
5028 @item -gnatwa
5029 @emph{Activate all optional errors.}
5030 @cindex @option{-gnatwa} (@command{gcc})
5031 This switch activates most optional warning messages, see remaining list
5032 in this section for details on optional warning messages that can be
5033 individually controlled.  The warnings that are not turned on by this
5034 switch are
5035 @option{-gnatwd} (implicit dereferencing),
5036 @option{-gnatwh} (hiding),
5037 @option{-gnatwl} (elaboration warnings),
5038 @option{-gnatw.o} (warn on values set by out parameters ignored)
5039 and @option{-gnatwt} (tracking of deleted conditional code).
5040 All other optional warnings are turned on.
5041
5042 @item -gnatwA
5043 @emph{Suppress all optional errors.}
5044 @cindex @option{-gnatwA} (@command{gcc})
5045 This switch suppresses all optional warning messages, see remaining list
5046 in this section for details on optional warning messages that can be
5047 individually controlled.
5048
5049 @item -gnatw.a
5050 @emph{Activate warnings on failing assertions.}
5051 @cindex @option{-gnatw.a} (@command{gcc})
5052 @cindex Assert failures
5053 This switch activates warnings for assertions where the compiler can tell at
5054 compile time that the assertion will fail. Note that this warning is given
5055 even if assertions are disabled. The default is that such warnings are
5056 generated.
5057
5058 @item -gnatw.A
5059 @emph{Suppress warnings on failing assertions.}
5060 @cindex @option{-gnatw.A} (@command{gcc})
5061 @cindex Assert failures
5062 This switch suppresses warnings for assertions where the compiler can tell at
5063 compile time that the assertion will fail.
5064
5065 @item -gnatwb
5066 @emph{Activate warnings on bad fixed values.}
5067 @cindex @option{-gnatwb} (@command{gcc})
5068 @cindex Bad fixed values
5069 @cindex Fixed-point Small value
5070 @cindex Small value
5071 This switch activates warnings for static fixed-point expressions whose
5072 value is not an exact multiple of Small. Such values are implementation
5073 dependent, since an implementation is free to choose either of the multiples
5074 that surround the value. GNAT always chooses the closer one, but this is not
5075 required behavior, and it is better to specify a value that is an exact
5076 multiple, ensuring predictable execution. The default is that such warnings
5077 are not generated.
5078
5079 @item -gnatwB
5080 @emph{Suppress warnings on bad fixed values.}
5081 @cindex @option{-gnatwB} (@command{gcc})
5082 This switch suppresses warnings for static fixed-point expressions whose
5083 value is not an exact multiple of Small.
5084
5085 @item -gnatw.b
5086 @emph{Activate warnings on biased representation.}
5087 @cindex @option{-gnatw.b} (@command{gcc})
5088 @cindex Biased representation
5089 This switch activates warnings when a size clause, value size clause, component
5090 clause, or component size clause forces the use of biased representation for an
5091 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5092 to represent 10/11). The default is that such warnings are generated.
5093
5094 @item -gnatw.B
5095 @emph{Suppress warnings on biased representation.}
5096 @cindex @option{-gnatwB} (@command{gcc})
5097 This switch suppresses warnings for representation clauses that force the use
5098 of biased representation.
5099
5100 @item -gnatwc
5101 @emph{Activate warnings on conditionals.}
5102 @cindex @option{-gnatwc} (@command{gcc})
5103 @cindex Conditionals, constant
5104 This switch activates warnings for conditional expressions used in
5105 tests that are known to be True or False at compile time. The default
5106 is that such warnings are not generated.
5107 Note that this warning does
5108 not get issued for the use of boolean variables or constants whose
5109 values are known at compile time, since this is a standard technique
5110 for conditional compilation in Ada, and this would generate too many
5111 false positive warnings.
5112
5113 This warning option also activates a special test for comparisons using
5114 the operators ``>='' and`` <=''.
5115 If the compiler can tell that only the equality condition is possible,
5116 then it will warn that the ``>'' or ``<'' part of the test
5117 is useless and that the operator could be replaced by ``=''.
5118 An example would be comparing a @code{Natural} variable <= 0.
5119
5120 This warning option also generates warnings if
5121 one or both tests is optimized away in a membership test for integer
5122 values if the result can be determined at compile time. Range tests on
5123 enumeration types are not included, since it is common for such tests
5124 to include an end point.
5125
5126 This warning can also be turned on using @option{-gnatwa}.
5127
5128 @item -gnatwC
5129 @emph{Suppress warnings on conditionals.}
5130 @cindex @option{-gnatwC} (@command{gcc})
5131 This switch suppresses warnings for conditional expressions used in
5132 tests that are known to be True or False at compile time.
5133
5134 @item -gnatw.c
5135 @emph{Activate warnings on missing component clauses.}
5136 @cindex @option{-gnatw.c} (@command{gcc})
5137 @cindex Component clause, missing
5138 This switch activates warnings for record components where a record
5139 representation clause is present and has component clauses for the
5140 majority, but not all, of the components. A warning is given for each
5141 component for which no component clause is present.
5142
5143 This warning can also be turned on using @option{-gnatwa}.
5144
5145 @item -gnatw.C
5146 @emph{Suppress warnings on missing component clauses.}
5147 @cindex @option{-gnatwC} (@command{gcc})
5148 This switch suppresses warnings for record components that are
5149 missing a component clause in the situation described above.
5150
5151 @item -gnatwd
5152 @emph{Activate warnings on implicit dereferencing.}
5153 @cindex @option{-gnatwd} (@command{gcc})
5154 If this switch is set, then the use of a prefix of an access type
5155 in an indexed component, slice, or selected component without an
5156 explicit @code{.all} will generate a warning. With this warning
5157 enabled, access checks occur only at points where an explicit
5158 @code{.all} appears in the source code (assuming no warnings are
5159 generated as a result of this switch). The default is that such
5160 warnings are not generated.
5161 Note that @option{-gnatwa} does not affect the setting of
5162 this warning option.
5163
5164 @item -gnatwD
5165 @emph{Suppress warnings on implicit dereferencing.}
5166 @cindex @option{-gnatwD} (@command{gcc})
5167 @cindex Implicit dereferencing
5168 @cindex Dereferencing, implicit
5169 This switch suppresses warnings for implicit dereferences in
5170 indexed components, slices, and selected components.
5171
5172 @item -gnatwe
5173 @emph{Treat warnings as errors.}
5174 @cindex @option{-gnatwe} (@command{gcc})
5175 @cindex Warnings, treat as error
5176 This switch causes warning messages to be treated as errors.
5177 The warning string still appears, but the warning messages are counted
5178 as errors, and prevent the generation of an object file.
5179
5180 @item -gnatw.e
5181 @emph{Activate every optional warning}
5182 @cindex @option{-gnatw.e} (@command{gcc})
5183 @cindex Warnings, activate every optional warning
5184 This switch activates all optional warnings, including those which
5185 are not activated by @code{-gnatwa}.
5186
5187 @item -gnatwf
5188 @emph{Activate warnings on unreferenced formals.}
5189 @cindex @option{-gnatwf} (@command{gcc})
5190 @cindex Formals, unreferenced
5191 This switch causes a warning to be generated if a formal parameter
5192 is not referenced in the body of the subprogram. This warning can
5193 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5194 default is that these warnings are not generated.
5195
5196 @item -gnatwF
5197 @emph{Suppress warnings on unreferenced formals.}
5198 @cindex @option{-gnatwF} (@command{gcc})
5199 This switch suppresses warnings for unreferenced formal
5200 parameters. Note that the
5201 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5202 effect of warning on unreferenced entities other than subprogram
5203 formals.
5204
5205 @item -gnatwg
5206 @emph{Activate warnings on unrecognized pragmas.}
5207 @cindex @option{-gnatwg} (@command{gcc})
5208 @cindex Pragmas, unrecognized
5209 This switch causes a warning to be generated if an unrecognized
5210 pragma is encountered. Apart from issuing this warning, the
5211 pragma is ignored and has no effect. This warning can
5212 also be turned on using @option{-gnatwa}. The default
5213 is that such warnings are issued (satisfying the Ada Reference
5214 Manual requirement that such warnings appear).
5215
5216 @item -gnatwG
5217 @emph{Suppress warnings on unrecognized pragmas.}
5218 @cindex @option{-gnatwG} (@command{gcc})
5219 This switch suppresses warnings for unrecognized pragmas.
5220
5221 @item -gnatwh
5222 @emph{Activate warnings on hiding.}
5223 @cindex @option{-gnatwh} (@command{gcc})
5224 @cindex Hiding of Declarations
5225 This switch activates warnings on hiding declarations.
5226 A declaration is considered hiding
5227 if it is for a non-overloadable entity, and it declares an entity with the
5228 same name as some other entity that is directly or use-visible. The default
5229 is that such warnings are not generated.
5230 Note that @option{-gnatwa} does not affect the setting of this warning option.
5231
5232 @item -gnatwH
5233 @emph{Suppress warnings on hiding.}
5234 @cindex @option{-gnatwH} (@command{gcc})
5235 This switch suppresses warnings on hiding declarations.
5236
5237 @item -gnatwi
5238 @emph{Activate warnings on implementation units.}
5239 @cindex @option{-gnatwi} (@command{gcc})
5240 This switch activates warnings for a @code{with} of an internal GNAT
5241 implementation unit, defined as any unit from the @code{Ada},
5242 @code{Interfaces}, @code{GNAT},
5243 ^^@code{DEC},^ or @code{System}
5244 hierarchies that is not
5245 documented in either the Ada Reference Manual or the GNAT
5246 Programmer's Reference Manual. Such units are intended only
5247 for internal implementation purposes and should not be @code{with}'ed
5248 by user programs. The default is that such warnings are generated
5249 This warning can also be turned on using @option{-gnatwa}.
5250
5251 @item -gnatwI
5252 @emph{Disable warnings on implementation units.}
5253 @cindex @option{-gnatwI} (@command{gcc})
5254 This switch disables warnings for a @code{with} of an internal GNAT
5255 implementation unit.
5256
5257 @item -gnatwj
5258 @emph{Activate warnings on obsolescent features (Annex J).}
5259 @cindex @option{-gnatwj} (@command{gcc})
5260 @cindex Features, obsolescent
5261 @cindex Obsolescent features
5262 If this warning option is activated, then warnings are generated for
5263 calls to subprograms marked with @code{pragma Obsolescent} and
5264 for use of features in Annex J of the Ada Reference Manual. In the
5265 case of Annex J, not all features are flagged. In particular use
5266 of the renamed packages (like @code{Text_IO}) and use of package
5267 @code{ASCII} are not flagged, since these are very common and
5268 would generate many annoying positive warnings. The default is that
5269 such warnings are not generated. This warning is also turned on by
5270 the use of @option{-gnatwa}.
5271
5272 In addition to the above cases, warnings are also generated for
5273 GNAT features that have been provided in past versions but which
5274 have been superseded (typically by features in the new Ada standard).
5275 For example, @code{pragma Ravenscar} will be flagged since its
5276 function is replaced by @code{pragma Profile(Ravenscar)}.
5277
5278 Note that this warning option functions differently from the
5279 restriction @code{No_Obsolescent_Features} in two respects.
5280 First, the restriction applies only to annex J features.
5281 Second, the restriction does flag uses of package @code{ASCII}.
5282
5283 @item -gnatwJ
5284 @emph{Suppress warnings on obsolescent features (Annex J).}
5285 @cindex @option{-gnatwJ} (@command{gcc})
5286 This switch disables warnings on use of obsolescent features.
5287
5288 @item -gnatwk
5289 @emph{Activate warnings on variables that could be constants.}
5290 @cindex @option{-gnatwk} (@command{gcc})
5291 This switch activates warnings for variables that are initialized but
5292 never modified, and then could be declared constants. The default is that
5293 such warnings are not given.
5294 This warning can also be turned on using @option{-gnatwa}.
5295
5296 @item -gnatwK
5297 @emph{Suppress warnings on variables that could be constants.}
5298 @cindex @option{-gnatwK} (@command{gcc})
5299 This switch disables warnings on variables that could be declared constants.
5300
5301 @item -gnatwl
5302 @emph{Activate warnings for elaboration pragmas.}
5303 @cindex @option{-gnatwl} (@command{gcc})
5304 @cindex Elaboration, warnings
5305 This switch activates warnings on missing
5306 @code{Elaborate_All} and @code{Elaborate} pragmas.
5307 See the section in this guide on elaboration checking for details on
5308 when such pragmas should be used. In dynamic elaboration mode, this switch
5309 generations warnings about the need to add elaboration pragmas. Note however,
5310 that if you blindly follow these warnings, and add @code{Elaborate_All}
5311 warnings wherever they are recommended, you basically end up with the
5312 equivalent of the static elaboration model, which may not be what you want for
5313 legacy code for which the static model does not work.
5314
5315 For the static model, the messages generated are labeled "info:" (for
5316 information messages). They are not warnings to add elaboration pragmas,
5317 merely informational messages showing what implicit elaboration pragmas
5318 have been added, for use in analyzing elaboration circularity problems.
5319
5320 Warnings are also generated if you
5321 are using the static mode of elaboration, and a @code{pragma Elaborate}
5322 is encountered. The default is that such warnings
5323 are not generated.
5324 This warning is not automatically turned on by the use of @option{-gnatwa}.
5325
5326 @item -gnatwL
5327 @emph{Suppress warnings for elaboration pragmas.}
5328 @cindex @option{-gnatwL} (@command{gcc})
5329 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5330 See the section in this guide on elaboration checking for details on
5331 when such pragmas should be used.
5332
5333 @item -gnatwm
5334 @emph{Activate warnings on modified but unreferenced variables.}
5335 @cindex @option{-gnatwm} (@command{gcc})
5336 This switch activates warnings for variables that are assigned (using
5337 an initialization value or with one or more assignment statements) but
5338 whose value is never read. The warning is suppressed for volatile
5339 variables and also for variables that are renamings of other variables
5340 or for which an address clause is given.
5341 This warning can also be turned on using @option{-gnatwa}.
5342 The default is that these warnings are not given.
5343
5344 @item -gnatwM
5345 @emph{Disable warnings on modified but unreferenced variables.}
5346 @cindex @option{-gnatwM} (@command{gcc})
5347 This switch disables warnings for variables that are assigned or
5348 initialized, but never read.
5349
5350 @item -gnatw.m
5351 @emph{Activate warnings on suspicious modulus values.}
5352 @cindex @option{-gnatw.m} (@command{gcc})
5353 This switch activates warnings for modulus values that seem suspicious.
5354 The cases caught are where the size is the same as the modulus (e.g.
5355 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5356 with no size clause. The guess in both cases is that 2**x was intended
5357 rather than x. The default is that these warnings are given.
5358
5359 @item -gnatw.M
5360 @emph{Disable warnings on suspicious modulus values.}
5361 @cindex @option{-gnatw.M} (@command{gcc})
5362 This switch disables warnings for suspicious modulus values.
5363
5364 @item -gnatwn
5365 @emph{Set normal warnings mode.}
5366 @cindex @option{-gnatwn} (@command{gcc})
5367 This switch sets normal warning mode, in which enabled warnings are
5368 issued and treated as warnings rather than errors. This is the default
5369 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5370 an explicit @option{-gnatws} or
5371 @option{-gnatwe}. It also cancels the effect of the
5372 implicit @option{-gnatwe} that is activated by the
5373 use of @option{-gnatg}.
5374
5375 @item -gnatwo
5376 @emph{Activate warnings on address clause overlays.}
5377 @cindex @option{-gnatwo} (@command{gcc})
5378 @cindex Address Clauses, warnings
5379 This switch activates warnings for possibly unintended initialization
5380 effects of defining address clauses that cause one variable to overlap
5381 another. The default is that such warnings are generated.
5382 This warning can also be turned on using @option{-gnatwa}.
5383
5384 @item -gnatwO
5385 @emph{Suppress warnings on address clause overlays.}
5386 @cindex @option{-gnatwO} (@command{gcc})
5387 This switch suppresses warnings on possibly unintended initialization
5388 effects of defining address clauses that cause one variable to overlap
5389 another.
5390
5391 @item -gnatw.o
5392 @emph{Activate warnings on modified but unreferenced out parameters.}
5393 @cindex @option{-gnatw.o} (@command{gcc})
5394 This switch activates warnings for variables that are modified by using
5395 them as actuals for a call to a procedure with an out mode formal, where
5396 the resulting assigned value is never read. It is applicable in the case
5397 where there is more than one out mode formal. If there is only one out
5398 mode formal, the warning is issued by default (controlled by -gnatwu).
5399 The warning is suppressed for volatile
5400 variables and also for variables that are renamings of other variables
5401 or for which an address clause is given.
5402 The default is that these warnings are not given. Note that this warning
5403 is not included in -gnatwa, it must be activated explicitly.
5404
5405 @item -gnatw.O
5406 @emph{Disable warnings on modified but unreferenced out parameters.}
5407 @cindex @option{-gnatw.O} (@command{gcc})
5408 This switch suppresses warnings for variables that are modified by using
5409 them as actuals for a call to a procedure with an out mode formal, where
5410 the resulting assigned value is never read.
5411
5412 @item -gnatwp
5413 @emph{Activate warnings on ineffective pragma Inlines.}
5414 @cindex @option{-gnatwp} (@command{gcc})
5415 @cindex Inlining, warnings
5416 This switch activates warnings for failure of front end inlining
5417 (activated by @option{-gnatN}) to inline a particular call. There are
5418 many reasons for not being able to inline a call, including most
5419 commonly that the call is too complex to inline. The default is
5420 that such warnings are not given.
5421 This warning can also be turned on using @option{-gnatwa}.
5422 Warnings on ineffective inlining by the gcc back-end can be activated
5423 separately, using the gcc switch -Winline.
5424
5425 @item -gnatwP
5426 @emph{Suppress warnings on ineffective pragma Inlines.}
5427 @cindex @option{-gnatwP} (@command{gcc})
5428 This switch suppresses warnings on ineffective pragma Inlines. If the
5429 inlining mechanism cannot inline a call, it will simply ignore the
5430 request silently.
5431
5432 @item -gnatw.p
5433 @emph{Activate warnings on parameter ordering.}
5434 @cindex @option{-gnatw.p} (@command{gcc})
5435 @cindex Parameter order, warnings
5436 This switch activates warnings for cases of suspicious parameter
5437 ordering when the list of arguments are all simple identifiers that
5438 match the names of the formals, but are in a different order. The
5439 warning is suppressed if any use of named parameter notation is used,
5440 so this is the appropriate way to suppress a false positive (and
5441 serves to emphasize that the "misordering" is deliberate). The
5442 default is
5443 that such warnings are not given.
5444 This warning can also be turned on using @option{-gnatwa}.
5445
5446 @item -gnatw.P
5447 @emph{Suppress warnings on parameter ordering.}
5448 @cindex @option{-gnatw.P} (@command{gcc})
5449 This switch suppresses warnings on cases of suspicious parameter
5450 ordering.
5451
5452 @item -gnatwq
5453 @emph{Activate warnings on questionable missing parentheses.}
5454 @cindex @option{-gnatwq} (@command{gcc})
5455 @cindex Parentheses, warnings
5456 This switch activates warnings for cases where parentheses are not used and
5457 the result is potential ambiguity from a readers point of view. For example
5458 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5459 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5460 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5461 follow the rule of always parenthesizing to make the association clear, and
5462 this warning switch warns if such parentheses are not present. The default
5463 is that these warnings are given.
5464 This warning can also be turned on using @option{-gnatwa}.
5465
5466 @item -gnatwQ
5467 @emph{Suppress warnings on questionable missing parentheses.}
5468 @cindex @option{-gnatwQ} (@command{gcc})
5469 This switch suppresses warnings for cases where the association is not
5470 clear and the use of parentheses is preferred.
5471
5472 @item -gnatwr
5473 @emph{Activate warnings on redundant constructs.}
5474 @cindex @option{-gnatwr} (@command{gcc})
5475 This switch activates warnings for redundant constructs. The following
5476 is the current list of constructs regarded as redundant:
5477
5478 @itemize @bullet
5479 @item
5480 Assignment of an item to itself.
5481 @item
5482 Type conversion that converts an expression to its own type.
5483 @item
5484 Use of the attribute @code{Base} where @code{typ'Base} is the same
5485 as @code{typ}.
5486 @item
5487 Use of pragma @code{Pack} when all components are placed by a record
5488 representation clause.
5489 @item
5490 Exception handler containing only a reraise statement (raise with no
5491 operand) which has no effect.
5492 @item
5493 Use of the operator abs on an operand that is known at compile time
5494 to be non-negative
5495 @item
5496 Comparison of boolean expressions to an explicit True value.
5497 @end itemize
5498
5499 This warning can also be turned on using @option{-gnatwa}.
5500 The default is that warnings for redundant constructs are not given.
5501
5502 @item -gnatwR
5503 @emph{Suppress warnings on redundant constructs.}
5504 @cindex @option{-gnatwR} (@command{gcc})
5505 This switch suppresses warnings for redundant constructs.
5506
5507 @item -gnatw.r
5508 @emph{Activate warnings for object renaming function.}
5509 @cindex @option{-gnatw.r} (@command{gcc})
5510 This switch activates warnings for an object renaming that renames a
5511 function call, which is equivalent to a constant declaration (as
5512 opposed to renaming the function itself).  The default is that these
5513 warnings are given.  This warning can also be turned on using
5514 @option{-gnatwa}.
5515
5516 @item -gnatw.R
5517 @emph{Suppress warnings for object renaming function.}
5518 @cindex @option{-gnatwT} (@command{gcc})
5519 This switch suppresses warnings for object renaming function.
5520
5521 @item -gnatws
5522 @emph{Suppress all warnings.}
5523 @cindex @option{-gnatws} (@command{gcc})
5524 This switch completely suppresses the
5525 output of all warning messages from the GNAT front end.
5526 Note that it does not suppress warnings from the @command{gcc} back end.
5527 To suppress these back end warnings as well, use the switch @option{-w}
5528 in addition to @option{-gnatws}.
5529
5530 @item -gnatwt
5531 @emph{Activate warnings for tracking of deleted conditional code.}
5532 @cindex @option{-gnatwt} (@command{gcc})
5533 @cindex Deactivated code, warnings
5534 @cindex Deleted code, warnings
5535 This switch activates warnings for tracking of code in conditionals (IF and
5536 CASE statements) that is detected to be dead code which cannot be executed, and
5537 which is removed by the front end. This warning is off by default, and is not
5538 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5539 useful for detecting deactivated code in certified applications.
5540
5541 @item -gnatwT
5542 @emph{Suppress warnings for tracking of deleted conditional code.}
5543 @cindex @option{-gnatwT} (@command{gcc})
5544 This switch suppresses warnings for tracking of deleted conditional code.
5545
5546 @item -gnatwu
5547 @emph{Activate warnings on unused entities.}
5548 @cindex @option{-gnatwu} (@command{gcc})
5549 This switch activates warnings to be generated for entities that
5550 are declared but not referenced, and for units that are @code{with}'ed
5551 and not
5552 referenced. In the case of packages, a warning is also generated if
5553 no entities in the package are referenced. This means that if the package
5554 is referenced but the only references are in @code{use}
5555 clauses or @code{renames}
5556 declarations, a warning is still generated. A warning is also generated
5557 for a generic package that is @code{with}'ed but never instantiated.
5558 In the case where a package or subprogram body is compiled, and there
5559 is a @code{with} on the corresponding spec
5560 that is only referenced in the body,
5561 a warning is also generated, noting that the
5562 @code{with} can be moved to the body. The default is that
5563 such warnings are not generated.
5564 This switch also activates warnings on unreferenced formals
5565 (it includes the effect of @option{-gnatwf}).
5566 This warning can also be turned on using @option{-gnatwa}.
5567
5568 @item -gnatwU
5569 @emph{Suppress warnings on unused entities.}
5570 @cindex @option{-gnatwU} (@command{gcc})
5571 This switch suppresses warnings for unused entities and packages.
5572 It also turns off warnings on unreferenced formals (and thus includes
5573 the effect of @option{-gnatwF}).
5574
5575 @item -gnatwv
5576 @emph{Activate warnings on unassigned variables.}
5577 @cindex @option{-gnatwv} (@command{gcc})
5578 @cindex Unassigned variable warnings
5579 This switch activates warnings for access to variables which
5580 may not be properly initialized. The default is that
5581 such warnings are generated.
5582 This warning can also be turned on using @option{-gnatwa}.
5583
5584 @item -gnatwV
5585 @emph{Suppress warnings on unassigned variables.}
5586 @cindex @option{-gnatwV} (@command{gcc})
5587 This switch suppresses warnings for access to variables which
5588 may not be properly initialized.
5589 For variables of a composite type, the warning can also be suppressed in
5590 Ada 2005 by using a default initialization with a box. For example, if
5591 Table is an array of records whose components are only partially uninitialized,
5592 then the following code:
5593
5594 @smallexample @c ada
5595    Tab : Table := (others => <>);
5596 @end smallexample
5597
5598 will suppress warnings on subsequent statements that access components
5599 of variable Tab.
5600
5601 @item -gnatww
5602 @emph{Activate warnings on wrong low bound assumption.}
5603 @cindex @option{-gnatww} (@command{gcc})
5604 @cindex String indexing warnings
5605 This switch activates warnings for indexing an unconstrained string parameter
5606 with a literal or S'Length. This is a case where the code is assuming that the
5607 low bound is one, which is in general not true (for example when a slice is
5608 passed). The default is that such warnings are generated.
5609 This warning can also be turned on using @option{-gnatwa}.
5610
5611 @item -gnatwW
5612 @emph{Suppress warnings on wrong low bound assumption.}
5613 @cindex @option{-gnatwW} (@command{gcc})
5614 This switch suppresses warnings for indexing an unconstrained string parameter
5615 with a literal or S'Length. Note that this warning can also be suppressed
5616 in a particular case by adding an
5617 assertion that the lower bound is 1,
5618 as shown in the following example.
5619
5620 @smallexample @c ada
5621    procedure K (S : String) is
5622       pragma Assert (S'First = 1);
5623       @dots{}
5624 @end smallexample
5625
5626 @item -gnatw.w
5627 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5628 @cindex @option{-gnatw.w} (@command{gcc})
5629 @cindex Warnings Off control
5630 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5631 where either the pragma is entirely useless (because it suppresses no
5632 warnings), or it could be replaced by @code{pragma Unreferenced} or
5633 @code{pragma Unmodified}.The default is that these warnings are not given.
5634 Note that this warning is not included in -gnatwa, it must be
5635 activated explicitly.
5636
5637 @item -gnatw.W
5638 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5639 @cindex @option{-gnatw.W} (@command{gcc})
5640 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5641
5642 @item -gnatwx
5643 @emph{Activate warnings on Export/Import pragmas.}
5644 @cindex @option{-gnatwx} (@command{gcc})
5645 @cindex Export/Import pragma warnings
5646 This switch activates warnings on Export/Import pragmas when
5647 the compiler detects a possible conflict between the Ada and
5648 foreign language calling sequences. For example, the use of
5649 default parameters in a convention C procedure is dubious
5650 because the C compiler cannot supply the proper default, so
5651 a warning is issued. The default is that such warnings are
5652 generated.
5653 This warning can also be turned on using @option{-gnatwa}.
5654
5655 @item -gnatwX
5656 @emph{Suppress warnings on Export/Import pragmas.}
5657 @cindex @option{-gnatwX} (@command{gcc})
5658 This switch suppresses warnings on Export/Import pragmas.
5659 The sense of this is that you are telling the compiler that
5660 you know what you are doing in writing the pragma, and it
5661 should not complain at you.
5662
5663 @item -gnatw.x
5664 @emph{Activate warnings for No_Exception_Propagation mode.}
5665 @cindex @option{-gnatwm} (@command{gcc})
5666 This switch activates warnings for exception usage when pragma Restrictions
5667 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5668 explicit exception raises which are not covered by a local handler, and for
5669 exception handlers which do not cover a local raise. The default is that these
5670 warnings are not given.
5671
5672 @item -gnatw.X
5673 @emph{Disable warnings for No_Exception_Propagation mode.}
5674 This switch disables warnings for exception usage when pragma Restrictions
5675 (No_Exception_Propagation) is in effect.
5676
5677 @item -gnatwy
5678 @emph{Activate warnings for Ada 2005 compatibility issues.}
5679 @cindex @option{-gnatwy} (@command{gcc})
5680 @cindex Ada 2005 compatibility issues warnings
5681 For the most part Ada 2005 is upwards compatible with Ada 95,
5682 but there are some exceptions (for example the fact that
5683 @code{interface} is now a reserved word in Ada 2005). This
5684 switch activates several warnings to help in identifying
5685 and correcting such incompatibilities. The default is that
5686 these warnings are generated. Note that at one point Ada 2005
5687 was called Ada 0Y, hence the choice of character.
5688 This warning can also be turned on using @option{-gnatwa}.
5689
5690 @item -gnatwY
5691 @emph{Disable warnings for Ada 2005 compatibility issues.}
5692 @cindex @option{-gnatwY} (@command{gcc})
5693 @cindex Ada 2005 compatibility issues warnings
5694 This switch suppresses several warnings intended to help in identifying
5695 incompatibilities between Ada 95 and Ada 2005.
5696
5697 @item -gnatwz
5698 @emph{Activate warnings on unchecked conversions.}
5699 @cindex @option{-gnatwz} (@command{gcc})
5700 @cindex Unchecked_Conversion warnings
5701 This switch activates warnings for unchecked conversions
5702 where the types are known at compile time to have different
5703 sizes. The default
5704 is that such warnings are generated. Warnings are also
5705 generated for subprogram pointers with different conventions,
5706 and, on VMS only, for data pointers with different conventions.
5707 This warning can also be turned on using @option{-gnatwa}.
5708
5709 @item -gnatwZ
5710 @emph{Suppress warnings on unchecked conversions.}
5711 @cindex @option{-gnatwZ} (@command{gcc})
5712 This switch suppresses warnings for unchecked conversions
5713 where the types are known at compile time to have different
5714 sizes or conventions.
5715
5716 @item ^-Wunused^WARNINGS=UNUSED^
5717 @cindex @option{-Wunused}
5718 The warnings controlled by the @option{-gnatw} switch are generated by
5719 the front end of the compiler. The @option{GCC} back end can provide
5720 additional warnings and they are controlled by the @option{-W} switch.
5721 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5722 warnings for entities that are declared but not referenced.
5723
5724 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5725 @cindex @option{-Wuninitialized}
5726 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5727 the back end warning for uninitialized variables. This switch must be
5728 used in conjunction with an optimization level greater than zero.
5729
5730 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5731 @cindex @option{-Wall}
5732 This switch enables all the above warnings from the @option{GCC} back end.
5733 The code generator detects a number of warning situations that are missed
5734 by the @option{GNAT} front end, and this switch can be used to activate them.
5735 The use of this switch also sets the default front end warning mode to
5736 @option{-gnatwa}, that is, most front end warnings activated as well.
5737
5738 @item ^-w^/NO_BACK_END_WARNINGS^
5739 @cindex @option{-w}
5740 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5741 The use of this switch also sets the default front end warning mode to
5742 @option{-gnatws}, that is, front end warnings suppressed as well.
5743
5744 @end table
5745
5746 @noindent
5747 @ifclear vms
5748 A string of warning parameters can be used in the same parameter. For example:
5749
5750 @smallexample
5751 -gnatwaLe
5752 @end smallexample
5753
5754 @noindent
5755 will turn on all optional warnings except for elaboration pragma warnings,
5756 and also specify that warnings should be treated as errors.
5757 @end ifclear
5758 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5759
5760 @table @option
5761 @c !sort!
5762 @item -gnatwC
5763 @item -gnatwD
5764 @item -gnatwF
5765 @item -gnatwg
5766 @item -gnatwH
5767 @item -gnatwi
5768 @item -gnatwJ
5769 @item -gnatwK
5770 @item -gnatwL
5771 @item -gnatwM
5772 @item -gnatwn
5773 @item -gnatwo
5774 @item -gnatwP
5775 @item -gnatwR
5776 @item -gnatwU
5777 @item -gnatwv
5778 @item -gnatwz
5779 @item -gnatwx
5780
5781 @end table
5782
5783 @node Debugging and Assertion Control
5784 @subsection Debugging and Assertion Control
5785
5786 @table @option
5787 @item -gnata
5788 @cindex @option{-gnata} (@command{gcc})
5789 @findex Assert
5790 @findex Debug
5791 @cindex Assertions
5792
5793 @noindent
5794 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5795 are ignored. This switch, where @samp{a} stands for assert, causes
5796 @code{Assert} and @code{Debug} pragmas to be activated.
5797
5798 The pragmas have the form:
5799
5800 @smallexample
5801 @cartouche
5802    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5803                       @var{static-string-expression}@r{]})
5804    @b{pragma} Debug (@var{procedure call})
5805 @end cartouche
5806 @end smallexample
5807
5808 @noindent
5809 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5810 If the result is @code{True}, the pragma has no effect (other than
5811 possible side effects from evaluating the expression). If the result is
5812 @code{False}, the exception @code{Assert_Failure} declared in the package
5813 @code{System.Assertions} is
5814 raised (passing @var{static-string-expression}, if present, as the
5815 message associated with the exception). If no string expression is
5816 given the default is a string giving the file name and line number
5817 of the pragma.
5818
5819 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5820 @code{pragma Debug} may appear within a declaration sequence, allowing
5821 debugging procedures to be called between declarations.
5822
5823 @ifset vms
5824 @item /DEBUG@r{[}=debug-level@r{]}
5825 @itemx  /NODEBUG
5826 Specifies how much debugging information is to be included in
5827 the resulting object file where 'debug-level' is one of the following:
5828 @table @code
5829 @item   TRACEBACK
5830 Include both debugger symbol records and traceback
5831 the object file.
5832 This is the default setting.
5833 @item   ALL
5834 Include both debugger symbol records and traceback in
5835 object file.
5836 @item   NONE
5837 Excludes both debugger symbol records and traceback
5838 the object file. Same as /NODEBUG.
5839 @item   SYMBOLS
5840 Includes only debugger symbol records in the object
5841 file. Note that this doesn't include traceback information.
5842 @end table
5843 @end ifset
5844 @end table
5845
5846 @node Validity Checking
5847 @subsection Validity Checking
5848 @findex Validity Checking
5849
5850 @noindent
5851 The Ada Reference Manual has specific requirements for checking
5852 for invalid values. In particular, RM 13.9.1 requires that the
5853 evaluation of invalid values (for example from unchecked conversions),
5854 not result in erroneous execution. In GNAT, the result of such an
5855 evaluation in normal default mode is to either use the value
5856 unmodified, or to raise Constraint_Error in those cases where use
5857 of the unmodified value would cause erroneous execution. The cases
5858 where unmodified values might lead to erroneous execution are case
5859 statements (where a wild jump might result from an invalid value),
5860 and subscripts on the left hand side (where memory corruption could
5861 occur as a result of an invalid value).
5862
5863 The @option{-gnatB} switch tells the compiler to assume that all
5864 values are valid (that is, within their declared subtype range)
5865 except in the context of a use of the Valid attribute. This means
5866 the compiler can generate more efficient code, since the range
5867 of values is better known at compile time.
5868
5869 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5870 checking mode.
5871 @ifclear vms
5872 The @code{x} argument is a string of letters that
5873 indicate validity checks that are performed or not performed in addition
5874 to the default checks described above.
5875 @end ifclear
5876 @ifset vms
5877 The options allowed for this qualifier
5878 indicate validity checks that are performed or not performed in addition
5879 to the default checks described above.
5880 @end ifset
5881
5882 @table @option
5883 @c !sort!
5884 @item -gnatVa
5885 @emph{All validity checks.}
5886 @cindex @option{-gnatVa} (@command{gcc})
5887 All validity checks are turned on.
5888 @ifclear vms
5889 That is, @option{-gnatVa} is
5890 equivalent to @option{gnatVcdfimorst}.
5891 @end ifclear
5892
5893 @item -gnatVc
5894 @emph{Validity checks for copies.}
5895 @cindex @option{-gnatVc} (@command{gcc})
5896 The right hand side of assignments, and the initializing values of
5897 object declarations are validity checked.
5898
5899 @item -gnatVd
5900 @emph{Default (RM) validity checks.}
5901 @cindex @option{-gnatVd} (@command{gcc})
5902 Some validity checks are done by default following normal Ada semantics
5903 (RM 13.9.1 (9-11)).
5904 A check is done in case statements that the expression is within the range
5905 of the subtype. If it is not, Constraint_Error is raised.
5906 For assignments to array components, a check is done that the expression used
5907 as index is within the range. If it is not, Constraint_Error is raised.
5908 Both these validity checks may be turned off using switch @option{-gnatVD}.
5909 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5910 switch @option{-gnatVd} will leave the checks turned on.
5911 Switch @option{-gnatVD} should be used only if you are sure that all such
5912 expressions have valid values. If you use this switch and invalid values
5913 are present, then the program is erroneous, and wild jumps or memory
5914 overwriting may occur.
5915
5916 @item -gnatVe
5917 @emph{Validity checks for elementary components.}
5918 @cindex @option{-gnatVe} (@command{gcc})
5919 In the absence of this switch, assignments to record or array components are
5920 not validity checked, even if validity checks for assignments generally
5921 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5922 require valid data, but assignment of individual components does. So for
5923 example, there is a difference between copying the elements of an array with a
5924 slice assignment, compared to assigning element by element in a loop. This
5925 switch allows you to turn off validity checking for components, even when they
5926 are assigned component by component.
5927
5928 @item -gnatVf
5929 @emph{Validity checks for floating-point values.}
5930 @cindex @option{-gnatVf} (@command{gcc})
5931 In the absence of this switch, validity checking occurs only for discrete
5932 values. If @option{-gnatVf} is specified, then validity checking also applies
5933 for floating-point values, and NaNs and infinities are considered invalid,
5934 as well as out of range values for constrained types. Note that this means
5935 that standard IEEE infinity mode is not allowed. The exact contexts
5936 in which floating-point values are checked depends on the setting of other
5937 options. For example,
5938 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5939 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5940 (the order does not matter) specifies that floating-point parameters of mode
5941 @code{in} should be validity checked.
5942
5943 @item -gnatVi
5944 @emph{Validity checks for @code{in} mode parameters}
5945 @cindex @option{-gnatVi} (@command{gcc})
5946 Arguments for parameters of mode @code{in} are validity checked in function
5947 and procedure calls at the point of call.
5948
5949 @item -gnatVm
5950 @emph{Validity checks for @code{in out} mode parameters.}
5951 @cindex @option{-gnatVm} (@command{gcc})
5952 Arguments for parameters of mode @code{in out} are validity checked in
5953 procedure calls at the point of call. The @code{'m'} here stands for
5954 modify, since this concerns parameters that can be modified by the call.
5955 Note that there is no specific option to test @code{out} parameters,
5956 but any reference within the subprogram will be tested in the usual
5957 manner, and if an invalid value is copied back, any reference to it
5958 will be subject to validity checking.
5959
5960 @item -gnatVn
5961 @emph{No validity checks.}
5962 @cindex @option{-gnatVn} (@command{gcc})
5963 This switch turns off all validity checking, including the default checking
5964 for case statements and left hand side subscripts. Note that the use of
5965 the switch @option{-gnatp} suppresses all run-time checks, including
5966 validity checks, and thus implies @option{-gnatVn}. When this switch
5967 is used, it cancels any other @option{-gnatV} previously issued.
5968
5969 @item -gnatVo
5970 @emph{Validity checks for operator and attribute operands.}
5971 @cindex @option{-gnatVo} (@command{gcc})
5972 Arguments for predefined operators and attributes are validity checked.
5973 This includes all operators in package @code{Standard},
5974 the shift operators defined as intrinsic in package @code{Interfaces}
5975 and operands for attributes such as @code{Pos}. Checks are also made
5976 on individual component values for composite comparisons, and on the
5977 expressions in type conversions and qualified expressions. Checks are
5978 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5979
5980 @item -gnatVp
5981 @emph{Validity checks for parameters.}
5982 @cindex @option{-gnatVp} (@command{gcc})
5983 This controls the treatment of parameters within a subprogram (as opposed
5984 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5985 of parameters on a call. If either of these call options is used, then
5986 normally an assumption is made within a subprogram that the input arguments
5987 have been validity checking at the point of call, and do not need checking
5988 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5989 is not made, and parameters are not assumed to be valid, so their validity
5990 will be checked (or rechecked) within the subprogram.
5991
5992 @item -gnatVr
5993 @emph{Validity checks for function returns.}
5994 @cindex @option{-gnatVr} (@command{gcc})
5995 The expression in @code{return} statements in functions is validity
5996 checked.
5997
5998 @item -gnatVs
5999 @emph{Validity checks for subscripts.}
6000 @cindex @option{-gnatVs} (@command{gcc})
6001 All subscripts expressions are checked for validity, whether they appear
6002 on the right side or left side (in default mode only left side subscripts
6003 are validity checked).
6004
6005 @item -gnatVt
6006 @emph{Validity checks for tests.}
6007 @cindex @option{-gnatVt} (@command{gcc})
6008 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6009 statements are checked, as well as guard expressions in entry calls.
6010
6011 @end table
6012
6013 @noindent
6014 The @option{-gnatV} switch may be followed by
6015 ^a string of letters^a list of options^
6016 to turn on a series of validity checking options.
6017 For example,
6018 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6019 specifies that in addition to the default validity checking, copies and
6020 function return expressions are to be validity checked.
6021 In order to make it easier
6022 to specify the desired combination of effects,
6023 @ifclear vms
6024 the upper case letters @code{CDFIMORST} may
6025 be used to turn off the corresponding lower case option.
6026 @end ifclear
6027 @ifset vms
6028 the prefix @code{NO} on an option turns off the corresponding validity
6029 checking:
6030 @itemize @bullet
6031 @item @code{NOCOPIES}
6032 @item @code{NODEFAULT}
6033 @item @code{NOFLOATS}
6034 @item @code{NOIN_PARAMS}
6035 @item @code{NOMOD_PARAMS}
6036 @item @code{NOOPERANDS}
6037 @item @code{NORETURNS}
6038 @item @code{NOSUBSCRIPTS}
6039 @item @code{NOTESTS}
6040 @end itemize
6041 @end ifset
6042 Thus
6043 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6044 turns on all validity checking options except for
6045 checking of @code{@b{in out}} procedure arguments.
6046
6047 The specification of additional validity checking generates extra code (and
6048 in the case of @option{-gnatVa} the code expansion can be substantial).
6049 However, these additional checks can be very useful in detecting
6050 uninitialized variables, incorrect use of unchecked conversion, and other
6051 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6052 is useful in conjunction with the extra validity checking, since this
6053 ensures that wherever possible uninitialized variables have invalid values.
6054
6055 See also the pragma @code{Validity_Checks} which allows modification of
6056 the validity checking mode at the program source level, and also allows for
6057 temporary disabling of validity checks.
6058
6059 @node Style Checking
6060 @subsection Style Checking
6061 @findex Style checking
6062
6063 @noindent
6064 The @option{-gnaty^x^(option,option,@dots{})^} switch
6065 @cindex @option{-gnaty} (@command{gcc})
6066 causes the compiler to
6067 enforce specified style rules. A limited set of style rules has been used
6068 in writing the GNAT sources themselves. This switch allows user programs
6069 to activate all or some of these checks. If the source program fails a
6070 specified style check, an appropriate warning message is given, preceded by
6071 the character sequence ``(style)''.
6072 @ifset vms
6073 @code{(option,option,@dots{})} is a sequence of keywords
6074 @end ifset
6075 @ifclear vms
6076 The string @var{x} is a sequence of letters or digits
6077 @end ifclear
6078 indicating the particular style
6079 checks to be performed. The following checks are defined:
6080
6081 @table @option
6082 @c !sort!
6083 @item 0-9
6084 @emph{Specify indentation level.}
6085 If a digit from 1-9 appears
6086 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6087 then proper indentation is checked, with the digit indicating the
6088 indentation level required. A value of zero turns off this style check.
6089 The general style of required indentation is as specified by
6090 the examples in the Ada Reference Manual. Full line comments must be
6091 aligned with the @code{--} starting on a column that is a multiple of
6092 the alignment level, or they may be aligned the same way as the following
6093 non-blank line (this is useful when full line comments appear in the middle
6094 of a statement.
6095
6096 @item ^a^ATTRIBUTE^
6097 @emph{Check attribute casing.}
6098 Attribute names, including the case of keywords such as @code{digits}
6099 used as attributes names, must be written in mixed case, that is, the
6100 initial letter and any letter following an underscore must be uppercase.
6101 All other letters must be lowercase.
6102
6103 @item ^A^ARRAY_INDEXES^
6104 @emph{Use of array index numbers in array attributes.}
6105 When using the array attributes First, Last, Range,
6106 or Length, the index number must be omitted for one-dimensional arrays
6107 and is required for multi-dimensional arrays.
6108
6109 @item ^b^BLANKS^
6110 @emph{Blanks not allowed at statement end.}
6111 Trailing blanks are not allowed at the end of statements. The purpose of this
6112 rule, together with h (no horizontal tabs), is to enforce a canonical format
6113 for the use of blanks to separate source tokens.
6114
6115 @item ^c^COMMENTS^
6116 @emph{Check comments.}
6117 Comments must meet the following set of rules:
6118
6119 @itemize @bullet
6120
6121 @item
6122 The ``@code{--}'' that starts the column must either start in column one,
6123 or else at least one blank must precede this sequence.
6124
6125 @item
6126 Comments that follow other tokens on a line must have at least one blank
6127 following the ``@code{--}'' at the start of the comment.
6128
6129 @item
6130 Full line comments must have two blanks following the ``@code{--}'' that
6131 starts the comment, with the following exceptions.
6132
6133 @item
6134 A line consisting only of the ``@code{--}'' characters, possibly preceded
6135 by blanks is permitted.
6136
6137 @item
6138 A comment starting with ``@code{--x}'' where @code{x} is a special character
6139 is permitted.
6140 This allows proper processing of the output generated by specialized tools
6141 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6142 annotation
6143 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6144 special character is defined as being in one of the ASCII ranges
6145 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6146 Note that this usage is not permitted
6147 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6148
6149 @item
6150 A line consisting entirely of minus signs, possibly preceded by blanks, is
6151 permitted. This allows the construction of box comments where lines of minus
6152 signs are used to form the top and bottom of the box.
6153
6154 @item
6155 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6156 least one blank follows the initial ``@code{--}''. Together with the preceding
6157 rule, this allows the construction of box comments, as shown in the following
6158 example:
6159 @smallexample
6160 ---------------------------
6161 -- This is a box comment --
6162 -- with two text lines.  --
6163 ---------------------------
6164 @end smallexample
6165 @end itemize
6166
6167 @item ^d^DOS_LINE_ENDINGS^
6168 @emph{Check no DOS line terminators present.}
6169 All lines must be terminated by a single ASCII.LF
6170 character (in particular the DOS line terminator sequence CR/LF is not
6171 allowed).
6172
6173 @item ^e^END^
6174 @emph{Check end/exit labels.}
6175 Optional labels on @code{end} statements ending subprograms and on
6176 @code{exit} statements exiting named loops, are required to be present.
6177
6178 @item ^f^VTABS^
6179 @emph{No form feeds or vertical tabs.}
6180 Neither form feeds nor vertical tab characters are permitted
6181 in the source text.
6182
6183 @item ^g^GNAT^
6184 @emph{GNAT style mode}
6185 The set of style check switches is set to match that used by the GNAT sources.
6186 This may be useful when developing code that is eventually intended to be
6187 incorporated into GNAT. For further details, see GNAT sources.
6188
6189 @item ^h^HTABS^
6190 @emph{No horizontal tabs.}
6191 Horizontal tab characters are not permitted in the source text.
6192 Together with the b (no blanks at end of line) check, this
6193 enforces a canonical form for the use of blanks to separate
6194 source tokens.
6195
6196 @item ^i^IF_THEN^
6197 @emph{Check if-then layout.}
6198 The keyword @code{then} must appear either on the same
6199 line as corresponding @code{if}, or on a line on its own, lined
6200 up under the @code{if} with at least one non-blank line in between
6201 containing all or part of the condition to be tested.
6202
6203 @item ^I^IN_MODE^
6204 @emph{check mode IN keywords}
6205 Mode @code{in} (the default mode) is not
6206 allowed to be given explicitly. @code{in out} is fine,
6207 but not @code{in} on its own.
6208
6209 @item ^k^KEYWORD^
6210 @emph{Check keyword casing.}
6211 All keywords must be in lower case (with the exception of keywords
6212 such as @code{digits} used as attribute names to which this check
6213 does not apply).
6214
6215 @item ^l^LAYOUT^
6216 @emph{Check layout.}
6217 Layout of statement and declaration constructs must follow the
6218 recommendations in the Ada Reference Manual, as indicated by the
6219 form of the syntax rules. For example an @code{else} keyword must
6220 be lined up with the corresponding @code{if} keyword.
6221
6222 There are two respects in which the style rule enforced by this check
6223 option are more liberal than those in the Ada Reference Manual. First
6224 in the case of record declarations, it is permissible to put the
6225 @code{record} keyword on the same line as the @code{type} keyword, and
6226 then the @code{end} in @code{end record} must line up under @code{type}.
6227 This is also permitted when the type declaration is split on two lines.
6228 For example, any of the following three layouts is acceptable:
6229
6230 @smallexample @c ada
6231 @cartouche
6232 type q is record
6233    a : integer;
6234    b : integer;
6235 end record;
6236
6237 type q is
6238    record
6239       a : integer;
6240       b : integer;
6241    end record;
6242
6243 type q is
6244    record
6245       a : integer;
6246       b : integer;
6247 end record;
6248
6249 @end cartouche
6250 @end smallexample
6251
6252 @noindent
6253 Second, in the case of a block statement, a permitted alternative
6254 is to put the block label on the same line as the @code{declare} or
6255 @code{begin} keyword, and then line the @code{end} keyword up under
6256 the block label. For example both the following are permitted:
6257
6258 @smallexample @c ada
6259 @cartouche
6260 Block : declare
6261    A : Integer := 3;
6262 begin
6263    Proc (A, A);
6264 end Block;
6265
6266 Block :
6267    declare
6268       A : Integer := 3;
6269    begin
6270       Proc (A, A);
6271    end Block;
6272 @end cartouche
6273 @end smallexample
6274
6275 @noindent
6276 The same alternative format is allowed for loops. For example, both of
6277 the following are permitted:
6278
6279 @smallexample @c ada
6280 @cartouche
6281 Clear : while J < 10 loop
6282    A (J) := 0;
6283 end loop Clear;
6284
6285 Clear :
6286    while J < 10 loop
6287       A (J) := 0;
6288    end loop Clear;
6289 @end cartouche
6290 @end smallexample
6291
6292 @item ^Lnnn^MAX_NESTING=nnn^
6293 @emph{Set maximum nesting level}
6294 The maximum level of nesting of constructs (including subprograms, loops,
6295 blocks, packages, and conditionals) may not exceed the given value
6296 @option{nnn}. A value of zero disconnects this style check.
6297
6298 @item ^m^LINE_LENGTH^
6299 @emph{Check maximum line length.}
6300 The length of source lines must not exceed 79 characters, including
6301 any trailing blanks. The value of 79 allows convenient display on an
6302 80 character wide device or window, allowing for possible special
6303 treatment of 80 character lines. Note that this count is of
6304 characters in the source text. This means that a tab character counts
6305 as one character in this count but a wide character sequence counts as
6306 a single character (however many bytes are needed in the encoding).
6307
6308 @item ^Mnnn^MAX_LENGTH=nnn^
6309 @emph{Set maximum line length.}
6310 The length of lines must not exceed the
6311 given value @option{nnn}. The maximum value that can be specified is 32767.
6312
6313 @item ^n^STANDARD_CASING^
6314 @emph{Check casing of entities in Standard.}
6315 Any identifier from Standard must be cased
6316 to match the presentation in the Ada Reference Manual (for example,
6317 @code{Integer} and @code{ASCII.NUL}).
6318
6319 @item ^N^NONE^
6320 @emph{Turn off all style checks}
6321 All style check options are turned off.
6322
6323 @item ^o^ORDERED_SUBPROGRAMS^
6324 @emph{Check order of subprogram bodies.}
6325 All subprogram bodies in a given scope
6326 (e.g.@: a package body) must be in alphabetical order. The ordering
6327 rule uses normal Ada rules for comparing strings, ignoring casing
6328 of letters, except that if there is a trailing numeric suffix, then
6329 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6330 before Junk10).
6331
6332 @item ^O^OVERRIDING_INDICATORS^
6333 @emph{Check that overriding subprograms are explicitly marked as such.}
6334 The declaration of a primitive operation of a type extension that overrides
6335 an inherited operation must carry an overriding indicator.
6336
6337 @item ^p^PRAGMA^
6338 @emph{Check pragma casing.}
6339 Pragma names must be written in mixed case, that is, the
6340 initial letter and any letter following an underscore must be uppercase.
6341 All other letters must be lowercase.
6342
6343 @item ^r^REFERENCES^
6344 @emph{Check references.}
6345 All identifier references must be cased in the same way as the
6346 corresponding declaration. No specific casing style is imposed on
6347 identifiers. The only requirement is for consistency of references
6348 with declarations.
6349
6350 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6351 @emph{Check no statements after THEN/ELSE.}
6352 No statements are allowed
6353 on the same line as a THEN or ELSE keyword following the
6354 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6355 and a special exception allows a pragma to appear after ELSE.
6356
6357 @item ^s^SPECS^
6358 @emph{Check separate specs.}
6359 Separate declarations (``specs'') are required for subprograms (a
6360 body is not allowed to serve as its own declaration). The only
6361 exception is that parameterless library level procedures are
6362 not required to have a separate declaration. This exception covers
6363 the most frequent form of main program procedures.
6364
6365 @item ^t^TOKEN^
6366 @emph{Check token spacing.}
6367 The following token spacing rules are enforced:
6368
6369 @itemize @bullet
6370
6371 @item
6372 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6373
6374 @item
6375 The token @code{=>} must be surrounded by spaces.
6376
6377 @item
6378 The token @code{<>} must be preceded by a space or a left parenthesis.
6379
6380 @item
6381 Binary operators other than @code{**} must be surrounded by spaces.
6382 There is no restriction on the layout of the @code{**} binary operator.
6383
6384 @item
6385 Colon must be surrounded by spaces.
6386
6387 @item
6388 Colon-equal (assignment, initialization) must be surrounded by spaces.
6389
6390 @item
6391 Comma must be the first non-blank character on the line, or be
6392 immediately preceded by a non-blank character, and must be followed
6393 by a space.
6394
6395 @item
6396 If the token preceding a left parenthesis ends with a letter or digit, then
6397 a space must separate the two tokens.
6398
6399 @item
6400 A right parenthesis must either be the first non-blank character on
6401 a line, or it must be preceded by a non-blank character.
6402
6403 @item
6404 A semicolon must not be preceded by a space, and must not be followed by
6405 a non-blank character.
6406
6407 @item
6408 A unary plus or minus may not be followed by a space.
6409
6410 @item
6411 A vertical bar must be surrounded by spaces.
6412 @end itemize
6413
6414 @item ^u^UNNECESSARY_BLANK_LINES^
6415 @emph{Check unnecessary blank lines.}
6416 Unnecessary blank lines are not allowed. A blank line is considered
6417 unnecessary if it appears at the end of the file, or if more than
6418 one blank line occurs in sequence.
6419
6420 @item ^x^XTRA_PARENS^
6421 @emph{Check extra parentheses.}
6422 Unnecessary extra level of parentheses (C-style) are not allowed
6423 around conditions in @code{if} statements, @code{while} statements and
6424 @code{exit} statements.
6425
6426 @item ^y^ALL_BUILTIN^
6427 @emph{Set all standard style check options}
6428 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6429 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6430 @option{-gnatyS}, @option{-gnatyLnnn},
6431 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6432
6433 @ifclear vms
6434 @item -
6435 @emph{Remove style check options}
6436 This causes any subsequent options in the string to act as canceling the
6437 corresponding style check option. To cancel maximum nesting level control,
6438 use @option{L} parameter witout any integer value after that, because any
6439 digit following @option{-} in the parameter string of the @option{-gnaty}
6440 option will be threated as canceling indentation check. The same is true
6441 for @option{M} parameter. @option{y} and @option{N} parameters are not
6442 allowed after @option{-}.
6443
6444 @item +
6445 This causes any subsequent options in the string to enable the corresponding
6446 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6447 if any.
6448 @end ifclear
6449
6450 @ifset vms
6451 @item NOxxx
6452 @emph{Removing style check options}
6453 If the name of a style check is preceded by @option{NO} then the corresponding
6454 style check is turned off. For example @option{NOCOMMENTS} turns off style
6455 checking for comments.
6456 @end ifset
6457 @end table
6458
6459 @noindent
6460 In the above rules, appearing in column one is always permitted, that is,
6461 counts as meeting either a requirement for a required preceding space,
6462 or as meeting a requirement for no preceding space.
6463
6464 Appearing at the end of a line is also always permitted, that is, counts
6465 as meeting either a requirement for a following space, or as meeting
6466 a requirement for no following space.
6467
6468 @noindent
6469 If any of these style rules is violated, a message is generated giving
6470 details on the violation. The initial characters of such messages are
6471 always ``@code{(style)}''. Note that these messages are treated as warning
6472 messages, so they normally do not prevent the generation of an object
6473 file. The @option{-gnatwe} switch can be used to treat warning messages,
6474 including style messages, as fatal errors.
6475
6476 The switch
6477 @ifclear vms
6478 @option{-gnaty} on its own (that is not
6479 followed by any letters or digits), then the effect is equivalent
6480 to the use of @option{-gnatyy}, as described above, that is all
6481 built-in standard style check options are enabled.
6482
6483 @end ifclear
6484 @ifset vms
6485 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6486 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6487 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6488 @end ifset
6489
6490
6491
6492 The switch
6493 @ifclear vms
6494 @option{-gnatyN}
6495 @end ifclear
6496 @ifset vms
6497 /STYLE_CHECKS=NONE
6498 @end ifset
6499 clears any previously set style checks.
6500
6501 @node Run-Time Checks
6502 @subsection Run-Time Checks
6503 @cindex Division by zero
6504 @cindex Access before elaboration
6505 @cindex Checks, division by zero
6506 @cindex Checks, access before elaboration
6507 @cindex Checks, stack overflow checking
6508
6509 @noindent
6510 By default, the following checks are suppressed: integer overflow
6511 checks, stack overflow checks, and checks for access before
6512 elaboration on subprogram calls. All other checks, including range
6513 checks and array bounds checks, are turned on by default. The
6514 following @command{gcc} switches refine this default behavior.
6515
6516 @table @option
6517 @c !sort!
6518 @item -gnatp
6519 @cindex @option{-gnatp} (@command{gcc})
6520 @cindex Suppressing checks
6521 @cindex Checks, suppressing
6522 @findex Suppress
6523 This switch causes the unit to be compiled
6524 as though @code{pragma Suppress (All_checks)}
6525 had been present in the source. Validity checks are also eliminated (in
6526 other words @option{-gnatp} also implies @option{-gnatVn}.
6527 Use this switch to improve the performance
6528 of the code at the expense of safety in the presence of invalid data or
6529 program bugs.
6530
6531 Note that when checks are suppressed, the compiler is allowed, but not
6532 required, to omit the checking code. If the run-time cost of the
6533 checking code is zero or near-zero, the compiler will generate it even
6534 if checks are suppressed. In particular, if the compiler can prove
6535 that a certain check will necessarily fail, it will generate code to
6536 do an unconditional ``raise'', even if checks are suppressed. The
6537 compiler warns in this case. Another case in which checks may not be
6538 eliminated is when they are embedded in certain run time routines such
6539 as math library routines.
6540
6541 Of course, run-time checks are omitted whenever the compiler can prove
6542 that they will not fail, whether or not checks are suppressed.
6543
6544 Note that if you suppress a check that would have failed, program
6545 execution is erroneous, which means the behavior is totally
6546 unpredictable. The program might crash, or print wrong answers, or
6547 do anything else. It might even do exactly what you wanted it to do
6548 (and then it might start failing mysteriously next week or next
6549 year). The compiler will generate code based on the assumption that
6550 the condition being checked is true, which can result in disaster if
6551 that assumption is wrong.
6552
6553 @item -gnato
6554 @cindex @option{-gnato} (@command{gcc})
6555 @cindex Overflow checks
6556 @cindex Check, overflow
6557 Enables overflow checking for integer operations.
6558 This causes GNAT to generate slower and larger executable
6559 programs by adding code to check for overflow (resulting in raising
6560 @code{Constraint_Error} as required by standard Ada
6561 semantics). These overflow checks correspond to situations in which
6562 the true value of the result of an operation may be outside the base
6563 range of the result type. The following example shows the distinction:
6564
6565 @smallexample @c ada
6566 X1 : Integer := "Integer'Last";
6567 X2 : Integer range 1 .. 5 := "5";
6568 X3 : Integer := "Integer'Last";
6569 X4 : Integer range 1 .. 5 := "5";
6570 F  : Float := "2.0E+20";
6571 @dots{}
6572 X1 := X1 + 1;
6573 X2 := X2 + 1;
6574 X3 := Integer (F);
6575 X4 := Integer (F);
6576 @end smallexample
6577
6578 @noindent
6579 Note that if explicit values are assigned at compile time, the
6580 compiler may be able to detect overflow at compile time, in which case
6581 no actual run-time checking code is required, and Constraint_Error
6582 will be raised unconditionally, with or without
6583 @option{-gnato}. That's why the assigned values in the above fragment
6584 are in quotes, the meaning is "assign a value not known to the
6585 compiler that happens to be equal to ...". The remaining discussion
6586 assumes that the compiler cannot detect the values at compile time.
6587
6588 Here the first addition results in a value that is outside the base range
6589 of Integer, and hence requires an overflow check for detection of the
6590 constraint error. Thus the first assignment to @code{X1} raises a
6591 @code{Constraint_Error} exception only if @option{-gnato} is set.
6592
6593 The second increment operation results in a violation of the explicit
6594 range constraint; such range checks are performed by default, and are
6595 unaffected by @option{-gnato}.
6596
6597 The two conversions of @code{F} both result in values that are outside
6598 the base range of type @code{Integer} and thus will raise
6599 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6600 The fact that the result of the second conversion is assigned to
6601 variable @code{X4} with a restricted range is irrelevant, since the problem
6602 is in the conversion, not the assignment.
6603
6604 Basically the rule is that in the default mode (@option{-gnato} not
6605 used), the generated code assures that all integer variables stay
6606 within their declared ranges, or within the base range if there is
6607 no declared range. This prevents any serious problems like indexes
6608 out of range for array operations.
6609
6610 What is not checked in default mode is an overflow that results in
6611 an in-range, but incorrect value. In the above example, the assignments
6612 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6613 range of the target variable, but the result is wrong in the sense that
6614 it is too large to be represented correctly. Typically the assignment
6615 to @code{X1} will result in wrap around to the largest negative number.
6616 The conversions of @code{F} will result in some @code{Integer} value
6617 and if that integer value is out of the @code{X4} range then the
6618 subsequent assignment would generate an exception.
6619
6620 @findex Machine_Overflows
6621 Note that the @option{-gnato} switch does not affect the code generated
6622 for any floating-point operations; it applies only to integer
6623 semantics).
6624 For floating-point, GNAT has the @code{Machine_Overflows}
6625 attribute set to @code{False} and the normal mode of operation is to
6626 generate IEEE NaN and infinite values on overflow or invalid operations
6627 (such as dividing 0.0 by 0.0).
6628
6629 The reason that we distinguish overflow checking from other kinds of
6630 range constraint checking is that a failure of an overflow check, unlike
6631 for example the failure of a range check, can result in an incorrect
6632 value, but cannot cause random memory destruction (like an out of range
6633 subscript), or a wild jump (from an out of range case value). Overflow
6634 checking is also quite expensive in time and space, since in general it
6635 requires the use of double length arithmetic.
6636
6637 Note again that @option{-gnato} is off by default, so overflow checking is
6638 not performed in default mode. This means that out of the box, with the
6639 default settings, GNAT does not do all the checks expected from the
6640 language description in the Ada Reference Manual. If you want all constraint
6641 checks to be performed, as described in this Manual, then you must
6642 explicitly use the -gnato switch either on the @command{gnatmake} or
6643 @command{gcc} command.
6644
6645 @item -gnatE
6646 @cindex @option{-gnatE} (@command{gcc})
6647 @cindex Elaboration checks
6648 @cindex Check, elaboration
6649 Enables dynamic checks for access-before-elaboration
6650 on subprogram calls and generic instantiations.
6651 Note that @option{-gnatE} is not necessary for safety, because in the
6652 default mode, GNAT ensures statically that the checks would not fail.
6653 For full details of the effect and use of this switch,
6654 @xref{Compiling Using gcc}.
6655
6656 @item -fstack-check
6657 @cindex @option{-fstack-check} (@command{gcc})
6658 @cindex Stack Overflow Checking
6659 @cindex Checks, stack overflow checking
6660 Activates stack overflow checking. For full details of the effect and use of
6661 this switch see @ref{Stack Overflow Checking}.
6662 @end table
6663
6664 @findex Unsuppress
6665 @noindent
6666 The setting of these switches only controls the default setting of the
6667 checks. You may modify them using either @code{Suppress} (to remove
6668 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6669 the program source.
6670
6671 @node Using gcc for Syntax Checking
6672 @subsection Using @command{gcc} for Syntax Checking
6673 @table @option
6674 @item -gnats
6675 @cindex @option{-gnats} (@command{gcc})
6676 @ifclear vms
6677
6678 @noindent
6679 The @code{s} stands for ``syntax''.
6680 @end ifclear
6681
6682 Run GNAT in syntax checking only mode. For
6683 example, the command
6684
6685 @smallexample
6686 $ gcc -c -gnats x.adb
6687 @end smallexample
6688
6689 @noindent
6690 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6691 series of files in a single command
6692 @ifclear vms
6693 , and can use wild cards to specify such a group of files.
6694 Note that you must specify the @option{-c} (compile
6695 only) flag in addition to the @option{-gnats} flag.
6696 @end ifclear
6697 .
6698 You may use other switches in conjunction with @option{-gnats}. In
6699 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6700 format of any generated error messages.
6701
6702 When the source file is empty or contains only empty lines and/or comments,
6703 the output is a warning:
6704
6705 @smallexample
6706 $ gcc -c -gnats -x ada toto.txt
6707 toto.txt:1:01: warning: empty file, contains no compilation units
6708 $
6709 @end smallexample
6710
6711 Otherwise, the output is simply the error messages, if any. No object file or
6712 ALI file is generated by a syntax-only compilation. Also, no units other
6713 than the one specified are accessed. For example, if a unit @code{X}
6714 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6715 check only mode does not access the source file containing unit
6716 @code{Y}.
6717
6718 @cindex Multiple units, syntax checking
6719 Normally, GNAT allows only a single unit in a source file. However, this
6720 restriction does not apply in syntax-check-only mode, and it is possible
6721 to check a file containing multiple compilation units concatenated
6722 together. This is primarily used by the @code{gnatchop} utility
6723 (@pxref{Renaming Files Using gnatchop}).
6724 @end table
6725
6726 @node Using gcc for Semantic Checking
6727 @subsection Using @command{gcc} for Semantic Checking
6728 @table @option
6729 @item -gnatc
6730 @cindex @option{-gnatc} (@command{gcc})
6731
6732 @ifclear vms
6733 @noindent
6734 The @code{c} stands for ``check''.
6735 @end ifclear
6736 Causes the compiler to operate in semantic check mode,
6737 with full checking for all illegalities specified in the
6738 Ada Reference Manual, but without generation of any object code
6739 (no object file is generated).
6740
6741 Because dependent files must be accessed, you must follow the GNAT
6742 semantic restrictions on file structuring to operate in this mode:
6743
6744 @itemize @bullet
6745 @item
6746 The needed source files must be accessible
6747 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6748
6749 @item
6750 Each file must contain only one compilation unit.
6751
6752 @item
6753 The file name and unit name must match (@pxref{File Naming Rules}).
6754 @end itemize
6755
6756 The output consists of error messages as appropriate. No object file is
6757 generated. An @file{ALI} file is generated for use in the context of
6758 cross-reference tools, but this file is marked as not being suitable
6759 for binding (since no object file is generated).
6760 The checking corresponds exactly to the notion of
6761 legality in the Ada Reference Manual.
6762
6763 Any unit can be compiled in semantics-checking-only mode, including
6764 units that would not normally be compiled (subunits,
6765 and specifications where a separate body is present).
6766 @end table
6767
6768 @node Compiling Different Versions of Ada
6769 @subsection Compiling Different Versions of Ada
6770
6771 @noindent
6772 The switches described in this section allow you to explicitly specify
6773 the version of the Ada language that your programs are written in.
6774 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6775 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6776 indicate Ada 83 compatibility mode.
6777
6778 @table @option
6779 @cindex Compatibility with Ada 83
6780
6781 @item -gnat83 (Ada 83 Compatibility Mode)
6782 @cindex @option{-gnat83} (@command{gcc})
6783 @cindex ACVC, Ada 83 tests
6784 @cindex Ada 83 mode
6785
6786 @noindent
6787 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6788 specifies that the program is to be compiled in Ada 83 mode. With
6789 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6790 semantics where this can be done easily.
6791 It is not possible to guarantee this switch does a perfect
6792 job; some subtle tests, such as are
6793 found in earlier ACVC tests (and that have been removed from the ACATS suite
6794 for Ada 95), might not compile correctly.
6795 Nevertheless, this switch may be useful in some circumstances, for example
6796 where, due to contractual reasons, existing code needs to be maintained
6797 using only Ada 83 features.
6798
6799 With few exceptions (most notably the need to use @code{<>} on
6800 @cindex Generic formal parameters
6801 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6802 reserved words, and the use of packages
6803 with optional bodies), it is not necessary to specify the
6804 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6805 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6806 a correct Ada 83 program is usually also a correct program
6807 in these later versions of the language standard.
6808 For further information, please refer to @ref{Compatibility and Porting Guide}.
6809
6810 @item -gnat95 (Ada 95 mode)
6811 @cindex @option{-gnat95} (@command{gcc})
6812 @cindex Ada 95 mode
6813
6814 @noindent
6815 This switch directs the compiler to implement the Ada 95 version of the
6816 language.
6817 Since Ada 95 is almost completely upwards
6818 compatible with Ada 83, Ada 83 programs may generally be compiled using
6819 this switch (see the description of the @option{-gnat83} switch for further
6820 information about Ada 83 mode).
6821 If an Ada 2005 program is compiled in Ada 95 mode,
6822 uses of the new Ada 2005 features will cause error
6823 messages or warnings.
6824
6825 This switch also can be used to cancel the effect of a previous
6826 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6827
6828 @item -gnat05 (Ada 2005 mode)
6829 @cindex @option{-gnat05} (@command{gcc})
6830 @cindex Ada 2005 mode
6831
6832 @noindent
6833 This switch directs the compiler to implement the Ada 2005 version of the
6834 language.
6835 Since Ada 2005 is almost completely upwards
6836 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6837 may generally be compiled using this switch (see the description of the
6838 @option{-gnat83} and @option{-gnat95} switches for further
6839 information).
6840
6841 For information about the approved ``Ada Issues'' that have been incorporated
6842 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6843 Included with GNAT releases is a file @file{features-ada0y} that describes
6844 the set of implemented Ada 2005 features.
6845 @end table
6846
6847
6848 @node Character Set Control
6849 @subsection Character Set Control
6850 @table @option
6851 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6852 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6853
6854 @noindent
6855 Normally GNAT recognizes the Latin-1 character set in source program
6856 identifiers, as described in the Ada Reference Manual.
6857 This switch causes
6858 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6859 single character ^^or word^ indicating the character set, as follows:
6860
6861 @table @code
6862 @item 1
6863 ISO 8859-1 (Latin-1) identifiers
6864
6865 @item 2
6866 ISO 8859-2 (Latin-2) letters allowed in identifiers
6867
6868 @item 3
6869 ISO 8859-3 (Latin-3) letters allowed in identifiers
6870
6871 @item 4
6872 ISO 8859-4 (Latin-4) letters allowed in identifiers
6873
6874 @item 5
6875 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6876
6877 @item 9
6878 ISO 8859-15 (Latin-9) letters allowed in identifiers
6879
6880 @item ^p^PC^
6881 IBM PC letters (code page 437) allowed in identifiers
6882
6883 @item ^8^PC850^
6884 IBM PC letters (code page 850) allowed in identifiers
6885
6886 @item ^f^FULL_UPPER^
6887 Full upper-half codes allowed in identifiers
6888
6889 @item ^n^NO_UPPER^
6890 No upper-half codes allowed in identifiers
6891
6892 @item ^w^WIDE^
6893 Wide-character codes (that is, codes greater than 255)
6894 allowed in identifiers
6895 @end table
6896
6897 @xref{Foreign Language Representation}, for full details on the
6898 implementation of these character sets.
6899
6900 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6901 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6902 Specify the method of encoding for wide characters.
6903 @var{e} is one of the following:
6904
6905 @table @code
6906
6907 @item ^h^HEX^
6908 Hex encoding (brackets coding also recognized)
6909
6910 @item ^u^UPPER^
6911 Upper half encoding (brackets encoding also recognized)
6912
6913 @item ^s^SHIFT_JIS^
6914 Shift/JIS encoding (brackets encoding also recognized)
6915
6916 @item ^e^EUC^
6917 EUC encoding (brackets encoding also recognized)
6918
6919 @item ^8^UTF8^
6920 UTF-8 encoding (brackets encoding also recognized)
6921
6922 @item ^b^BRACKETS^
6923 Brackets encoding only (default value)
6924 @end table
6925 For full details on these encoding
6926 methods see @ref{Wide Character Encodings}.
6927 Note that brackets coding is always accepted, even if one of the other
6928 options is specified, so for example @option{-gnatW8} specifies that both
6929 brackets and UTF-8 encodings will be recognized. The units that are
6930 with'ed directly or indirectly will be scanned using the specified
6931 representation scheme, and so if one of the non-brackets scheme is
6932 used, it must be used consistently throughout the program. However,
6933 since brackets encoding is always recognized, it may be conveniently
6934 used in standard libraries, allowing these libraries to be used with
6935 any of the available coding schemes.
6936 scheme.
6937
6938 If no @option{-gnatW?} parameter is present, then the default
6939 representation is normally Brackets encoding only. However, if the
6940 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6941 byte order mark or BOM for UTF-8), then these three characters are
6942 skipped and the default representation for the file is set to UTF-8.
6943
6944 Note that the wide character representation that is specified (explicitly
6945 or by default) for the main program also acts as the default encoding used
6946 for Wide_Text_IO files if not specifically overridden by a WCEM form
6947 parameter.
6948
6949 @end table
6950 @node File Naming Control
6951 @subsection File Naming Control
6952
6953 @table @option
6954 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6955 @cindex @option{-gnatk} (@command{gcc})
6956 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6957 1-999, indicates the maximum allowable length of a file name (not
6958 including the @file{.ads} or @file{.adb} extension). The default is not
6959 to enable file name krunching.
6960
6961 For the source file naming rules, @xref{File Naming Rules}.
6962 @end table
6963
6964 @node Subprogram Inlining Control
6965 @subsection Subprogram Inlining Control
6966
6967 @table @option
6968 @c !sort!
6969 @item -gnatn
6970 @cindex @option{-gnatn} (@command{gcc})
6971 @ifclear vms
6972 The @code{n} here is intended to suggest the first syllable of the
6973 word ``inline''.
6974 @end ifclear
6975 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6976 inlining to actually occur, optimization must be enabled. To enable
6977 inlining of subprograms specified by pragma @code{Inline},
6978 you must also specify this switch.
6979 In the absence of this switch, GNAT does not attempt
6980 inlining and does not need to access the bodies of
6981 subprograms for which @code{pragma Inline} is specified if they are not
6982 in the current unit.
6983
6984 If you specify this switch the compiler will access these bodies,
6985 creating an extra source dependency for the resulting object file, and
6986 where possible, the call will be inlined.
6987 For further details on when inlining is possible
6988 see @ref{Inlining of Subprograms}.
6989
6990 @item -gnatN
6991 @cindex @option{-gnatN} (@command{gcc})
6992 This switch activates front-end inlining which also
6993 generates additional dependencies.
6994
6995 When using a gcc-based back end (in practice this means using any version
6996 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6997 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6998 Historically front end inlining was more extensive than the gcc back end
6999 inlining, but that is no longer the case.
7000 @end table
7001
7002 @node Auxiliary Output Control
7003 @subsection Auxiliary Output Control
7004
7005 @table @option
7006 @item -gnatt
7007 @cindex @option{-gnatt} (@command{gcc})
7008 @cindex Writing internal trees
7009 @cindex Internal trees, writing to file
7010 Causes GNAT to write the internal tree for a unit to a file (with the
7011 extension @file{.adt}.
7012 This not normally required, but is used by separate analysis tools.
7013 Typically
7014 these tools do the necessary compilations automatically, so you should
7015 not have to specify this switch in normal operation.
7016 Note that the combination of switches @option{-gnatct}
7017 generates a tree in the form required by ASIS applications.
7018
7019 @item -gnatu
7020 @cindex @option{-gnatu} (@command{gcc})
7021 Print a list of units required by this compilation on @file{stdout}.
7022 The listing includes all units on which the unit being compiled depends
7023 either directly or indirectly.
7024
7025 @ifclear vms
7026 @item -pass-exit-codes
7027 @cindex @option{-pass-exit-codes} (@command{gcc})
7028 If this switch is not used, the exit code returned by @command{gcc} when
7029 compiling multiple files indicates whether all source files have
7030 been successfully used to generate object files or not.
7031
7032 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7033 exit status and allows an integrated development environment to better
7034 react to a compilation failure. Those exit status are:
7035
7036 @table @asis
7037 @item 5
7038 There was an error in at least one source file.
7039 @item 3
7040 At least one source file did not generate an object file.
7041 @item 2
7042 The compiler died unexpectedly (internal error for example).
7043 @item 0
7044 An object file has been generated for every source file.
7045 @end table
7046 @end ifclear
7047 @end table
7048
7049 @node Debugging Control
7050 @subsection Debugging Control
7051
7052 @table @option
7053 @c !sort!
7054 @cindex Debugging options
7055 @ifclear vms
7056 @item -gnatd@var{x}
7057 @cindex @option{-gnatd} (@command{gcc})
7058 Activate internal debugging switches. @var{x} is a letter or digit, or
7059 string of letters or digits, which specifies the type of debugging
7060 outputs desired. Normally these are used only for internal development
7061 or system debugging purposes. You can find full documentation for these
7062 switches in the body of the @code{Debug} unit in the compiler source
7063 file @file{debug.adb}.
7064 @end ifclear
7065
7066 @item -gnatG[=nn]
7067 @cindex @option{-gnatG} (@command{gcc})
7068 This switch causes the compiler to generate auxiliary output containing
7069 a pseudo-source listing of the generated expanded code. Like most Ada
7070 compilers, GNAT works by first transforming the high level Ada code into
7071 lower level constructs. For example, tasking operations are transformed
7072 into calls to the tasking run-time routines. A unique capability of GNAT
7073 is to list this expanded code in a form very close to normal Ada source.
7074 This is very useful in understanding the implications of various Ada
7075 usage on the efficiency of the generated code. There are many cases in
7076 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7077 generate a lot of run-time code. By using @option{-gnatG} you can identify
7078 these cases, and consider whether it may be desirable to modify the coding
7079 approach to improve efficiency.
7080
7081 The optional parameter @code{nn} if present after -gnatG specifies an
7082 alternative maximum line length that overrides the normal default of 72.
7083 This value is in the range 40-999999, values less than 40 being silently
7084 reset to 40. The equal sign is optional.
7085
7086 The format of the output is very similar to standard Ada source, and is
7087 easily understood by an Ada programmer. The following special syntactic
7088 additions correspond to low level features used in the generated code that
7089 do not have any exact analogies in pure Ada source form. The following
7090 is a partial list of these special constructions. See the spec
7091 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7092
7093 If the switch @option{-gnatL} is used in conjunction with
7094 @cindex @option{-gnatL} (@command{gcc})
7095 @option{-gnatG}, then the original source lines are interspersed
7096 in the expanded source (as comment lines with the original line number).
7097
7098 @table @code
7099 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7100 Shows the storage pool being used for an allocator.
7101
7102 @item at end @var{procedure-name};
7103 Shows the finalization (cleanup) procedure for a scope.
7104
7105 @item (if @var{expr} then @var{expr} else @var{expr})
7106 Conditional expression equivalent to the @code{x?y:z} construction in C.
7107
7108 @item @var{target}^^^(@var{source})
7109 A conversion with floating-point truncation instead of rounding.
7110
7111 @item @var{target}?(@var{source})
7112 A conversion that bypasses normal Ada semantic checking. In particular
7113 enumeration types and fixed-point types are treated simply as integers.
7114
7115 @item @var{target}?^^^(@var{source})
7116 Combines the above two cases.
7117
7118 @item @var{x} #/ @var{y}
7119 @itemx @var{x} #mod @var{y}
7120 @itemx @var{x} #* @var{y}
7121 @itemx @var{x} #rem @var{y}
7122 A division or multiplication of fixed-point values which are treated as
7123 integers without any kind of scaling.
7124
7125 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7126 Shows the storage pool associated with a @code{free} statement.
7127
7128 @item [subtype or type declaration]
7129 Used to list an equivalent declaration for an internally generated
7130 type that is referenced elsewhere in the listing.
7131
7132 @item freeze @var{type-name} @ovar{actions}
7133 Shows the point at which @var{type-name} is frozen, with possible
7134 associated actions to be performed at the freeze point.
7135
7136 @item reference @var{itype}
7137 Reference (and hence definition) to internal type @var{itype}.
7138
7139 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7140 Intrinsic function call.
7141
7142 @item @var{label-name} : label
7143 Declaration of label @var{labelname}.
7144
7145 @item #$ @var{subprogram-name}
7146 An implicit call to a run-time support routine
7147 (to meet the requirement of H.3.1(9) in a
7148 convenient manner).
7149
7150 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7151 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7152 @var{expr}, but handled more efficiently).
7153
7154 @item [constraint_error]
7155 Raise the @code{Constraint_Error} exception.
7156
7157 @item @var{expression}'reference
7158 A pointer to the result of evaluating @var{expression}.
7159
7160 @item @var{target-type}!(@var{source-expression})
7161 An unchecked conversion of @var{source-expression} to @var{target-type}.
7162
7163 @item [@var{numerator}/@var{denominator}]
7164 Used to represent internal real literals (that) have no exact
7165 representation in base 2-16 (for example, the result of compile time
7166 evaluation of the expression 1.0/27.0).
7167 @end table
7168
7169 @item -gnatD[=nn]
7170 @cindex @option{-gnatD} (@command{gcc})
7171 When used in conjunction with @option{-gnatG}, this switch causes
7172 the expanded source, as described above for
7173 @option{-gnatG} to be written to files with names
7174 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7175 instead of to the standard output file. For
7176 example, if the source file name is @file{hello.adb}, then a file
7177 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7178 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7179 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7180 you to do source level debugging using the generated code which is
7181 sometimes useful for complex code, for example to find out exactly
7182 which part of a complex construction raised an exception. This switch
7183 also suppress generation of cross-reference information (see
7184 @option{-gnatx}) since otherwise the cross-reference information
7185 would refer to the @file{^.dg^.DG^} file, which would cause
7186 confusion since this is not the original source file.
7187
7188 Note that @option{-gnatD} actually implies @option{-gnatG}
7189 automatically, so it is not necessary to give both options.
7190 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7191
7192 If the switch @option{-gnatL} is used in conjunction with
7193 @cindex @option{-gnatL} (@command{gcc})
7194 @option{-gnatDG}, then the original source lines are interspersed
7195 in the expanded source (as comment lines with the original line number).
7196
7197 The optional parameter @code{nn} if present after -gnatD specifies an
7198 alternative maximum line length that overrides the normal default of 72.
7199 This value is in the range 40-999999, values less than 40 being silently
7200 reset to 40. The equal sign is optional.
7201
7202 @item -gnatr
7203 @cindex @option{-gnatr} (@command{gcc})
7204 @cindex pragma Restrictions
7205 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7206 so that violation of restrictions causes warnings rather than illegalities.
7207 This is useful during the development process when new restrictions are added
7208 or investigated. The switch also causes pragma Profile to be treated as
7209 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7210 restriction warnings rather than restrictions.
7211
7212 @ifclear vms
7213 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7214 @cindex @option{-gnatR} (@command{gcc})
7215 This switch controls output from the compiler of a listing showing
7216 representation information for declared types and objects. For
7217 @option{-gnatR0}, no information is output (equivalent to omitting
7218 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7219 so @option{-gnatR} with no parameter has the same effect), size and alignment
7220 information is listed for declared array and record types. For
7221 @option{-gnatR2}, size and alignment information is listed for all
7222 declared types and objects. Finally @option{-gnatR3} includes symbolic
7223 expressions for values that are computed at run time for
7224 variant records. These symbolic expressions have a mostly obvious
7225 format with #n being used to represent the value of the n'th
7226 discriminant. See source files @file{repinfo.ads/adb} in the
7227 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7228 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7229 the output is to a file with the name @file{^file.rep^file_REP^} where
7230 file is the name of the corresponding source file.
7231 @end ifclear
7232 @ifset vms
7233 @item /REPRESENTATION_INFO
7234 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7235 This qualifier controls output from the compiler of a listing showing
7236 representation information for declared types and objects. For
7237 @option{/REPRESENTATION_INFO=NONE}, no information is output
7238 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7239 @option{/REPRESENTATION_INFO} without option is equivalent to
7240 @option{/REPRESENTATION_INFO=ARRAYS}.
7241 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7242 information is listed for declared array and record types. For
7243 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7244 is listed for all expression information for values that are computed
7245 at run time for variant records. These symbolic expressions have a mostly
7246 obvious format with #n being used to represent the value of the n'th
7247 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7248 @code{GNAT} sources for full details on the format of
7249 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7250 If _FILE is added at the end of an option
7251 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7252 then the output is to a file with the name @file{file_REP} where
7253 file is the name of the corresponding source file.
7254 @end ifset
7255 Note that it is possible for record components to have zero size. In
7256 this case, the component clause uses an obvious extension of permitted
7257 Ada syntax, for example @code{at 0 range 0 .. -1}.
7258
7259 Representation information requires that code be generated (since it is the
7260 code generator that lays out complex data structures). If an attempt is made
7261 to output representation information when no code is generated, for example
7262 when a subunit is compiled on its own, then no information can be generated
7263 and the compiler outputs a message to this effect.
7264
7265 @item -gnatS
7266 @cindex @option{-gnatS} (@command{gcc})
7267 The use of the switch @option{-gnatS} for an
7268 Ada compilation will cause the compiler to output a
7269 representation of package Standard in a form very
7270 close to standard Ada. It is not quite possible to
7271 do this entirely in standard Ada (since new
7272 numeric base types cannot be created in standard
7273 Ada), but the output is easily
7274 readable to any Ada programmer, and is useful to
7275 determine the characteristics of target dependent
7276 types in package Standard.
7277
7278 @item -gnatx
7279 @cindex @option{-gnatx} (@command{gcc})
7280 Normally the compiler generates full cross-referencing information in
7281 the @file{ALI} file. This information is used by a number of tools,
7282 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7283 suppresses this information. This saves some space and may slightly
7284 speed up compilation, but means that these tools cannot be used.
7285 @end table
7286
7287 @node Exception Handling Control
7288 @subsection Exception Handling Control
7289
7290 @noindent
7291 GNAT uses two methods for handling exceptions at run-time. The
7292 @code{setjmp/longjmp} method saves the context when entering
7293 a frame with an exception handler. Then when an exception is
7294 raised, the context can be restored immediately, without the
7295 need for tracing stack frames. This method provides very fast
7296 exception propagation, but introduces significant overhead for
7297 the use of exception handlers, even if no exception is raised.
7298
7299 The other approach is called ``zero cost'' exception handling.
7300 With this method, the compiler builds static tables to describe
7301 the exception ranges. No dynamic code is required when entering
7302 a frame containing an exception handler. When an exception is
7303 raised, the tables are used to control a back trace of the
7304 subprogram invocation stack to locate the required exception
7305 handler. This method has considerably poorer performance for
7306 the propagation of exceptions, but there is no overhead for
7307 exception handlers if no exception is raised. Note that in this
7308 mode and in the context of mixed Ada and C/C++ programming,
7309 to propagate an exception through a C/C++ code, the C/C++ code
7310 must be compiled with the @option{-funwind-tables} GCC's
7311 option.
7312
7313 The following switches may be used to control which of the
7314 two exception handling methods is used.
7315
7316 @table @option
7317 @c !sort!
7318
7319 @item --RTS=sjlj
7320 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7321 This switch causes the setjmp/longjmp run-time (when available) to be used
7322 for exception handling. If the default
7323 mechanism for the target is zero cost exceptions, then
7324 this switch can be used to modify this default, and must be
7325 used for all units in the partition.
7326 This option is rarely used. One case in which it may be
7327 advantageous is if you have an application where exception
7328 raising is common and the overall performance of the
7329 application is improved by favoring exception propagation.
7330
7331 @item --RTS=zcx
7332 @cindex @option{--RTS=zcx} (@command{gnatmake})
7333 @cindex Zero Cost Exceptions
7334 This switch causes the zero cost approach to be used
7335 for exception handling. If this is the default mechanism for the
7336 target (see below), then this switch is unneeded. If the default
7337 mechanism for the target is setjmp/longjmp exceptions, then
7338 this switch can be used to modify this default, and must be
7339 used for all units in the partition.
7340 This option can only be used if the zero cost approach
7341 is available for the target in use, otherwise it will generate an error.
7342 @end table
7343
7344 @noindent
7345 The same option @option{--RTS} must be used both for @command{gcc}
7346 and @command{gnatbind}. Passing this option to @command{gnatmake}
7347 (@pxref{Switches for gnatmake}) will ensure the required consistency
7348 through the compilation and binding steps.
7349
7350 @node Units to Sources Mapping Files
7351 @subsection Units to Sources Mapping Files
7352
7353 @table @option
7354
7355 @item -gnatem^^=^@var{path}
7356 @cindex @option{-gnatem} (@command{gcc})
7357 A mapping file is a way to communicate to the compiler two mappings:
7358 from unit names to file names (without any directory information) and from
7359 file names to path names (with full directory information). These mappings
7360 are used by the compiler to short-circuit the path search.
7361
7362 The use of mapping files is not required for correct operation of the
7363 compiler, but mapping files can improve efficiency, particularly when
7364 sources are read over a slow network connection. In normal operation,
7365 you need not be concerned with the format or use of mapping files,
7366 and the @option{-gnatem} switch is not a switch that you would use
7367 explicitly. it is intended only for use by automatic tools such as
7368 @command{gnatmake} running under the project file facility. The
7369 description here of the format of mapping files is provided
7370 for completeness and for possible use by other tools.
7371
7372 A mapping file is a sequence of sets of three lines. In each set,
7373 the first line is the unit name, in lower case, with ``@code{%s}''
7374 appended for
7375 specs and ``@code{%b}'' appended for bodies; the second line is the
7376 file name; and the third line is the path name.
7377
7378 Example:
7379 @smallexample
7380    main%b
7381    main.2.ada
7382    /gnat/project1/sources/main.2.ada
7383 @end smallexample
7384
7385 When the switch @option{-gnatem} is specified, the compiler will create
7386 in memory the two mappings from the specified file. If there is any problem
7387 (nonexistent file, truncated file or duplicate entries), no mapping will
7388 be created.
7389
7390 Several @option{-gnatem} switches may be specified; however, only the last
7391 one on the command line will be taken into account.
7392
7393 When using a project file, @command{gnatmake} create a temporary mapping file
7394 and communicates it to the compiler using this switch.
7395
7396 @end table
7397
7398 @node Integrated Preprocessing
7399 @subsection Integrated Preprocessing
7400
7401 @noindent
7402 GNAT sources may be preprocessed immediately before compilation.
7403 In this case, the actual
7404 text of the source is not the text of the source file, but is derived from it
7405 through a process called preprocessing. Integrated preprocessing is specified
7406 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7407 indicates, through a text file, the preprocessing data to be used.
7408 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7409
7410 @noindent
7411 Note that when integrated preprocessing is used, the output from the
7412 preprocessor is not written to any external file. Instead it is passed
7413 internally to the compiler. If you need to preserve the result of
7414 preprocessing in a file, then you should use @command{gnatprep}
7415 to perform the desired preprocessing in stand-alone mode.
7416
7417 @noindent
7418 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7419 used when Integrated Preprocessing is used. The reason is that preprocessing
7420 with another Preprocessing Data file without changing the sources will
7421 not trigger recompilation without this switch.
7422
7423 @noindent
7424 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7425 always trigger recompilation for sources that are preprocessed,
7426 because @command{gnatmake} cannot compute the checksum of the source after
7427 preprocessing.
7428
7429 @noindent
7430 The actual preprocessing function is described in details in section
7431 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7432 preprocessing is triggered and parameterized.
7433
7434 @table @code
7435
7436 @item -gnatep=@var{file}
7437 @cindex @option{-gnatep} (@command{gcc})
7438 This switch indicates to the compiler the file name (without directory
7439 information) of the preprocessor data file to use. The preprocessor data file
7440 should be found in the source directories.
7441
7442 @noindent
7443 A preprocessing data file is a text file with significant lines indicating
7444 how should be preprocessed either a specific source or all sources not
7445 mentioned in other lines. A significant line is a nonempty, non-comment line.
7446 Comments are similar to Ada comments.
7447
7448 @noindent
7449 Each significant line starts with either a literal string or the character '*'.
7450 A literal string is the file name (without directory information) of the source
7451 to preprocess. A character '*' indicates the preprocessing for all the sources
7452 that are not specified explicitly on other lines (order of the lines is not
7453 significant). It is an error to have two lines with the same file name or two
7454 lines starting with the character '*'.
7455
7456 @noindent
7457 After the file name or the character '*', another optional literal string
7458 indicating the file name of the definition file to be used for preprocessing
7459 (@pxref{Form of Definitions File}). The definition files are found by the
7460 compiler in one of the source directories. In some cases, when compiling
7461 a source in a directory other than the current directory, if the definition
7462 file is in the current directory, it may be necessary to add the current
7463 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7464 the compiler would not find the definition file.
7465
7466 @noindent
7467 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7468 be found. Those ^switches^switches^ are:
7469
7470 @table @code
7471
7472 @item -b
7473 Causes both preprocessor lines and the lines deleted by
7474 preprocessing to be replaced by blank lines, preserving the line number.
7475 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7476 it cancels the effect of @option{-c}.
7477
7478 @item -c
7479 Causes both preprocessor lines and the lines deleted
7480 by preprocessing to be retained as comments marked
7481 with the special string ``@code{--! }''.
7482
7483 @item -Dsymbol=value
7484 Define or redefine a symbol, associated with value. A symbol is an Ada
7485 identifier, or an Ada reserved word, with the exception of @code{if},
7486 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7487 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7488 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7489 same name defined in a definition file.
7490
7491 @item -s
7492 Causes a sorted list of symbol names and values to be
7493 listed on the standard output file.
7494
7495 @item -u
7496 Causes undefined symbols to be treated as having the value @code{FALSE}
7497 in the context
7498 of a preprocessor test. In the absence of this option, an undefined symbol in
7499 a @code{#if} or @code{#elsif} test will be treated as an error.
7500
7501 @end table
7502
7503 @noindent
7504 Examples of valid lines in a preprocessor data file:
7505
7506 @smallexample
7507   "toto.adb"  "prep.def" -u
7508   --  preprocess "toto.adb", using definition file "prep.def",
7509   --  undefined symbol are False.
7510
7511   * -c -DVERSION=V101
7512   --  preprocess all other sources without a definition file;
7513   --  suppressed lined are commented; symbol VERSION has the value V101.
7514
7515   "titi.adb" "prep2.def" -s
7516   --  preprocess "titi.adb", using definition file "prep2.def";
7517   --  list all symbols with their values.
7518 @end smallexample
7519
7520 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7521 @cindex @option{-gnateD} (@command{gcc})
7522 Define or redefine a preprocessing symbol, associated with value. If no value
7523 is given on the command line, then the value of the symbol is @code{True}.
7524 A symbol is an identifier, following normal Ada (case-insensitive)
7525 rules for its syntax, and value is any sequence (including an empty sequence)
7526 of characters from the set (letters, digits, period, underline).
7527 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7528 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7529
7530 @noindent
7531 A symbol declared with this ^switch^switch^ on the command line replaces a
7532 symbol with the same name either in a definition file or specified with a
7533 ^switch^switch^ -D in the preprocessor data file.
7534
7535 @noindent
7536 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7537
7538 @item -gnateG
7539 When integrated preprocessing is performed and the preprocessor modifies
7540 the source text, write the result of this preprocessing into a file
7541 <source>^.prep^_prep^.
7542
7543 @end table
7544
7545 @node Code Generation Control
7546 @subsection Code Generation Control
7547
7548 @noindent
7549
7550 The GCC technology provides a wide range of target dependent
7551 @option{-m} switches for controlling
7552 details of code generation with respect to different versions of
7553 architectures. This includes variations in instruction sets (e.g.@:
7554 different members of the power pc family), and different requirements
7555 for optimal arrangement of instructions (e.g.@: different members of
7556 the x86 family). The list of available @option{-m} switches may be
7557 found in the GCC documentation.
7558
7559 Use of these @option{-m} switches may in some cases result in improved
7560 code performance.
7561
7562 The GNAT Pro technology is tested and qualified without any
7563 @option{-m} switches,
7564 so generally the most reliable approach is to avoid the use of these
7565 switches. However, we generally expect most of these switches to work
7566 successfully with GNAT Pro, and many customers have reported successful
7567 use of these options.
7568
7569 Our general advice is to avoid the use of @option{-m} switches unless
7570 special needs lead to requirements in this area. In particular,
7571 there is no point in using @option{-m} switches to improve performance
7572 unless you actually see a performance improvement.
7573
7574 @ifset vms
7575 @node Return Codes
7576 @subsection Return Codes
7577 @cindex Return Codes
7578 @cindex @option{/RETURN_CODES=VMS}
7579
7580 @noindent
7581 On VMS, GNAT compiled programs return POSIX-style codes by default,
7582 e.g.@: @option{/RETURN_CODES=POSIX}.
7583
7584 To enable VMS style return codes, use GNAT BIND and LINK with the option
7585 @option{/RETURN_CODES=VMS}. For example:
7586
7587 @smallexample
7588 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7589 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7590 @end smallexample
7591
7592 @noindent
7593 Programs built with /RETURN_CODES=VMS are suitable to be called in
7594 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7595 are suitable for spawning with appropriate GNAT RTL routines.
7596
7597 @end ifset
7598
7599 @node Search Paths and the Run-Time Library (RTL)
7600 @section Search Paths and the Run-Time Library (RTL)
7601
7602 @noindent
7603 With the GNAT source-based library system, the compiler must be able to
7604 find source files for units that are needed by the unit being compiled.
7605 Search paths are used to guide this process.
7606
7607 The compiler compiles one source file whose name must be given
7608 explicitly on the command line. In other words, no searching is done
7609 for this file. To find all other source files that are needed (the most
7610 common being the specs of units), the compiler examines the following
7611 directories, in the following order:
7612
7613 @enumerate
7614 @item
7615 The directory containing the source file of the main unit being compiled
7616 (the file name on the command line).
7617
7618 @item
7619 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7620 @command{gcc} command line, in the order given.
7621
7622 @item
7623 @findex ADA_PRJ_INCLUDE_FILE
7624 Each of the directories listed in the text file whose name is given
7625 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7626
7627 @noindent
7628 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7629 driver when project files are used. It should not normally be set
7630 by other means.
7631
7632 @item
7633 @findex ADA_INCLUDE_PATH
7634 Each of the directories listed in the value of the
7635 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7636 @ifclear vms
7637 Construct this value
7638 exactly as the @env{PATH} environment variable: a list of directory
7639 names separated by colons (semicolons when working with the NT version).
7640 @end ifclear
7641 @ifset vms
7642 Normally, define this value as a logical name containing a comma separated
7643 list of directory names.
7644
7645 This variable can also be defined by means of an environment string
7646 (an argument to the HP C exec* set of functions).
7647
7648 Logical Name:
7649 @smallexample
7650 DEFINE ANOTHER_PATH FOO:[BAG]
7651 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7652 @end smallexample
7653
7654 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7655 first, followed by the standard Ada
7656 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7657 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7658 (Text_IO, Sequential_IO, etc)
7659 instead of the standard Ada packages. Thus, in order to get the standard Ada
7660 packages by default, ADA_INCLUDE_PATH must be redefined.
7661 @end ifset
7662
7663 @item
7664 The content of the @file{ada_source_path} file which is part of the GNAT
7665 installation tree and is used to store standard libraries such as the
7666 GNAT Run Time Library (RTL) source files.
7667 @ifclear vms
7668 @ref{Installing a library}
7669 @end ifclear
7670 @end enumerate
7671
7672 @noindent
7673 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7674 inhibits the use of the directory
7675 containing the source file named in the command line. You can still
7676 have this directory on your search path, but in this case it must be
7677 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7678
7679 Specifying the switch @option{-nostdinc}
7680 inhibits the search of the default location for the GNAT Run Time
7681 Library (RTL) source files.
7682
7683 The compiler outputs its object files and ALI files in the current
7684 working directory.
7685 @ifclear vms
7686 Caution: The object file can be redirected with the @option{-o} switch;
7687 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7688 so the @file{ALI} file will not go to the right place. Therefore, you should
7689 avoid using the @option{-o} switch.
7690 @end ifclear
7691
7692 @findex System.IO
7693 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7694 children make up the GNAT RTL, together with the simple @code{System.IO}
7695 package used in the @code{"Hello World"} example. The sources for these units
7696 are needed by the compiler and are kept together in one directory. Not
7697 all of the bodies are needed, but all of the sources are kept together
7698 anyway. In a normal installation, you need not specify these directory
7699 names when compiling or binding. Either the environment variables or
7700 the built-in defaults cause these files to be found.
7701
7702 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7703 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7704 consisting of child units of @code{GNAT}. This is a collection of generally
7705 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7706 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7707
7708 Besides simplifying access to the RTL, a major use of search paths is
7709 in compiling sources from multiple directories. This can make
7710 development environments much more flexible.
7711
7712 @node Order of Compilation Issues
7713 @section Order of Compilation Issues
7714
7715 @noindent
7716 If, in our earlier example, there was a spec for the @code{hello}
7717 procedure, it would be contained in the file @file{hello.ads}; yet this
7718 file would not have to be explicitly compiled. This is the result of the
7719 model we chose to implement library management. Some of the consequences
7720 of this model are as follows:
7721
7722 @itemize @bullet
7723 @item
7724 There is no point in compiling specs (except for package
7725 specs with no bodies) because these are compiled as needed by clients. If
7726 you attempt a useless compilation, you will receive an error message.
7727 It is also useless to compile subunits because they are compiled as needed
7728 by the parent.
7729
7730 @item
7731 There are no order of compilation requirements: performing a
7732 compilation never obsoletes anything. The only way you can obsolete
7733 something and require recompilations is to modify one of the
7734 source files on which it depends.
7735
7736 @item
7737 There is no library as such, apart from the ALI files
7738 (@pxref{The Ada Library Information Files}, for information on the format
7739 of these files). For now we find it convenient to create separate ALI files,
7740 but eventually the information therein may be incorporated into the object
7741 file directly.
7742
7743 @item
7744 When you compile a unit, the source files for the specs of all units
7745 that it @code{with}'s, all its subunits, and the bodies of any generics it
7746 instantiates must be available (reachable by the search-paths mechanism
7747 described above), or you will receive a fatal error message.
7748 @end itemize
7749
7750 @node Examples
7751 @section Examples
7752
7753 @noindent
7754 The following are some typical Ada compilation command line examples:
7755
7756 @table @code
7757 @item $ gcc -c xyz.adb
7758 Compile body in file @file{xyz.adb} with all default options.
7759
7760 @ifclear vms
7761 @item $ gcc -c -O2 -gnata xyz-def.adb
7762 @end ifclear
7763 @ifset vms
7764 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7765 @end ifset
7766
7767 Compile the child unit package in file @file{xyz-def.adb} with extensive
7768 optimizations, and pragma @code{Assert}/@code{Debug} statements
7769 enabled.
7770
7771 @item $ gcc -c -gnatc abc-def.adb
7772 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7773 mode.
7774 @end table
7775
7776 @node Binding Using gnatbind
7777 @chapter Binding Using @code{gnatbind}
7778 @findex gnatbind
7779
7780 @menu
7781 * Running gnatbind::
7782 * Switches for gnatbind::
7783 * Command-Line Access::
7784 * Search Paths for gnatbind::
7785 * Examples of gnatbind Usage::
7786 @end menu
7787
7788 @noindent
7789 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7790 to bind compiled GNAT objects.
7791
7792 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7793 driver (see @ref{The GNAT Driver and Project Files}).
7794
7795 The @code{gnatbind} program performs four separate functions:
7796
7797 @enumerate
7798 @item
7799 Checks that a program is consistent, in accordance with the rules in
7800 Chapter 10 of the Ada Reference Manual. In particular, error
7801 messages are generated if a program uses inconsistent versions of a
7802 given unit.
7803
7804 @item
7805 Checks that an acceptable order of elaboration exists for the program
7806 and issues an error message if it cannot find an order of elaboration
7807 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7808
7809 @item
7810 Generates a main program incorporating the given elaboration order.
7811 This program is a small Ada package (body and spec) that
7812 must be subsequently compiled
7813 using the GNAT compiler. The necessary compilation step is usually
7814 performed automatically by @command{gnatlink}. The two most important
7815 functions of this program
7816 are to call the elaboration routines of units in an appropriate order
7817 and to call the main program.
7818
7819 @item
7820 Determines the set of object files required by the given main program.
7821 This information is output in the forms of comments in the generated program,
7822 to be read by the @command{gnatlink} utility used to link the Ada application.
7823 @end enumerate
7824
7825 @node Running gnatbind
7826 @section Running @code{gnatbind}
7827
7828 @noindent
7829 The form of the @code{gnatbind} command is
7830
7831 @smallexample
7832 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7833 @end smallexample
7834
7835 @noindent
7836 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7837 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7838 package in two files whose names are
7839 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7840 For example, if given the
7841 parameter @file{hello.ali}, for a main program contained in file
7842 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7843 and @file{b~hello.adb}.
7844
7845 When doing consistency checking, the binder takes into consideration
7846 any source files it can locate. For example, if the binder determines
7847 that the given main program requires the package @code{Pack}, whose
7848 @file{.ALI}
7849 file is @file{pack.ali} and whose corresponding source spec file is
7850 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7851 (using the same search path conventions as previously described for the
7852 @command{gcc} command). If it can locate this source file, it checks that
7853 the time stamps
7854 or source checksums of the source and its references to in @file{ALI} files
7855 match. In other words, any @file{ALI} files that mentions this spec must have
7856 resulted from compiling this version of the source file (or in the case
7857 where the source checksums match, a version close enough that the
7858 difference does not matter).
7859
7860 @cindex Source files, use by binder
7861 The effect of this consistency checking, which includes source files, is
7862 that the binder ensures that the program is consistent with the latest
7863 version of the source files that can be located at bind time. Editing a
7864 source file without compiling files that depend on the source file cause
7865 error messages to be generated by the binder.
7866
7867 For example, suppose you have a main program @file{hello.adb} and a
7868 package @code{P}, from file @file{p.ads} and you perform the following
7869 steps:
7870
7871 @enumerate
7872 @item
7873 Enter @code{gcc -c hello.adb} to compile the main program.
7874
7875 @item
7876 Enter @code{gcc -c p.ads} to compile package @code{P}.
7877
7878 @item
7879 Edit file @file{p.ads}.
7880
7881 @item
7882 Enter @code{gnatbind hello}.
7883 @end enumerate
7884
7885 @noindent
7886 At this point, the file @file{p.ali} contains an out-of-date time stamp
7887 because the file @file{p.ads} has been edited. The attempt at binding
7888 fails, and the binder generates the following error messages:
7889
7890 @smallexample
7891 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7892 error: "p.ads" has been modified and must be recompiled
7893 @end smallexample
7894
7895 @noindent
7896 Now both files must be recompiled as indicated, and then the bind can
7897 succeed, generating a main program. You need not normally be concerned
7898 with the contents of this file, but for reference purposes a sample
7899 binder output file is given in @ref{Example of Binder Output File}.
7900
7901 In most normal usage, the default mode of @command{gnatbind} which is to
7902 generate the main package in Ada, as described in the previous section.
7903 In particular, this means that any Ada programmer can read and understand
7904 the generated main program. It can also be debugged just like any other
7905 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7906 @command{gnatbind} and @command{gnatlink}.
7907
7908 However for some purposes it may be convenient to generate the main
7909 program in C rather than Ada. This may for example be helpful when you
7910 are generating a mixed language program with the main program in C. The
7911 GNAT compiler itself is an example.
7912 The use of the @option{^-C^/BIND_FILE=C^} switch
7913 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7914 be generated in C (and compiled using the gnu C compiler).
7915
7916 @node Switches for gnatbind
7917 @section Switches for @command{gnatbind}
7918
7919 @noindent
7920 The following switches are available with @code{gnatbind}; details will
7921 be presented in subsequent sections.
7922
7923 @menu
7924 * Consistency-Checking Modes::
7925 * Binder Error Message Control::
7926 * Elaboration Control::
7927 * Output Control::
7928 * Binding with Non-Ada Main Programs::
7929 * Binding Programs with No Main Subprogram::
7930 @end menu
7931
7932 @table @option
7933 @c !sort!
7934
7935 @item --version
7936 @cindex @option{--version} @command{gnatbind}
7937 Display Copyright and version, then exit disregarding all other options.
7938
7939 @item --help
7940 @cindex @option{--help} @command{gnatbind}
7941 If @option{--version} was not used, display usage, then exit disregarding
7942 all other options.
7943
7944 @item -a
7945 @cindex @option{-a} @command{gnatbind}
7946 Indicates that, if supported by the platform, the adainit procedure should
7947 be treated as an initialisation routine by the linker (a constructor). This
7948 is intended to be used by the Project Manager to automatically initialize
7949 shared Stand-Alone Libraries.
7950
7951 @item ^-aO^/OBJECT_SEARCH^
7952 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7953 Specify directory to be searched for ALI files.
7954
7955 @item ^-aI^/SOURCE_SEARCH^
7956 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7957 Specify directory to be searched for source file.
7958
7959 @item ^-A^/BIND_FILE=ADA^
7960 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7961 Generate binder program in Ada (default)
7962
7963 @item ^-b^/REPORT_ERRORS=BRIEF^
7964 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7965 Generate brief messages to @file{stderr} even if verbose mode set.
7966
7967 @item ^-c^/NOOUTPUT^
7968 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7969 Check only, no generation of binder output file.
7970
7971 @item ^-C^/BIND_FILE=C^
7972 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7973 Generate binder program in C
7974
7975 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7976 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7977 This switch can be used to change the default task stack size value
7978 to a specified size @var{nn}, which is expressed in bytes by default, or
7979 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7980 with @var{m}.
7981 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7982 in effect, to completing all task specs with
7983 @smallexample @c ada
7984    pragma Storage_Size (nn);
7985 @end smallexample
7986 When they do not already have such a pragma.
7987
7988 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7989 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7990 This switch can be used to change the default secondary stack size value
7991 to a specified size @var{nn}, which is expressed in bytes by default, or
7992 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7993 with @var{m}.
7994
7995 The secondary stack is used to deal with functions that return a variable
7996 sized result, for example a function returning an unconstrained
7997 String. There are two ways in which this secondary stack is allocated.
7998
7999 For most targets, the secondary stack is growing on demand and is allocated
8000 as a chain of blocks in the heap. The -D option is not very
8001 relevant. It only give some control over the size of the allocated
8002 blocks (whose size is the minimum of the default secondary stack size value,
8003 and the actual size needed for the current allocation request).
8004
8005 For certain targets, notably VxWorks 653,
8006 the secondary stack is allocated by carving off a fixed ratio chunk of the
8007 primary task stack. The -D option is used to define the
8008 size of the environment task's secondary stack.
8009
8010 @item ^-e^/ELABORATION_DEPENDENCIES^
8011 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8012 Output complete list of elaboration-order dependencies.
8013
8014 @item ^-E^/STORE_TRACEBACKS^
8015 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8016 Store tracebacks in exception occurrences when the target supports it.
8017 This is the default with the zero cost exception mechanism.
8018 @ignore
8019 @c The following may get moved to an appendix
8020 This option is currently supported on the following targets:
8021 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8022 @end ignore
8023 See also the packages @code{GNAT.Traceback} and
8024 @code{GNAT.Traceback.Symbolic} for more information.
8025 @ifclear vms
8026 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8027 @command{gcc} option.
8028 @end ifclear
8029
8030 @item ^-F^/FORCE_ELABS_FLAGS^
8031 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8032 Force the checks of elaboration flags. @command{gnatbind} does not normally
8033 generate checks of elaboration flags for the main executable, except when
8034 a Stand-Alone Library is used. However, there are cases when this cannot be
8035 detected by gnatbind. An example is importing an interface of a Stand-Alone
8036 Library through a pragma Import and only specifying through a linker switch
8037 this Stand-Alone Library. This switch is used to guarantee that elaboration
8038 flag checks are generated.
8039
8040 @item ^-h^/HELP^
8041 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8042 Output usage (help) information
8043
8044 @item ^-I^/SEARCH^
8045 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8046 Specify directory to be searched for source and ALI files.
8047
8048 @item ^-I-^/NOCURRENT_DIRECTORY^
8049 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8050 Do not look for sources in the current directory where @code{gnatbind} was
8051 invoked, and do not look for ALI files in the directory containing the
8052 ALI file named in the @code{gnatbind} command line.
8053
8054 @item ^-l^/ORDER_OF_ELABORATION^
8055 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8056 Output chosen elaboration order.
8057
8058 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8059 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8060 Bind the units for library building. In this case the adainit and
8061 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8062 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8063 ^@var{xxx}final^@var{XXX}FINAL^.
8064 Implies ^-n^/NOCOMPILE^.
8065 @ifclear vms
8066 (@xref{GNAT and Libraries}, for more details.)
8067 @end ifclear
8068 @ifset vms
8069 On OpenVMS, these init and final procedures are exported in uppercase
8070 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8071 the init procedure will be "TOTOINIT" and the exported name of the final
8072 procedure will be "TOTOFINAL".
8073 @end ifset
8074
8075 @item ^-Mxyz^/RENAME_MAIN=xyz^
8076 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8077 Rename generated main program from main to xyz. This option is
8078 supported on cross environments only.
8079
8080 @item ^-m^/ERROR_LIMIT=^@var{n}
8081 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8082 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8083 in the range 1..999999. The default value if no switch is
8084 given is 9999. If the number of warnings reaches this limit, then a
8085 message is output and further warnings are suppressed, the bind
8086 continues in this case. If the number of errors reaches this
8087 limit, then a message is output and the bind is abandoned.
8088 A value of zero means that no limit is enforced. The equal
8089 sign is optional.
8090
8091 @ifset unw
8092 Furthermore, under Windows, the sources pointed to by the libraries path
8093 set in the registry are not searched for.
8094 @end ifset
8095
8096 @item ^-n^/NOMAIN^
8097 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8098 No main program.
8099
8100 @item -nostdinc
8101 @cindex @option{-nostdinc} (@command{gnatbind})
8102 Do not look for sources in the system default directory.
8103
8104 @item -nostdlib
8105 @cindex @option{-nostdlib} (@command{gnatbind})
8106 Do not look for library files in the system default directory.
8107
8108 @item --RTS=@var{rts-path}
8109 @cindex @option{--RTS} (@code{gnatbind})
8110 Specifies the default location of the runtime library. Same meaning as the
8111 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8112
8113 @item ^-o ^/OUTPUT=^@var{file}
8114 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8115 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8116 Note that if this option is used, then linking must be done manually,
8117 gnatlink cannot be used.
8118
8119 @item ^-O^/OBJECT_LIST^
8120 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8121 Output object list.
8122
8123 @item ^-p^/PESSIMISTIC_ELABORATION^
8124 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8125 Pessimistic (worst-case) elaboration order
8126
8127 @item ^-R^-R^
8128 @cindex @option{^-R^-R^} (@command{gnatbind})
8129 Output closure source list.
8130
8131 @item ^-s^/READ_SOURCES=ALL^
8132 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8133 Require all source files to be present.
8134
8135 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8136 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8137 Specifies the value to be used when detecting uninitialized scalar
8138 objects with pragma Initialize_Scalars.
8139 The @var{xxx} ^string specified with the switch^option^ may be either
8140 @itemize @bullet
8141 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8142 @item ``@option{^lo^LOW^}'' for the lowest possible value
8143 @item ``@option{^hi^HIGH^}'' for the highest possible value
8144 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8145 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8146 @end itemize
8147
8148 In addition, you can specify @option{-Sev} to indicate that the value is
8149 to be set at run time. In this case, the program will look for an environment
8150 @cindex GNAT_INIT_SCALARS
8151 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8152 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8153 If no environment variable is found, or if it does not have a valid value,
8154 then the default is @option{in} (invalid values).
8155
8156 @ifclear vms
8157 @item -static
8158 @cindex @option{-static} (@code{gnatbind})
8159 Link against a static GNAT run time.
8160
8161 @item -shared
8162 @cindex @option{-shared} (@code{gnatbind})
8163 Link against a shared GNAT run time when available.
8164 @end ifclear
8165
8166 @item ^-t^/NOTIME_STAMP_CHECK^
8167 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8168 Tolerate time stamp and other consistency errors
8169
8170 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8171 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8172 Set the time slice value to @var{n} milliseconds. If the system supports
8173 the specification of a specific time slice value, then the indicated value
8174 is used. If the system does not support specific time slice values, but
8175 does support some general notion of round-robin scheduling, then any
8176 nonzero value will activate round-robin scheduling.
8177
8178 A value of zero is treated specially. It turns off time
8179 slicing, and in addition, indicates to the tasking run time that the
8180 semantics should match as closely as possible the Annex D
8181 requirements of the Ada RM, and in particular sets the default
8182 scheduling policy to @code{FIFO_Within_Priorities}.
8183
8184 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8185 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8186 Enable dynamic stack usage, with @var{n} results stored and displayed
8187 at program termination. A result is generated when a task
8188 terminates. Results that can't be stored are displayed on the fly, at
8189 task termination. This option is currently not supported on Itanium
8190 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8191
8192 @item ^-v^/REPORT_ERRORS=VERBOSE^
8193 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8194 Verbose mode. Write error messages, header, summary output to
8195 @file{stdout}.
8196
8197 @ifclear vms
8198 @item -w@var{x}
8199 @cindex @option{-w} (@code{gnatbind})
8200 Warning mode (@var{x}=s/e for suppress/treat as error)
8201 @end ifclear
8202
8203 @ifset vms
8204 @item /WARNINGS=NORMAL
8205 @cindex @option{/WARNINGS} (@code{gnatbind})
8206 Normal warnings mode. Warnings are issued but ignored
8207
8208 @item /WARNINGS=SUPPRESS
8209 @cindex @option{/WARNINGS} (@code{gnatbind})
8210 All warning messages are suppressed
8211
8212 @item /WARNINGS=ERROR
8213 @cindex @option{/WARNINGS} (@code{gnatbind})
8214 Warning messages are treated as fatal errors
8215 @end ifset
8216
8217 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8218 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8219 Override default wide character encoding for standard Text_IO files.
8220
8221 @item ^-x^/READ_SOURCES=NONE^
8222 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8223 Exclude source files (check object consistency only).
8224
8225 @ifset vms
8226 @item /READ_SOURCES=AVAILABLE
8227 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8228 Default mode, in which sources are checked for consistency only if
8229 they are available.
8230 @end ifset
8231
8232 @item ^-y^/ENABLE_LEAP_SECONDS^
8233 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8234 Enable leap seconds support in @code{Ada.Calendar} and its children.
8235
8236 @item ^-z^/ZERO_MAIN^
8237 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8238 No main subprogram.
8239 @end table
8240
8241 @ifclear vms
8242 @noindent
8243 You may obtain this listing of switches by running @code{gnatbind} with
8244 no arguments.
8245 @end ifclear
8246
8247 @node Consistency-Checking Modes
8248 @subsection Consistency-Checking Modes
8249
8250 @noindent
8251 As described earlier, by default @code{gnatbind} checks
8252 that object files are consistent with one another and are consistent
8253 with any source files it can locate. The following switches control binder
8254 access to sources.
8255
8256 @table @option
8257 @c !sort!
8258 @item ^-s^/READ_SOURCES=ALL^
8259 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8260 Require source files to be present. In this mode, the binder must be
8261 able to locate all source files that are referenced, in order to check
8262 their consistency. In normal mode, if a source file cannot be located it
8263 is simply ignored. If you specify this switch, a missing source
8264 file is an error.
8265
8266 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8267 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8268 Override default wide character encoding for standard Text_IO files.
8269 Normally the default wide character encoding method used for standard
8270 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8271 the main source input (see description of switch
8272 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8273 use of this switch for the binder (which has the same set of
8274 possible arguments) overrides this default as specified.
8275
8276 @item ^-x^/READ_SOURCES=NONE^
8277 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8278 Exclude source files. In this mode, the binder only checks that ALI
8279 files are consistent with one another. Source files are not accessed.
8280 The binder runs faster in this mode, and there is still a guarantee that
8281 the resulting program is self-consistent.
8282 If a source file has been edited since it was last compiled, and you
8283 specify this switch, the binder will not detect that the object
8284 file is out of date with respect to the source file. Note that this is the
8285 mode that is automatically used by @command{gnatmake} because in this
8286 case the checking against sources has already been performed by
8287 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8288
8289 @ifset vms
8290 @item /READ_SOURCES=AVAILABLE
8291 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8292 This is the default mode in which source files are checked if they are
8293 available, and ignored if they are not available.
8294 @end ifset
8295 @end table
8296
8297 @node Binder Error Message Control
8298 @subsection Binder Error Message Control
8299
8300 @noindent
8301 The following switches provide control over the generation of error
8302 messages from the binder:
8303
8304 @table @option
8305 @c !sort!
8306 @item ^-v^/REPORT_ERRORS=VERBOSE^
8307 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8308 Verbose mode. In the normal mode, brief error messages are generated to
8309 @file{stderr}. If this switch is present, a header is written
8310 to @file{stdout} and any error messages are directed to @file{stdout}.
8311 All that is written to @file{stderr} is a brief summary message.
8312
8313 @item ^-b^/REPORT_ERRORS=BRIEF^
8314 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8315 Generate brief error messages to @file{stderr} even if verbose mode is
8316 specified. This is relevant only when used with the
8317 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8318
8319 @ifclear vms
8320 @item -m@var{n}
8321 @cindex @option{-m} (@code{gnatbind})
8322 Limits the number of error messages to @var{n}, a decimal integer in the
8323 range 1-999. The binder terminates immediately if this limit is reached.
8324
8325 @item -M@var{xxx}
8326 @cindex @option{-M} (@code{gnatbind})
8327 Renames the generated main program from @code{main} to @code{xxx}.
8328 This is useful in the case of some cross-building environments, where
8329 the actual main program is separate from the one generated
8330 by @code{gnatbind}.
8331 @end ifclear
8332
8333 @item ^-ws^/WARNINGS=SUPPRESS^
8334 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8335 @cindex Warnings
8336 Suppress all warning messages.
8337
8338 @item ^-we^/WARNINGS=ERROR^
8339 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8340 Treat any warning messages as fatal errors.
8341
8342 @ifset vms
8343 @item /WARNINGS=NORMAL
8344 Standard mode with warnings generated, but warnings do not get treated
8345 as errors.
8346 @end ifset
8347
8348 @item ^-t^/NOTIME_STAMP_CHECK^
8349 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8350 @cindex Time stamp checks, in binder
8351 @cindex Binder consistency checks
8352 @cindex Consistency checks, in binder
8353 The binder performs a number of consistency checks including:
8354
8355 @itemize @bullet
8356 @item
8357 Check that time stamps of a given source unit are consistent
8358 @item
8359 Check that checksums of a given source unit are consistent
8360 @item
8361 Check that consistent versions of @code{GNAT} were used for compilation
8362 @item
8363 Check consistency of configuration pragmas as required
8364 @end itemize
8365
8366 @noindent
8367 Normally failure of such checks, in accordance with the consistency
8368 requirements of the Ada Reference Manual, causes error messages to be
8369 generated which abort the binder and prevent the output of a binder
8370 file and subsequent link to obtain an executable.
8371
8372 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8373 into warnings, so that
8374 binding and linking can continue to completion even in the presence of such
8375 errors. The result may be a failed link (due to missing symbols), or a
8376 non-functional executable which has undefined semantics.
8377 @emph{This means that
8378 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8379 with extreme care.}
8380 @end table
8381
8382 @node Elaboration Control
8383 @subsection Elaboration Control
8384
8385 @noindent
8386 The following switches provide additional control over the elaboration
8387 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8388
8389 @table @option
8390 @item ^-p^/PESSIMISTIC_ELABORATION^
8391 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8392 Normally the binder attempts to choose an elaboration order that is
8393 likely to minimize the likelihood of an elaboration order error resulting
8394 in raising a @code{Program_Error} exception. This switch reverses the
8395 action of the binder, and requests that it deliberately choose an order
8396 that is likely to maximize the likelihood of an elaboration error.
8397 This is useful in ensuring portability and avoiding dependence on
8398 accidental fortuitous elaboration ordering.
8399
8400 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8401 switch if dynamic
8402 elaboration checking is used (@option{-gnatE} switch used for compilation).
8403 This is because in the default static elaboration mode, all necessary
8404 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8405 These implicit pragmas are still respected by the binder in
8406 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8407 safe elaboration order is assured.
8408 @end table
8409
8410 @node Output Control
8411 @subsection Output Control
8412
8413 @noindent
8414 The following switches allow additional control over the output
8415 generated by the binder.
8416
8417 @table @option
8418 @c !sort!
8419
8420 @item ^-A^/BIND_FILE=ADA^
8421 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8422 Generate binder program in Ada (default). The binder program is named
8423 @file{b~@var{mainprog}.adb} by default. This can be changed with
8424 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8425
8426 @item ^-c^/NOOUTPUT^
8427 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8428 Check only. Do not generate the binder output file. In this mode the
8429 binder performs all error checks but does not generate an output file.
8430
8431 @item ^-C^/BIND_FILE=C^
8432 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8433 Generate binder program in C. The binder program is named
8434 @file{b_@var{mainprog}.c}.
8435 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8436 option.
8437
8438 @item ^-e^/ELABORATION_DEPENDENCIES^
8439 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8440 Output complete list of elaboration-order dependencies, showing the
8441 reason for each dependency. This output can be rather extensive but may
8442 be useful in diagnosing problems with elaboration order. The output is
8443 written to @file{stdout}.
8444
8445 @item ^-h^/HELP^
8446 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8447 Output usage information. The output is written to @file{stdout}.
8448
8449 @item ^-K^/LINKER_OPTION_LIST^
8450 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8451 Output linker options to @file{stdout}. Includes library search paths,
8452 contents of pragmas Ident and Linker_Options, and libraries added
8453 by @code{gnatbind}.
8454
8455 @item ^-l^/ORDER_OF_ELABORATION^
8456 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8457 Output chosen elaboration order. The output is written to @file{stdout}.
8458
8459 @item ^-O^/OBJECT_LIST^
8460 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8461 Output full names of all the object files that must be linked to provide
8462 the Ada component of the program. The output is written to @file{stdout}.
8463 This list includes the files explicitly supplied and referenced by the user
8464 as well as implicitly referenced run-time unit files. The latter are
8465 omitted if the corresponding units reside in shared libraries. The
8466 directory names for the run-time units depend on the system configuration.
8467
8468 @item ^-o ^/OUTPUT=^@var{file}
8469 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8470 Set name of output file to @var{file} instead of the normal
8471 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8472 binder generated body filename. In C mode you would normally give
8473 @var{file} an extension of @file{.c} because it will be a C source program.
8474 Note that if this option is used, then linking must be done manually.
8475 It is not possible to use gnatlink in this case, since it cannot locate
8476 the binder file.
8477
8478 @item ^-r^/RESTRICTION_LIST^
8479 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8480 Generate list of @code{pragma Restrictions} that could be applied to
8481 the current unit. This is useful for code audit purposes, and also may
8482 be used to improve code generation in some cases.
8483
8484 @end table
8485
8486 @node Binding with Non-Ada Main Programs
8487 @subsection Binding with Non-Ada Main Programs
8488
8489 @noindent
8490 In our description so far we have assumed that the main
8491 program is in Ada, and that the task of the binder is to generate a
8492 corresponding function @code{main} that invokes this Ada main
8493 program. GNAT also supports the building of executable programs where
8494 the main program is not in Ada, but some of the called routines are
8495 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8496 The following switch is used in this situation:
8497
8498 @table @option
8499 @item ^-n^/NOMAIN^
8500 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8501 No main program. The main program is not in Ada.
8502 @end table
8503
8504 @noindent
8505 In this case, most of the functions of the binder are still required,
8506 but instead of generating a main program, the binder generates a file
8507 containing the following callable routines:
8508
8509 @table @code
8510 @item adainit
8511 @findex adainit
8512 You must call this routine to initialize the Ada part of the program by
8513 calling the necessary elaboration routines. A call to @code{adainit} is
8514 required before the first call to an Ada subprogram.
8515
8516 Note that it is assumed that the basic execution environment must be setup
8517 to be appropriate for Ada execution at the point where the first Ada
8518 subprogram is called. In particular, if the Ada code will do any
8519 floating-point operations, then the FPU must be setup in an appropriate
8520 manner. For the case of the x86, for example, full precision mode is
8521 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8522 that the FPU is in the right state.
8523
8524 @item adafinal
8525 @findex adafinal
8526 You must call this routine to perform any library-level finalization
8527 required by the Ada subprograms. A call to @code{adafinal} is required
8528 after the last call to an Ada subprogram, and before the program
8529 terminates.
8530 @end table
8531
8532 @noindent
8533 If the @option{^-n^/NOMAIN^} switch
8534 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8535 @cindex Binder, multiple input files
8536 is given, more than one ALI file may appear on
8537 the command line for @code{gnatbind}. The normal @dfn{closure}
8538 calculation is performed for each of the specified units. Calculating
8539 the closure means finding out the set of units involved by tracing
8540 @code{with} references. The reason it is necessary to be able to
8541 specify more than one ALI file is that a given program may invoke two or
8542 more quite separate groups of Ada units.
8543
8544 The binder takes the name of its output file from the last specified ALI
8545 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8546 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8547 The output is an Ada unit in source form that can
8548 be compiled with GNAT unless the -C switch is used in which case the
8549 output is a C source file, which must be compiled using the C compiler.
8550 This compilation occurs automatically as part of the @command{gnatlink}
8551 processing.
8552
8553 Currently the GNAT run time requires a FPU using 80 bits mode
8554 precision. Under targets where this is not the default it is required to
8555 call GNAT.Float_Control.Reset before using floating point numbers (this
8556 include float computation, float input and output) in the Ada code. A
8557 side effect is that this could be the wrong mode for the foreign code
8558 where floating point computation could be broken after this call.
8559
8560 @node Binding Programs with No Main Subprogram
8561 @subsection Binding Programs with No Main Subprogram
8562
8563 @noindent
8564 It is possible to have an Ada program which does not have a main
8565 subprogram. This program will call the elaboration routines of all the
8566 packages, then the finalization routines.
8567
8568 The following switch is used to bind programs organized in this manner:
8569
8570 @table @option
8571 @item ^-z^/ZERO_MAIN^
8572 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8573 Normally the binder checks that the unit name given on the command line
8574 corresponds to a suitable main subprogram. When this switch is used,
8575 a list of ALI files can be given, and the execution of the program
8576 consists of elaboration of these units in an appropriate order. Note
8577 that the default wide character encoding method for standard Text_IO
8578 files is always set to Brackets if this switch is set (you can use
8579 the binder switch
8580 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8581 @end table
8582
8583 @node Command-Line Access
8584 @section Command-Line Access
8585
8586 @noindent
8587 The package @code{Ada.Command_Line} provides access to the command-line
8588 arguments and program name. In order for this interface to operate
8589 correctly, the two variables
8590
8591 @smallexample
8592 @group
8593 int gnat_argc;
8594 char **gnat_argv;
8595 @end group
8596 @end smallexample
8597
8598 @noindent
8599 @findex gnat_argv
8600 @findex gnat_argc
8601 are declared in one of the GNAT library routines. These variables must
8602 be set from the actual @code{argc} and @code{argv} values passed to the
8603 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8604 generates the C main program to automatically set these variables.
8605 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8606 set these variables. If they are not set, the procedures in
8607 @code{Ada.Command_Line} will not be available, and any attempt to use
8608 them will raise @code{Constraint_Error}. If command line access is
8609 required, your main program must set @code{gnat_argc} and
8610 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8611 it.
8612
8613 @node Search Paths for gnatbind
8614 @section Search Paths for @code{gnatbind}
8615
8616 @noindent
8617 The binder takes the name of an ALI file as its argument and needs to
8618 locate source files as well as other ALI files to verify object consistency.
8619
8620 For source files, it follows exactly the same search rules as @command{gcc}
8621 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8622 directories searched are:
8623
8624 @enumerate
8625 @item
8626 The directory containing the ALI file named in the command line, unless
8627 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8628
8629 @item
8630 All directories specified by @option{^-I^/SEARCH^}
8631 switches on the @code{gnatbind}
8632 command line, in the order given.
8633
8634 @item
8635 @findex ADA_PRJ_OBJECTS_FILE
8636 Each of the directories listed in the text file whose name is given
8637 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8638
8639 @noindent
8640 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8641 driver when project files are used. It should not normally be set
8642 by other means.
8643
8644 @item
8645 @findex ADA_OBJECTS_PATH
8646 Each of the directories listed in the value of the
8647 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8648 @ifset unw
8649 Construct this value
8650 exactly as the @env{PATH} environment variable: a list of directory
8651 names separated by colons (semicolons when working with the NT version
8652 of GNAT).
8653 @end ifset
8654 @ifset vms
8655 Normally, define this value as a logical name containing a comma separated
8656 list of directory names.
8657
8658 This variable can also be defined by means of an environment string
8659 (an argument to the HP C exec* set of functions).
8660
8661 Logical Name:
8662 @smallexample
8663 DEFINE ANOTHER_PATH FOO:[BAG]
8664 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8665 @end smallexample
8666
8667 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8668 first, followed by the standard Ada
8669 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8670 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8671 (Text_IO, Sequential_IO, etc)
8672 instead of the standard Ada packages. Thus, in order to get the standard Ada
8673 packages by default, ADA_OBJECTS_PATH must be redefined.
8674 @end ifset
8675
8676 @item
8677 The content of the @file{ada_object_path} file which is part of the GNAT
8678 installation tree and is used to store standard libraries such as the
8679 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8680 specified.
8681 @ifclear vms
8682 @ref{Installing a library}
8683 @end ifclear
8684 @end enumerate
8685
8686 @noindent
8687 In the binder the switch @option{^-I^/SEARCH^}
8688 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8689 is used to specify both source and
8690 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8691 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8692 instead if you want to specify
8693 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8694 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8695 if you want to specify library paths
8696 only. This means that for the binder
8697 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8698 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8699 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8700 The binder generates the bind file (a C language source file) in the
8701 current working directory.
8702
8703 @findex Ada
8704 @findex System
8705 @findex Interfaces
8706 @findex GNAT
8707 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8708 children make up the GNAT Run-Time Library, together with the package
8709 GNAT and its children, which contain a set of useful additional
8710 library functions provided by GNAT. The sources for these units are
8711 needed by the compiler and are kept together in one directory. The ALI
8712 files and object files generated by compiling the RTL are needed by the
8713 binder and the linker and are kept together in one directory, typically
8714 different from the directory containing the sources. In a normal
8715 installation, you need not specify these directory names when compiling
8716 or binding. Either the environment variables or the built-in defaults
8717 cause these files to be found.
8718
8719 Besides simplifying access to the RTL, a major use of search paths is
8720 in compiling sources from multiple directories. This can make
8721 development environments much more flexible.
8722
8723 @node Examples of gnatbind Usage
8724 @section Examples of @code{gnatbind} Usage
8725
8726 @noindent
8727 This section contains a number of examples of using the GNAT binding
8728 utility @code{gnatbind}.
8729
8730 @table @code
8731 @item gnatbind hello
8732 The main program @code{Hello} (source program in @file{hello.adb}) is
8733 bound using the standard switch settings. The generated main program is
8734 @file{b~hello.adb}. This is the normal, default use of the binder.
8735
8736 @ifclear vms
8737 @item gnatbind hello -o mainprog.adb
8738 @end ifclear
8739 @ifset vms
8740 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8741 @end ifset
8742 The main program @code{Hello} (source program in @file{hello.adb}) is
8743 bound using the standard switch settings. The generated main program is
8744 @file{mainprog.adb} with the associated spec in
8745 @file{mainprog.ads}. Note that you must specify the body here not the
8746 spec, in the case where the output is in Ada. Note that if this option
8747 is used, then linking must be done manually, since gnatlink will not
8748 be able to find the generated file.
8749
8750 @ifclear vms
8751 @item gnatbind main -C -o mainprog.c -x
8752 @end ifclear
8753 @ifset vms
8754 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8755 @end ifset
8756 The main program @code{Main} (source program in
8757 @file{main.adb}) is bound, excluding source files from the
8758 consistency checking, generating
8759 the file @file{mainprog.c}.
8760
8761 @ifclear vms
8762 @item gnatbind -x main_program -C -o mainprog.c
8763 This command is exactly the same as the previous example. Switches may
8764 appear anywhere in the command line, and single letter switches may be
8765 combined into a single switch.
8766 @end ifclear
8767
8768 @ifclear vms
8769 @item gnatbind -n math dbase -C -o ada-control.c
8770 @end ifclear
8771 @ifset vms
8772 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8773 @end ifset
8774 The main program is in a language other than Ada, but calls to
8775 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8776 to @code{gnatbind} generates the file @file{ada-control.c} containing
8777 the @code{adainit} and @code{adafinal} routines to be called before and
8778 after accessing the Ada units.
8779 @end table
8780
8781 @c ------------------------------------
8782 @node Linking Using gnatlink
8783 @chapter Linking Using @command{gnatlink}
8784 @c ------------------------------------
8785 @findex gnatlink
8786
8787 @noindent
8788 This chapter discusses @command{gnatlink}, a tool that links
8789 an Ada program and builds an executable file. This utility
8790 invokes the system linker ^(via the @command{gcc} command)^^
8791 with a correct list of object files and library references.
8792 @command{gnatlink} automatically determines the list of files and
8793 references for the Ada part of a program. It uses the binder file
8794 generated by the @command{gnatbind} to determine this list.
8795
8796 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8797 driver (see @ref{The GNAT Driver and Project Files}).
8798
8799 @menu
8800 * Running gnatlink::
8801 * Switches for gnatlink::
8802 @end menu
8803
8804 @node Running gnatlink
8805 @section Running @command{gnatlink}
8806
8807 @noindent
8808 The form of the @command{gnatlink} command is
8809
8810 @smallexample
8811 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8812            @ovar{non-Ada objects} @ovar{linker options}
8813 @end smallexample
8814
8815 @noindent
8816 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8817 non-Ada objects
8818 or linker options) may be in any order, provided that no non-Ada object may
8819 be mistaken for a main @file{ALI} file.
8820 Any file name @file{F} without the @file{.ali}
8821 extension will be taken as the main @file{ALI} file if a file exists
8822 whose name is the concatenation of @file{F} and @file{.ali}.
8823
8824 @noindent
8825 @file{@var{mainprog}.ali} references the ALI file of the main program.
8826 The @file{.ali} extension of this file can be omitted. From this
8827 reference, @command{gnatlink} locates the corresponding binder file
8828 @file{b~@var{mainprog}.adb} and, using the information in this file along
8829 with the list of non-Ada objects and linker options, constructs a
8830 linker command file to create the executable.
8831
8832 The arguments other than the @command{gnatlink} switches and the main
8833 @file{ALI} file are passed to the linker uninterpreted.
8834 They typically include the names of
8835 object files for units written in other languages than Ada and any library
8836 references required to resolve references in any of these foreign language
8837 units, or in @code{Import} pragmas in any Ada units.
8838
8839 @var{linker options} is an optional list of linker specific
8840 switches.
8841 The default linker called by gnatlink is @command{gcc} which in
8842 turn calls the appropriate system linker.
8843 Standard options for the linker such as @option{-lmy_lib} or
8844 @option{-Ldir} can be added as is.
8845 For options that are not recognized by
8846 @command{gcc} as linker options, use the @command{gcc} switches
8847 @option{-Xlinker} or @option{-Wl,}.
8848 Refer to the GCC documentation for
8849 details. Here is an example showing how to generate a linker map:
8850
8851 @smallexample
8852 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8853 @end smallexample
8854
8855 Using @var{linker options} it is possible to set the program stack and
8856 heap size.
8857 @ifset unw
8858 See @ref{Setting Stack Size from gnatlink} and
8859 @ref{Setting Heap Size from gnatlink}.
8860 @end ifset
8861
8862 @command{gnatlink} determines the list of objects required by the Ada
8863 program and prepends them to the list of objects passed to the linker.
8864 @command{gnatlink} also gathers any arguments set by the use of
8865 @code{pragma Linker_Options} and adds them to the list of arguments
8866 presented to the linker.
8867
8868 @ifset vms
8869 @command{gnatlink} accepts the following types of extra files on the command
8870 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8871 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8872 handled according to their extension.
8873 @end ifset
8874
8875 @node Switches for gnatlink
8876 @section Switches for @command{gnatlink}
8877
8878 @noindent
8879 The following switches are available with the @command{gnatlink} utility:
8880
8881 @table @option
8882 @c !sort!
8883
8884 @item --version
8885 @cindex @option{--version} @command{gnatlink}
8886 Display Copyright and version, then exit disregarding all other options.
8887
8888 @item --help
8889 @cindex @option{--help} @command{gnatlink}
8890 If @option{--version} was not used, display usage, then exit disregarding
8891 all other options.
8892
8893 @item ^-A^/BIND_FILE=ADA^
8894 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8895 The binder has generated code in Ada. This is the default.
8896
8897 @item ^-C^/BIND_FILE=C^
8898 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8899 If instead of generating a file in Ada, the binder has generated one in
8900 C, then the linker needs to know about it. Use this switch to signal
8901 to @command{gnatlink} that the binder has generated C code rather than
8902 Ada code.
8903
8904 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8905 @cindex Command line length
8906 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8907 On some targets, the command line length is limited, and @command{gnatlink}
8908 will generate a separate file for the linker if the list of object files
8909 is too long.
8910 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8911 to be generated even if
8912 the limit is not exceeded. This is useful in some cases to deal with
8913 special situations where the command line length is exceeded.
8914
8915 @item ^-g^/DEBUG^
8916 @cindex Debugging information, including
8917 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8918 The option to include debugging information causes the Ada bind file (in
8919 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8920 @option{^-g^/DEBUG^}.
8921 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8922 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8923 Without @option{^-g^/DEBUG^}, the binder removes these files by
8924 default. The same procedure apply if a C bind file was generated using
8925 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8926 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8927
8928 @item ^-n^/NOCOMPILE^
8929 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8930 Do not compile the file generated by the binder. This may be used when
8931 a link is rerun with different options, but there is no need to recompile
8932 the binder file.
8933
8934 @item ^-v^/VERBOSE^
8935 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8936 Causes additional information to be output, including a full list of the
8937 included object files. This switch option is most useful when you want
8938 to see what set of object files are being used in the link step.
8939
8940 @item ^-v -v^/VERBOSE/VERBOSE^
8941 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8942 Very verbose mode. Requests that the compiler operate in verbose mode when
8943 it compiles the binder file, and that the system linker run in verbose mode.
8944
8945 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8946 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8947 @var{exec-name} specifies an alternate name for the generated
8948 executable program. If this switch is omitted, the executable has the same
8949 name as the main unit. For example, @code{gnatlink try.ali} creates
8950 an executable called @file{^try^TRY.EXE^}.
8951
8952 @ifclear vms
8953 @item -b @var{target}
8954 @cindex @option{-b} (@command{gnatlink})
8955 Compile your program to run on @var{target}, which is the name of a
8956 system configuration. You must have a GNAT cross-compiler built if
8957 @var{target} is not the same as your host system.
8958
8959 @item -B@var{dir}
8960 @cindex @option{-B} (@command{gnatlink})
8961 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8962 from @var{dir} instead of the default location. Only use this switch
8963 when multiple versions of the GNAT compiler are available.
8964 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8965 for further details. You would normally use the @option{-b} or
8966 @option{-V} switch instead.
8967
8968 @item --GCC=@var{compiler_name}
8969 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8970 Program used for compiling the binder file. The default is
8971 @command{gcc}. You need to use quotes around @var{compiler_name} if
8972 @code{compiler_name} contains spaces or other separator characters.
8973 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8974 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8975 inserted after your command name. Thus in the above example the compiler
8976 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8977 A limitation of this syntax is that the name and path name of the executable
8978 itself must not include any embedded spaces. If the compiler executable is
8979 different from the default one (gcc or <prefix>-gcc), then the back-end
8980 switches in the ALI file are not used to compile the binder generated source.
8981 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8982 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8983 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8984 is taken into account. However, all the additional switches are also taken
8985 into account. Thus,
8986 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8987 @option{--GCC="bar -x -y -z -t"}.
8988
8989 @item --LINK=@var{name}
8990 @cindex @option{--LINK=} (@command{gnatlink})
8991 @var{name} is the name of the linker to be invoked. This is especially
8992 useful in mixed language programs since languages such as C++ require
8993 their own linker to be used. When this switch is omitted, the default
8994 name for the linker is @command{gcc}. When this switch is used, the
8995 specified linker is called instead of @command{gcc} with exactly the same
8996 parameters that would have been passed to @command{gcc} so if the desired
8997 linker requires different parameters it is necessary to use a wrapper
8998 script that massages the parameters before invoking the real linker. It
8999 may be useful to control the exact invocation by using the verbose
9000 switch.
9001
9002 @end ifclear
9003
9004 @ifset vms
9005 @item /DEBUG=TRACEBACK
9006 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9007 This qualifier causes sufficient information to be included in the
9008 executable file to allow a traceback, but does not include the full
9009 symbol information needed by the debugger.
9010
9011 @item /IDENTIFICATION="<string>"
9012 @code{"<string>"} specifies the string to be stored in the image file
9013 identification field in the image header.
9014 It overrides any pragma @code{Ident} specified string.
9015
9016 @item /NOINHIBIT-EXEC
9017 Generate the executable file even if there are linker warnings.
9018
9019 @item /NOSTART_FILES
9020 Don't link in the object file containing the ``main'' transfer address.
9021 Used when linking with a foreign language main program compiled with an
9022 HP compiler.
9023
9024 @item /STATIC
9025 Prefer linking with object libraries over sharable images, even without
9026 /DEBUG.
9027 @end ifset
9028
9029 @end table
9030
9031 @node The GNAT Make Program gnatmake
9032 @chapter The GNAT Make Program @command{gnatmake}
9033 @findex gnatmake
9034
9035 @menu
9036 * Running gnatmake::
9037 * Switches for gnatmake::
9038 * Mode Switches for gnatmake::
9039 * Notes on the Command Line::
9040 * How gnatmake Works::
9041 * Examples of gnatmake Usage::
9042 @end menu
9043 @noindent
9044 A typical development cycle when working on an Ada program consists of
9045 the following steps:
9046
9047 @enumerate
9048 @item
9049 Edit some sources to fix bugs.
9050
9051 @item
9052 Add enhancements.
9053
9054 @item
9055 Compile all sources affected.
9056
9057 @item
9058 Rebind and relink.
9059
9060 @item
9061 Test.
9062 @end enumerate
9063
9064 @noindent
9065 The third step can be tricky, because not only do the modified files
9066 @cindex Dependency rules
9067 have to be compiled, but any files depending on these files must also be
9068 recompiled. The dependency rules in Ada can be quite complex, especially
9069 in the presence of overloading, @code{use} clauses, generics and inlined
9070 subprograms.
9071
9072 @command{gnatmake} automatically takes care of the third and fourth steps
9073 of this process. It determines which sources need to be compiled,
9074 compiles them, and binds and links the resulting object files.
9075
9076 Unlike some other Ada make programs, the dependencies are always
9077 accurately recomputed from the new sources. The source based approach of
9078 the GNAT compilation model makes this possible. This means that if
9079 changes to the source program cause corresponding changes in
9080 dependencies, they will always be tracked exactly correctly by
9081 @command{gnatmake}.
9082
9083 @node Running gnatmake
9084 @section Running @command{gnatmake}
9085
9086 @noindent
9087 The usual form of the @command{gnatmake} command is
9088
9089 @smallexample
9090 $ gnatmake @ovar{switches} @var{file_name}
9091       @ovar{file_names} @ovar{mode_switches}
9092 @end smallexample
9093
9094 @noindent
9095 The only required argument is one @var{file_name}, which specifies
9096 a compilation unit that is a main program. Several @var{file_names} can be
9097 specified: this will result in several executables being built.
9098 If @code{switches} are present, they can be placed before the first
9099 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9100 If @var{mode_switches} are present, they must always be placed after
9101 the last @var{file_name} and all @code{switches}.
9102
9103 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9104 extension may be omitted from the @var{file_name} arguments. However, if
9105 you are using non-standard extensions, then it is required that the
9106 extension be given. A relative or absolute directory path can be
9107 specified in a @var{file_name}, in which case, the input source file will
9108 be searched for in the specified directory only. Otherwise, the input
9109 source file will first be searched in the directory where
9110 @command{gnatmake} was invoked and if it is not found, it will be search on
9111 the source path of the compiler as described in
9112 @ref{Search Paths and the Run-Time Library (RTL)}.
9113
9114 All @command{gnatmake} output (except when you specify
9115 @option{^-M^/DEPENDENCIES_LIST^}) is to
9116 @file{stderr}. The output produced by the
9117 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9118 @file{stdout}.
9119
9120 @node Switches for gnatmake
9121 @section Switches for @command{gnatmake}
9122
9123 @noindent
9124 You may specify any of the following switches to @command{gnatmake}:
9125
9126 @table @option
9127 @c !sort!
9128
9129 @item --version
9130 @cindex @option{--version} @command{gnatmake}
9131 Display Copyright and version, then exit disregarding all other options.
9132
9133 @item --help
9134 @cindex @option{--help} @command{gnatmake}
9135 If @option{--version} was not used, display usage, then exit disregarding
9136 all other options.
9137
9138 @ifclear vms
9139 @item --GCC=@var{compiler_name}
9140 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9141 Program used for compiling. The default is `@command{gcc}'. You need to use
9142 quotes around @var{compiler_name} if @code{compiler_name} contains
9143 spaces or other separator characters. As an example @option{--GCC="foo -x
9144 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9145 compiler. A limitation of this syntax is that the name and path name of
9146 the executable itself must not include any embedded spaces. Note that
9147 switch @option{-c} is always inserted after your command name. Thus in the
9148 above example the compiler command that will be used by @command{gnatmake}
9149 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9150 used, only the last @var{compiler_name} is taken into account. However,
9151 all the additional switches are also taken into account. Thus,
9152 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9153 @option{--GCC="bar -x -y -z -t"}.
9154
9155 @item --GNATBIND=@var{binder_name}
9156 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9157 Program used for binding. The default is `@code{gnatbind}'. You need to
9158 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9159 or other separator characters. As an example @option{--GNATBIND="bar -x
9160 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9161 binder. Binder switches that are normally appended by @command{gnatmake}
9162 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9163 A limitation of this syntax is that the name and path name of the executable
9164 itself must not include any embedded spaces.
9165
9166 @item --GNATLINK=@var{linker_name}
9167 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9168 Program used for linking. The default is `@command{gnatlink}'. You need to
9169 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9170 or other separator characters. As an example @option{--GNATLINK="lan -x
9171 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9172 linker. Linker switches that are normally appended by @command{gnatmake} to
9173 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9174 A limitation of this syntax is that the name and path name of the executable
9175 itself must not include any embedded spaces.
9176
9177 @end ifclear
9178
9179 @item ^-a^/ALL_FILES^
9180 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9181 Consider all files in the make process, even the GNAT internal system
9182 files (for example, the predefined Ada library files), as well as any
9183 locked files. Locked files are files whose ALI file is write-protected.
9184 By default,
9185 @command{gnatmake} does not check these files,
9186 because the assumption is that the GNAT internal files are properly up
9187 to date, and also that any write protected ALI files have been properly
9188 installed. Note that if there is an installation problem, such that one
9189 of these files is not up to date, it will be properly caught by the
9190 binder.
9191 You may have to specify this switch if you are working on GNAT
9192 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9193 in conjunction with @option{^-f^/FORCE_COMPILE^}
9194 if you need to recompile an entire application,
9195 including run-time files, using special configuration pragmas,
9196 such as a @code{Normalize_Scalars} pragma.
9197
9198 By default
9199 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9200 internal files with
9201 @ifclear vms
9202 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9203 @end ifclear
9204 @ifset vms
9205 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9206 @end ifset
9207
9208 @item ^-b^/ACTIONS=BIND^
9209 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9210 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9211 compilation and binding, but no link.
9212 Can be combined with @option{^-l^/ACTIONS=LINK^}
9213 to do binding and linking. When not combined with
9214 @option{^-c^/ACTIONS=COMPILE^}
9215 all the units in the closure of the main program must have been previously
9216 compiled and must be up to date. The root unit specified by @var{file_name}
9217 may be given without extension, with the source extension or, if no GNAT
9218 Project File is specified, with the ALI file extension.
9219
9220 @item ^-c^/ACTIONS=COMPILE^
9221 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9222 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9223 is also specified. Do not perform linking, except if both
9224 @option{^-b^/ACTIONS=BIND^} and
9225 @option{^-l^/ACTIONS=LINK^} are also specified.
9226 If the root unit specified by @var{file_name} is not a main unit, this is the
9227 default. Otherwise @command{gnatmake} will attempt binding and linking
9228 unless all objects are up to date and the executable is more recent than
9229 the objects.
9230
9231 @item ^-C^/MAPPING^
9232 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9233 Use a temporary mapping file. A mapping file is a way to communicate to the
9234 compiler two mappings: from unit names to file names (without any directory
9235 information) and from file names to path names (with full directory
9236 information). These mappings are used by the compiler to short-circuit the path
9237 search. When @command{gnatmake} is invoked with this switch, it will create
9238 a temporary mapping file, initially populated by the project manager,
9239 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9240 Each invocation of the compiler will add the newly accessed sources to the
9241 mapping file. This will improve the source search during the next invocation
9242 of the compiler.
9243
9244 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9245 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9246 Use a specific mapping file. The file, specified as a path name (absolute or
9247 relative) by this switch, should already exist, otherwise the switch is
9248 ineffective. The specified mapping file will be communicated to the compiler.
9249 This switch is not compatible with a project file
9250 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9251 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9252
9253 @item ^-d^/DISPLAY_PROGRESS^
9254 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9255 Display progress for each source, up to date or not, as a single line
9256
9257 @smallexample
9258 completed x out of y (zz%)
9259 @end smallexample
9260
9261 If the file needs to be compiled this is displayed after the invocation of
9262 the compiler. These lines are displayed even in quiet output mode.
9263
9264 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9265 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9266 Put all object files and ALI file in directory @var{dir}.
9267 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9268 and ALI files go in the current working directory.
9269
9270 This switch cannot be used when using a project file.
9271
9272 @ifclear vms
9273 @item -eL
9274 @cindex @option{-eL} (@command{gnatmake})
9275 Follow all symbolic links when processing project files.
9276 @end ifclear
9277
9278 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9279 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9280 Output the commands for the compiler, the binder and the linker
9281 on ^standard output^SYS$OUTPUT^,
9282 instead of ^standard error^SYS$ERROR^.
9283
9284 @item ^-f^/FORCE_COMPILE^
9285 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9286 Force recompilations. Recompile all sources, even though some object
9287 files may be up to date, but don't recompile predefined or GNAT internal
9288 files or locked files (files with a write-protected ALI file),
9289 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9290
9291 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9292 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9293 When using project files, if some errors or warnings are detected during
9294 parsing and verbose mode is not in effect (no use of switch
9295 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9296 file, rather than its simple file name.
9297
9298 @item ^-g^/DEBUG^
9299 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9300 Enable debugging. This switch is simply passed to the compiler and to the
9301 linker.
9302
9303 @item ^-i^/IN_PLACE^
9304 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9305 In normal mode, @command{gnatmake} compiles all object files and ALI files
9306 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9307 then instead object files and ALI files that already exist are overwritten
9308 in place. This means that once a large project is organized into separate
9309 directories in the desired manner, then @command{gnatmake} will automatically
9310 maintain and update this organization. If no ALI files are found on the
9311 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9312 the new object and ALI files are created in the
9313 directory containing the source being compiled. If another organization
9314 is desired, where objects and sources are kept in different directories,
9315 a useful technique is to create dummy ALI files in the desired directories.
9316 When detecting such a dummy file, @command{gnatmake} will be forced to
9317 recompile the corresponding source file, and it will be put the resulting
9318 object and ALI files in the directory where it found the dummy file.
9319
9320 @item ^-j^/PROCESSES=^@var{n}
9321 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9322 @cindex Parallel make
9323 Use @var{n} processes to carry out the (re)compilations. On a
9324 multiprocessor machine compilations will occur in parallel. In the
9325 event of compilation errors, messages from various compilations might
9326 get interspersed (but @command{gnatmake} will give you the full ordered
9327 list of failing compiles at the end). If this is problematic, rerun
9328 the make process with n set to 1 to get a clean list of messages.
9329
9330 @item ^-k^/CONTINUE_ON_ERROR^
9331 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9332 Keep going. Continue as much as possible after a compilation error. To
9333 ease the programmer's task in case of compilation errors, the list of
9334 sources for which the compile fails is given when @command{gnatmake}
9335 terminates.
9336
9337 If @command{gnatmake} is invoked with several @file{file_names} and with this
9338 switch, if there are compilation errors when building an executable,
9339 @command{gnatmake} will not attempt to build the following executables.
9340
9341 @item ^-l^/ACTIONS=LINK^
9342 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9343 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9344 and linking. Linking will not be performed if combined with
9345 @option{^-c^/ACTIONS=COMPILE^}
9346 but not with @option{^-b^/ACTIONS=BIND^}.
9347 When not combined with @option{^-b^/ACTIONS=BIND^}
9348 all the units in the closure of the main program must have been previously
9349 compiled and must be up to date, and the main program needs to have been bound.
9350 The root unit specified by @var{file_name}
9351 may be given without extension, with the source extension or, if no GNAT
9352 Project File is specified, with the ALI file extension.
9353
9354 @item ^-m^/MINIMAL_RECOMPILATION^
9355 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9356 Specify that the minimum necessary amount of recompilations
9357 be performed. In this mode @command{gnatmake} ignores time
9358 stamp differences when the only
9359 modifications to a source file consist in adding/removing comments,
9360 empty lines, spaces or tabs. This means that if you have changed the
9361 comments in a source file or have simply reformatted it, using this
9362 switch will tell @command{gnatmake} not to recompile files that depend on it
9363 (provided other sources on which these files depend have undergone no
9364 semantic modifications). Note that the debugging information may be
9365 out of date with respect to the sources if the @option{-m} switch causes
9366 a compilation to be switched, so the use of this switch represents a
9367 trade-off between compilation time and accurate debugging information.
9368
9369 @item ^-M^/DEPENDENCIES_LIST^
9370 @cindex Dependencies, producing list
9371 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9372 Check if all objects are up to date. If they are, output the object
9373 dependences to @file{stdout} in a form that can be directly exploited in
9374 a @file{Makefile}. By default, each source file is prefixed with its
9375 (relative or absolute) directory name. This name is whatever you
9376 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9377 and @option{^-I^/SEARCH^} switches. If you use
9378 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9379 @option{^-q^/QUIET^}
9380 (see below), only the source file names,
9381 without relative paths, are output. If you just specify the
9382 @option{^-M^/DEPENDENCIES_LIST^}
9383 switch, dependencies of the GNAT internal system files are omitted. This
9384 is typically what you want. If you also specify
9385 the @option{^-a^/ALL_FILES^} switch,
9386 dependencies of the GNAT internal files are also listed. Note that
9387 dependencies of the objects in external Ada libraries (see switch
9388 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9389 are never reported.
9390
9391 @item ^-n^/DO_OBJECT_CHECK^
9392 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9393 Don't compile, bind, or link. Checks if all objects are up to date.
9394 If they are not, the full name of the first file that needs to be
9395 recompiled is printed.
9396 Repeated use of this option, followed by compiling the indicated source
9397 file, will eventually result in recompiling all required units.
9398
9399 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9400 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9401 Output executable name. The name of the final executable program will be
9402 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9403 name for the executable will be the name of the input file in appropriate form
9404 for an executable file on the host system.
9405
9406 This switch cannot be used when invoking @command{gnatmake} with several
9407 @file{file_names}.
9408
9409 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9410 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9411 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9412 automatically missing object directories, library directories and exec
9413 directories.
9414
9415 @item ^-P^/PROJECT_FILE=^@var{project}
9416 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9417 Use project file @var{project}. Only one such switch can be used.
9418 @xref{gnatmake and Project Files}.
9419
9420 @item ^-q^/QUIET^
9421 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9422 Quiet. When this flag is not set, the commands carried out by
9423 @command{gnatmake} are displayed.
9424
9425 @item ^-s^/SWITCH_CHECK/^
9426 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9427 Recompile if compiler switches have changed since last compilation.
9428 All compiler switches but -I and -o are taken into account in the
9429 following way:
9430 orders between different ``first letter'' switches are ignored, but
9431 orders between same switches are taken into account. For example,
9432 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9433 is equivalent to @option{-O -g}.
9434
9435 This switch is recommended when Integrated Preprocessing is used.
9436
9437 @item ^-u^/UNIQUE^
9438 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9439 Unique. Recompile at most the main files. It implies -c. Combined with
9440 -f, it is equivalent to calling the compiler directly. Note that using
9441 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9442 (@pxref{Project Files and Main Subprograms}).
9443
9444 @item ^-U^/ALL_PROJECTS^
9445 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9446 When used without a project file or with one or several mains on the command
9447 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9448 on the command line, all sources of all project files are checked and compiled
9449 if not up to date, and libraries are rebuilt, if necessary.
9450
9451 @item ^-v^/REASONS^
9452 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9453 Verbose. Display the reason for all recompilations @command{gnatmake}
9454 decides are necessary, with the highest verbosity level.
9455
9456 @item ^-vl^/LOW_VERBOSITY^
9457 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9458 Verbosity level Low. Display fewer lines than in verbosity Medium.
9459
9460 @item ^-vm^/MEDIUM_VERBOSITY^
9461 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9462 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9463
9464 @item ^-vh^/HIGH_VERBOSITY^
9465 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9466 Verbosity level High. Equivalent to ^-v^/REASONS^.
9467
9468 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9469 Indicate the verbosity of the parsing of GNAT project files.
9470 @xref{Switches Related to Project Files}.
9471
9472 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9473 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9474 Indicate that sources that are not part of any Project File may be compiled.
9475 Normally, when using Project Files, only sources that are part of a Project
9476 File may be compile. When this switch is used, a source outside of all Project
9477 Files may be compiled. The ALI file and the object file will be put in the
9478 object directory of the main Project. The compilation switches used will only
9479 be those specified on the command line. Even when
9480 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9481 command line need to be sources of a project file.
9482
9483 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9484 Indicate that external variable @var{name} has the value @var{value}.
9485 The Project Manager will use this value for occurrences of
9486 @code{external(name)} when parsing the project file.
9487 @xref{Switches Related to Project Files}.
9488
9489 @item ^-z^/NOMAIN^
9490 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9491 No main subprogram. Bind and link the program even if the unit name
9492 given on the command line is a package name. The resulting executable
9493 will execute the elaboration routines of the package and its closure,
9494 then the finalization routines.
9495
9496 @end table
9497
9498 @table @asis
9499 @item @command{gcc} @asis{switches}
9500 @ifclear vms
9501 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9502 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9503 @end ifclear
9504 @ifset vms
9505 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9506 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9507 automatically treated as a compiler switch, and passed on to all
9508 compilations that are carried out.
9509 @end ifset
9510 @end table
9511
9512 @noindent
9513 Source and library search path switches:
9514
9515 @table @option
9516 @c !sort!
9517 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9518 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9519 When looking for source files also look in directory @var{dir}.
9520 The order in which source files search is undertaken is
9521 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9522
9523 @item ^-aL^/SKIP_MISSING=^@var{dir}
9524 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9525 Consider @var{dir} as being an externally provided Ada library.
9526 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9527 files have been located in directory @var{dir}. This allows you to have
9528 missing bodies for the units in @var{dir} and to ignore out of date bodies
9529 for the same units. You still need to specify
9530 the location of the specs for these units by using the switches
9531 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9532 or @option{^-I^/SEARCH=^@var{dir}}.
9533 Note: this switch is provided for compatibility with previous versions
9534 of @command{gnatmake}. The easier method of causing standard libraries
9535 to be excluded from consideration is to write-protect the corresponding
9536 ALI files.
9537
9538 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9539 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9540 When searching for library and object files, look in directory
9541 @var{dir}. The order in which library files are searched is described in
9542 @ref{Search Paths for gnatbind}.
9543
9544 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9545 @cindex Search paths, for @command{gnatmake}
9546 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9547 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9548 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9549
9550 @item ^-I^/SEARCH=^@var{dir}
9551 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9552 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9553 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9554
9555 @item ^-I-^/NOCURRENT_DIRECTORY^
9556 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9557 @cindex Source files, suppressing search
9558 Do not look for source files in the directory containing the source
9559 file named in the command line.
9560 Do not look for ALI or object files in the directory
9561 where @command{gnatmake} was invoked.
9562
9563 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9564 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9565 @cindex Linker libraries
9566 Add directory @var{dir} to the list of directories in which the linker
9567 will search for libraries. This is equivalent to
9568 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9569 @ifclear vms
9570 Furthermore, under Windows, the sources pointed to by the libraries path
9571 set in the registry are not searched for.
9572 @end ifclear
9573
9574 @item -nostdinc
9575 @cindex @option{-nostdinc} (@command{gnatmake})
9576 Do not look for source files in the system default directory.
9577
9578 @item -nostdlib
9579 @cindex @option{-nostdlib} (@command{gnatmake})
9580 Do not look for library files in the system default directory.
9581
9582 @item --RTS=@var{rts-path}
9583 @cindex @option{--RTS} (@command{gnatmake})
9584 Specifies the default location of the runtime library. GNAT looks for the
9585 runtime
9586 in the following directories, and stops as soon as a valid runtime is found
9587 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9588 @file{ada_object_path} present):
9589
9590 @itemize @bullet
9591 @item <current directory>/$rts_path
9592
9593 @item <default-search-dir>/$rts_path
9594
9595 @item <default-search-dir>/rts-$rts_path
9596 @end itemize
9597
9598 @noindent
9599 The selected path is handled like a normal RTS path.
9600
9601 @end table
9602
9603 @node Mode Switches for gnatmake
9604 @section Mode Switches for @command{gnatmake}
9605
9606 @noindent
9607 The mode switches (referred to as @code{mode_switches}) allow the
9608 inclusion of switches that are to be passed to the compiler itself, the
9609 binder or the linker. The effect of a mode switch is to cause all
9610 subsequent switches up to the end of the switch list, or up to the next
9611 mode switch, to be interpreted as switches to be passed on to the
9612 designated component of GNAT.
9613
9614 @table @option
9615 @c !sort!
9616 @item -cargs @var{switches}
9617 @cindex @option{-cargs} (@command{gnatmake})
9618 Compiler switches. Here @var{switches} is a list of switches
9619 that are valid switches for @command{gcc}. They will be passed on to
9620 all compile steps performed by @command{gnatmake}.
9621
9622 @item -bargs @var{switches}
9623 @cindex @option{-bargs} (@command{gnatmake})
9624 Binder switches. Here @var{switches} is a list of switches
9625 that are valid switches for @code{gnatbind}. They will be passed on to
9626 all bind steps performed by @command{gnatmake}.
9627
9628 @item -largs @var{switches}
9629 @cindex @option{-largs} (@command{gnatmake})
9630 Linker switches. Here @var{switches} is a list of switches
9631 that are valid switches for @command{gnatlink}. They will be passed on to
9632 all link steps performed by @command{gnatmake}.
9633
9634 @item -margs @var{switches}
9635 @cindex @option{-margs} (@command{gnatmake})
9636 Make switches. The switches are directly interpreted by @command{gnatmake},
9637 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9638 or @option{-largs}.
9639 @end table
9640
9641 @node Notes on the Command Line
9642 @section Notes on the Command Line
9643
9644 @noindent
9645 This section contains some additional useful notes on the operation
9646 of the @command{gnatmake} command.
9647
9648 @itemize @bullet
9649 @item
9650 @cindex Recompilation, by @command{gnatmake}
9651 If @command{gnatmake} finds no ALI files, it recompiles the main program
9652 and all other units required by the main program.
9653 This means that @command{gnatmake}
9654 can be used for the initial compile, as well as during subsequent steps of
9655 the development cycle.
9656
9657 @item
9658 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9659 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9660 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9661 warning.
9662
9663 @item
9664 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9665 is used to specify both source and
9666 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9667 instead if you just want to specify
9668 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9669 if you want to specify library paths
9670 only.
9671
9672 @item
9673 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9674 This may conveniently be used to exclude standard libraries from
9675 consideration and in particular it means that the use of the
9676 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9677 unless @option{^-a^/ALL_FILES^} is also specified.
9678
9679 @item
9680 @command{gnatmake} has been designed to make the use of Ada libraries
9681 particularly convenient. Assume you have an Ada library organized
9682 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9683 of your Ada compilation units,
9684 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9685 specs of these units, but no bodies. Then to compile a unit
9686 stored in @code{main.adb}, which uses this Ada library you would just type
9687
9688 @smallexample
9689 @ifclear vms
9690 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9691 @end ifclear
9692 @ifset vms
9693 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9694            /SKIP_MISSING=@i{[OBJ_DIR]} main
9695 @end ifset
9696 @end smallexample
9697
9698 @item
9699 Using @command{gnatmake} along with the
9700 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9701 switch provides a mechanism for avoiding unnecessary recompilations. Using
9702 this switch,
9703 you can update the comments/format of your
9704 source files without having to recompile everything. Note, however, that
9705 adding or deleting lines in a source files may render its debugging
9706 info obsolete. If the file in question is a spec, the impact is rather
9707 limited, as that debugging info will only be useful during the
9708 elaboration phase of your program. For bodies the impact can be more
9709 significant. In all events, your debugger will warn you if a source file
9710 is more recent than the corresponding object, and alert you to the fact
9711 that the debugging information may be out of date.
9712 @end itemize
9713
9714 @node How gnatmake Works
9715 @section How @command{gnatmake} Works
9716
9717 @noindent
9718 Generally @command{gnatmake} automatically performs all necessary
9719 recompilations and you don't need to worry about how it works. However,
9720 it may be useful to have some basic understanding of the @command{gnatmake}
9721 approach and in particular to understand how it uses the results of
9722 previous compilations without incorrectly depending on them.
9723
9724 First a definition: an object file is considered @dfn{up to date} if the
9725 corresponding ALI file exists and if all the source files listed in the
9726 dependency section of this ALI file have time stamps matching those in
9727 the ALI file. This means that neither the source file itself nor any
9728 files that it depends on have been modified, and hence there is no need
9729 to recompile this file.
9730
9731 @command{gnatmake} works by first checking if the specified main unit is up
9732 to date. If so, no compilations are required for the main unit. If not,
9733 @command{gnatmake} compiles the main program to build a new ALI file that
9734 reflects the latest sources. Then the ALI file of the main unit is
9735 examined to find all the source files on which the main program depends,
9736 and @command{gnatmake} recursively applies the above procedure on all these
9737 files.
9738
9739 This process ensures that @command{gnatmake} only trusts the dependencies
9740 in an existing ALI file if they are known to be correct. Otherwise it
9741 always recompiles to determine a new, guaranteed accurate set of
9742 dependencies. As a result the program is compiled ``upside down'' from what may
9743 be more familiar as the required order of compilation in some other Ada
9744 systems. In particular, clients are compiled before the units on which
9745 they depend. The ability of GNAT to compile in any order is critical in
9746 allowing an order of compilation to be chosen that guarantees that
9747 @command{gnatmake} will recompute a correct set of new dependencies if
9748 necessary.
9749
9750 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9751 imported by several of the executables, it will be recompiled at most once.
9752
9753 Note: when using non-standard naming conventions
9754 (@pxref{Using Other File Names}), changing through a configuration pragmas
9755 file the version of a source and invoking @command{gnatmake} to recompile may
9756 have no effect, if the previous version of the source is still accessible
9757 by @command{gnatmake}. It may be necessary to use the switch
9758 ^-f^/FORCE_COMPILE^.
9759
9760 @node Examples of gnatmake Usage
9761 @section Examples of @command{gnatmake} Usage
9762
9763 @table @code
9764 @item gnatmake hello.adb
9765 Compile all files necessary to bind and link the main program
9766 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9767 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9768
9769 @item gnatmake main1 main2 main3
9770 Compile all files necessary to bind and link the main programs
9771 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9772 (containing unit @code{Main2}) and @file{main3.adb}
9773 (containing unit @code{Main3}) and bind and link the resulting object files
9774 to generate three executable files @file{^main1^MAIN1.EXE^},
9775 @file{^main2^MAIN2.EXE^}
9776 and @file{^main3^MAIN3.EXE^}.
9777
9778 @ifclear vms
9779 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9780 @end ifclear
9781
9782 @ifset vms
9783 @item gnatmake Main_Unit /QUIET
9784 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9785 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9786 @end ifset
9787 Compile all files necessary to bind and link the main program unit
9788 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9789 be done with optimization level 2 and the order of elaboration will be
9790 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9791 displaying commands it is executing.
9792 @end table
9793
9794 @c *************************
9795 @node Improving Performance
9796 @chapter Improving Performance
9797 @cindex Improving performance
9798
9799 @noindent
9800 This chapter presents several topics related to program performance.
9801 It first describes some of the tradeoffs that need to be considered
9802 and some of the techniques for making your program run faster.
9803 It then documents the @command{gnatelim} tool and unused subprogram/data
9804 elimination feature, which can reduce the size of program executables.
9805
9806 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9807 driver (see @ref{The GNAT Driver and Project Files}).
9808
9809 @ifnottex
9810 @menu
9811 * Performance Considerations::
9812 * Text_IO Suggestions::
9813 * Reducing Size of Ada Executables with gnatelim::
9814 * Reducing Size of Executables with unused subprogram/data elimination::
9815 @end menu
9816 @end ifnottex
9817
9818 @c *****************************
9819 @node Performance Considerations
9820 @section Performance Considerations
9821
9822 @noindent
9823 The GNAT system provides a number of options that allow a trade-off
9824 between
9825
9826 @itemize @bullet
9827 @item
9828 performance of the generated code
9829
9830 @item
9831 speed of compilation
9832
9833 @item
9834 minimization of dependences and recompilation
9835
9836 @item
9837 the degree of run-time checking.
9838 @end itemize
9839
9840 @noindent
9841 The defaults (if no options are selected) aim at improving the speed
9842 of compilation and minimizing dependences, at the expense of performance
9843 of the generated code:
9844
9845 @itemize @bullet
9846 @item
9847 no optimization
9848
9849 @item
9850 no inlining of subprogram calls
9851
9852 @item
9853 all run-time checks enabled except overflow and elaboration checks
9854 @end itemize
9855
9856 @noindent
9857 These options are suitable for most program development purposes. This
9858 chapter describes how you can modify these choices, and also provides
9859 some guidelines on debugging optimized code.
9860
9861 @menu
9862 * Controlling Run-Time Checks::
9863 * Use of Restrictions::
9864 * Optimization Levels::
9865 * Debugging Optimized Code::
9866 * Inlining of Subprograms::
9867 * Other Optimization Switches::
9868 * Optimization and Strict Aliasing::
9869
9870 @ifset vms
9871 * Coverage Analysis::
9872 @end ifset
9873 @end menu
9874
9875 @node Controlling Run-Time Checks
9876 @subsection Controlling Run-Time Checks
9877
9878 @noindent
9879 By default, GNAT generates all run-time checks, except integer overflow
9880 checks, stack overflow checks, and checks for access before elaboration on
9881 subprogram calls. The latter are not required in default mode, because all
9882 necessary checking is done at compile time.
9883 @cindex @option{-gnatp} (@command{gcc})
9884 @cindex @option{-gnato} (@command{gcc})
9885 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9886 be modified. @xref{Run-Time Checks}.
9887
9888 Our experience is that the default is suitable for most development
9889 purposes.
9890
9891 We treat integer overflow specially because these
9892 are quite expensive and in our experience are not as important as other
9893 run-time checks in the development process. Note that division by zero
9894 is not considered an overflow check, and divide by zero checks are
9895 generated where required by default.
9896
9897 Elaboration checks are off by default, and also not needed by default, since
9898 GNAT uses a static elaboration analysis approach that avoids the need for
9899 run-time checking. This manual contains a full chapter discussing the issue
9900 of elaboration checks, and if the default is not satisfactory for your use,
9901 you should read this chapter.
9902
9903 For validity checks, the minimal checks required by the Ada Reference
9904 Manual (for case statements and assignments to array elements) are on
9905 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9906 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9907 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9908 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9909 are also suppressed entirely if @option{-gnatp} is used.
9910
9911 @cindex Overflow checks
9912 @cindex Checks, overflow
9913 @findex Suppress
9914 @findex Unsuppress
9915 @cindex pragma Suppress
9916 @cindex pragma Unsuppress
9917 Note that the setting of the switches controls the default setting of
9918 the checks. They may be modified using either @code{pragma Suppress} (to
9919 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9920 checks) in the program source.
9921
9922 @node Use of Restrictions
9923 @subsection Use of Restrictions
9924
9925 @noindent
9926 The use of pragma Restrictions allows you to control which features are
9927 permitted in your program. Apart from the obvious point that if you avoid
9928 relatively expensive features like finalization (enforceable by the use
9929 of pragma Restrictions (No_Finalization), the use of this pragma does not
9930 affect the generated code in most cases.
9931
9932 One notable exception to this rule is that the possibility of task abort
9933 results in some distributed overhead, particularly if finalization or
9934 exception handlers are used. The reason is that certain sections of code
9935 have to be marked as non-abortable.
9936
9937 If you use neither the @code{abort} statement, nor asynchronous transfer
9938 of control (@code{select @dots{} then abort}), then this distributed overhead
9939 is removed, which may have a general positive effect in improving
9940 overall performance.  Especially code involving frequent use of tasking
9941 constructs and controlled types will show much improved performance.
9942 The relevant restrictions pragmas are
9943
9944 @smallexample @c ada
9945    pragma Restrictions (No_Abort_Statements);
9946    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9947 @end smallexample
9948
9949 @noindent
9950 It is recommended that these restriction pragmas be used if possible. Note
9951 that this also means that you can write code without worrying about the
9952 possibility of an immediate abort at any point.
9953
9954 @node Optimization Levels
9955 @subsection Optimization Levels
9956 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9957
9958 @noindent
9959 Without any optimization ^option,^qualifier,^
9960 the compiler's goal is to reduce the cost of
9961 compilation and to make debugging produce the expected results.
9962 Statements are independent: if you stop the program with a breakpoint between
9963 statements, you can then assign a new value to any variable or change
9964 the program counter to any other statement in the subprogram and get exactly
9965 the results you would expect from the source code.
9966
9967 Turning on optimization makes the compiler attempt to improve the
9968 performance and/or code size at the expense of compilation time and
9969 possibly the ability to debug the program.
9970
9971 If you use multiple
9972 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9973 the last such option is the one that is effective.
9974
9975 @noindent
9976 The default is optimization off. This results in the fastest compile
9977 times, but GNAT makes absolutely no attempt to optimize, and the
9978 generated programs are considerably larger and slower than when
9979 optimization is enabled. You can use the
9980 @ifclear vms
9981 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9982 @option{-O2}, @option{-O3}, and @option{-Os})
9983 @end ifclear
9984 @ifset vms
9985 @code{OPTIMIZE} qualifier
9986 @end ifset
9987 to @command{gcc} to control the optimization level:
9988
9989 @table @option
9990 @item ^-O0^/OPTIMIZE=NONE^
9991 No optimization (the default);
9992 generates unoptimized code but has
9993 the fastest compilation time.
9994
9995 Note that many other compilers do fairly extensive optimization
9996 even if ``no optimization'' is specified. With gcc, it is
9997 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9998 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9999 really does mean no optimization at all. This difference between
10000 gcc and other compilers should be kept in mind when doing
10001 performance comparisons.
10002
10003 @item ^-O1^/OPTIMIZE=SOME^
10004 Moderate optimization;
10005 optimizes reasonably well but does not
10006 degrade compilation time significantly.
10007
10008 @item ^-O2^/OPTIMIZE=ALL^
10009 @ifset vms
10010 @itemx /OPTIMIZE=DEVELOPMENT
10011 @end ifset
10012 Full optimization;
10013 generates highly optimized code and has
10014 the slowest compilation time.
10015
10016 @item ^-O3^/OPTIMIZE=INLINING^
10017 Full optimization as in @option{-O2},
10018 and also attempts automatic inlining of small
10019 subprograms within a unit (@pxref{Inlining of Subprograms}).
10020
10021 @item ^-Os^/OPTIMIZE=SPACE^
10022 Optimize space usage of resulting program.
10023 @end table
10024
10025 @noindent
10026 Higher optimization levels perform more global transformations on the
10027 program and apply more expensive analysis algorithms in order to generate
10028 faster and more compact code. The price in compilation time, and the
10029 resulting improvement in execution time,
10030 both depend on the particular application and the hardware environment.
10031 You should experiment to find the best level for your application.
10032
10033 Since the precise set of optimizations done at each level will vary from
10034 release to release (and sometime from target to target), it is best to think
10035 of the optimization settings in general terms.
10036 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10037 the GNU Compiler Collection (GCC)}, for details about
10038 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10039 individually enable or disable specific optimizations.
10040
10041 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10042 been tested extensively at all optimization levels. There are some bugs
10043 which appear only with optimization turned on, but there have also been
10044 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10045 level of optimization does not improve the reliability of the code
10046 generator, which in practice is highly reliable at all optimization
10047 levels.
10048
10049 Note regarding the use of @option{-O3}: The use of this optimization level
10050 is generally discouraged with GNAT, since it often results in larger
10051 executables which run more slowly. See further discussion of this point
10052 in @ref{Inlining of Subprograms}.
10053
10054 @node Debugging Optimized Code
10055 @subsection Debugging Optimized Code
10056 @cindex Debugging optimized code
10057 @cindex Optimization and debugging
10058
10059 @noindent
10060 Although it is possible to do a reasonable amount of debugging at
10061 @ifclear vms
10062 nonzero optimization levels,
10063 the higher the level the more likely that
10064 @end ifclear
10065 @ifset vms
10066 @option{/OPTIMIZE} settings other than @code{NONE},
10067 such settings will make it more likely that
10068 @end ifset
10069 source-level constructs will have been eliminated by optimization.
10070 For example, if a loop is strength-reduced, the loop
10071 control variable may be completely eliminated and thus cannot be
10072 displayed in the debugger.
10073 This can only happen at @option{-O2} or @option{-O3}.
10074 Explicit temporary variables that you code might be eliminated at
10075 ^level^setting^ @option{-O1} or higher.
10076
10077 The use of the @option{^-g^/DEBUG^} switch,
10078 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10079 which is needed for source-level debugging,
10080 affects the size of the program executable on disk,
10081 and indeed the debugging information can be quite large.
10082 However, it has no effect on the generated code (and thus does not
10083 degrade performance)
10084
10085 Since the compiler generates debugging tables for a compilation unit before
10086 it performs optimizations, the optimizing transformations may invalidate some
10087 of the debugging data.  You therefore need to anticipate certain
10088 anomalous situations that may arise while debugging optimized code.
10089 These are the most common cases:
10090
10091 @enumerate
10092 @item
10093 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10094 commands show
10095 the PC bouncing back and forth in the code.  This may result from any of
10096 the following optimizations:
10097
10098 @itemize @bullet
10099 @item
10100 @i{Common subexpression elimination:} using a single instance of code for a
10101 quantity that the source computes several times.  As a result you
10102 may not be able to stop on what looks like a statement.
10103
10104 @item
10105 @i{Invariant code motion:} moving an expression that does not change within a
10106 loop, to the beginning of the loop.
10107
10108 @item
10109 @i{Instruction scheduling:} moving instructions so as to
10110 overlap loads and stores (typically) with other code, or in
10111 general to move computations of values closer to their uses. Often
10112 this causes you to pass an assignment statement without the assignment
10113 happening and then later bounce back to the statement when the
10114 value is actually needed.  Placing a breakpoint on a line of code
10115 and then stepping over it may, therefore, not always cause all the
10116 expected side-effects.
10117 @end itemize
10118
10119 @item
10120 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10121 two identical pieces of code are merged and the program counter suddenly
10122 jumps to a statement that is not supposed to be executed, simply because
10123 it (and the code following) translates to the same thing as the code
10124 that @emph{was} supposed to be executed.  This effect is typically seen in
10125 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10126 a @code{break} in a C @code{^switch^switch^} statement.
10127
10128 @item
10129 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10130 There are various reasons for this effect:
10131
10132 @itemize @bullet
10133 @item
10134 In a subprogram prologue, a parameter may not yet have been moved to its
10135 ``home''.
10136
10137 @item
10138 A variable may be dead, and its register re-used.  This is
10139 probably the most common cause.
10140
10141 @item
10142 As mentioned above, the assignment of a value to a variable may
10143 have been moved.
10144
10145 @item
10146 A variable may be eliminated entirely by value propagation or
10147 other means.  In this case, GCC may incorrectly generate debugging
10148 information for the variable
10149 @end itemize
10150
10151 @noindent
10152 In general, when an unexpected value appears for a local variable or parameter
10153 you should first ascertain if that value was actually computed by
10154 your program, as opposed to being incorrectly reported by the debugger.
10155 Record fields or
10156 array elements in an object designated by an access value
10157 are generally less of a problem, once you have ascertained that the access
10158 value is sensible.
10159 Typically, this means checking variables in the preceding code and in the
10160 calling subprogram to verify that the value observed is explainable from other
10161 values (one must apply the procedure recursively to those
10162 other values); or re-running the code and stopping a little earlier
10163 (perhaps before the call) and stepping to better see how the variable obtained
10164 the value in question; or continuing to step @emph{from} the point of the
10165 strange value to see if code motion had simply moved the variable's
10166 assignments later.
10167 @end enumerate
10168
10169 @noindent
10170 In light of such anomalies, a recommended technique is to use @option{-O0}
10171 early in the software development cycle, when extensive debugging capabilities
10172 are most needed, and then move to @option{-O1} and later @option{-O2} as
10173 the debugger becomes less critical.
10174 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10175 a release management issue.
10176 @ifclear vms
10177 Note that if you use @option{-g} you can then use the @command{strip} program
10178 on the resulting executable,
10179 which removes both debugging information and global symbols.
10180 @end ifclear
10181
10182 @node Inlining of Subprograms
10183 @subsection Inlining of Subprograms
10184
10185 @noindent
10186 A call to a subprogram in the current unit is inlined if all the
10187 following conditions are met:
10188
10189 @itemize @bullet
10190 @item
10191 The optimization level is at least @option{-O1}.
10192
10193 @item
10194 The called subprogram is suitable for inlining: It must be small enough
10195 and not contain something that @command{gcc} cannot support in inlined
10196 subprograms.
10197
10198 @item
10199 @cindex pragma Inline
10200 @findex Inline
10201 Either @code{pragma Inline} applies to the subprogram, or it is local
10202 to the unit and called once from within it, or it is small and automatic
10203 inlining (optimization level @option{-O3}) is specified.
10204 @end itemize
10205
10206 @noindent
10207 Calls to subprograms in @code{with}'ed units are normally not inlined.
10208 To achieve actual inlining (that is, replacement of the call by the code
10209 in the body of the subprogram), the following conditions must all be true.
10210
10211 @itemize @bullet
10212 @item
10213 The optimization level is at least @option{-O1}.
10214
10215 @item
10216 The called subprogram is suitable for inlining: It must be small enough
10217 and not contain something that @command{gcc} cannot support in inlined
10218 subprograms.
10219
10220 @item
10221 The call appears in a body (not in a package spec).
10222
10223 @item
10224 There is a @code{pragma Inline} for the subprogram.
10225
10226 @item
10227 @cindex @option{-gnatn} (@command{gcc})
10228 The @option{^-gnatn^/INLINE^} switch
10229 is used in the @command{gcc} command line
10230 @end itemize
10231
10232 Even if all these conditions are met, it may not be possible for
10233 the compiler to inline the call, due to the length of the body,
10234 or features in the body that make it impossible for the compiler
10235 to do the inlining.
10236
10237 Note that specifying the @option{-gnatn} switch causes additional
10238 compilation dependencies. Consider the following:
10239
10240 @smallexample @c ada
10241 @cartouche
10242 package R is
10243    procedure Q;
10244    pragma Inline (Q);
10245 end R;
10246 package body R is
10247    @dots{}
10248 end R;
10249
10250 with R;
10251 procedure Main is
10252 begin
10253    @dots{}
10254    R.Q;
10255 end Main;
10256 @end cartouche
10257 @end smallexample
10258
10259 @noindent
10260 With the default behavior (no @option{-gnatn} switch specified), the
10261 compilation of the @code{Main} procedure depends only on its own source,
10262 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10263 means that editing the body of @code{R} does not require recompiling
10264 @code{Main}.
10265
10266 On the other hand, the call @code{R.Q} is not inlined under these
10267 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10268 is compiled, the call will be inlined if the body of @code{Q} is small
10269 enough, but now @code{Main} depends on the body of @code{R} in
10270 @file{r.adb} as well as on the spec. This means that if this body is edited,
10271 the main program must be recompiled. Note that this extra dependency
10272 occurs whether or not the call is in fact inlined by @command{gcc}.
10273
10274 The use of front end inlining with @option{-gnatN} generates similar
10275 additional dependencies.
10276
10277 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10278 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10279 can be used to prevent
10280 all inlining. This switch overrides all other conditions and ensures
10281 that no inlining occurs. The extra dependences resulting from
10282 @option{-gnatn} will still be active, even if
10283 this switch is used to suppress the resulting inlining actions.
10284
10285 @cindex @option{-fno-inline-functions} (@command{gcc})
10286 Note: The @option{-fno-inline-functions} switch can be used to prevent
10287 automatic inlining of small subprograms if @option{-O3} is used.
10288
10289 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10290 Note: The @option{-fno-inline-functions-called-once} switch
10291 can be used to prevent inlining of subprograms local to the unit
10292 and called once from within it if @option{-O1} is used.
10293
10294 Note regarding the use of @option{-O3}: There is no difference in inlining
10295 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10296 pragma @code{Inline} assuming the use of @option{-gnatn}
10297 or @option{-gnatN} (the switches that activate inlining). If you have used
10298 pragma @code{Inline} in appropriate cases, then it is usually much better
10299 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10300 in this case only has the effect of inlining subprograms you did not
10301 think should be inlined. We often find that the use of @option{-O3} slows
10302 down code by performing excessive inlining, leading to increased instruction
10303 cache pressure from the increased code size. So the bottom line here is
10304 that you should not automatically assume that @option{-O3} is better than
10305 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10306 it actually improves performance.
10307
10308 @node Other Optimization Switches
10309 @subsection Other Optimization Switches
10310 @cindex Optimization Switches
10311
10312 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10313 @command{gcc} optimization switches are potentially usable. These switches
10314 have not been extensively tested with GNAT but can generally be expected
10315 to work. Examples of switches in this category are
10316 @option{-funroll-loops} and
10317 the various target-specific @option{-m} options (in particular, it has been
10318 observed that @option{-march=pentium4} can significantly improve performance
10319 on appropriate machines). For full details of these switches, see
10320 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10321 the GNU Compiler Collection (GCC)}.
10322
10323 @node Optimization and Strict Aliasing
10324 @subsection Optimization and Strict Aliasing
10325 @cindex Aliasing
10326 @cindex Strict Aliasing
10327 @cindex No_Strict_Aliasing
10328
10329 @noindent
10330 The strong typing capabilities of Ada allow an optimizer to generate
10331 efficient code in situations where other languages would be forced to
10332 make worst case assumptions preventing such optimizations. Consider
10333 the following example:
10334
10335 @smallexample @c ada
10336 @cartouche
10337 procedure R is
10338    type Int1 is new Integer;
10339    type Int2 is new Integer;
10340    type Int1A is access Int1;
10341    type Int2A is access Int2;
10342    Int1V : Int1A;
10343    Int2V : Int2A;
10344    @dots{}
10345
10346 begin
10347    @dots{}
10348    for J in Data'Range loop
10349       if Data (J) = Int1V.all then
10350          Int2V.all := Int2V.all + 1;
10351       end if;
10352    end loop;
10353    @dots{}
10354 end R;
10355 @end cartouche
10356 @end smallexample
10357
10358 @noindent
10359 In this example, since the variable @code{Int1V} can only access objects
10360 of type @code{Int1}, and @code{Int2V} can only access objects of type
10361 @code{Int2}, there is no possibility that the assignment to
10362 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10363 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10364 for all iterations of the loop and avoid the extra memory reference
10365 required to dereference it each time through the loop.
10366
10367 This kind of optimization, called strict aliasing analysis, is
10368 triggered by specifying an optimization level of @option{-O2} or
10369 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10370 when access values are involved.
10371
10372 However, although this optimization is always correct in terms of
10373 the formal semantics of the Ada Reference Manual, difficulties can
10374 arise if features like @code{Unchecked_Conversion} are used to break
10375 the typing system. Consider the following complete program example:
10376
10377 @smallexample @c ada
10378 @cartouche
10379 package p1 is
10380    type int1 is new integer;
10381    type int2 is new integer;
10382    type a1 is access int1;
10383    type a2 is access int2;
10384 end p1;
10385
10386 with p1; use p1;
10387 package p2 is
10388    function to_a2 (Input : a1) return a2;
10389 end p2;
10390
10391 with Unchecked_Conversion;
10392 package body p2 is
10393    function to_a2 (Input : a1) return a2 is
10394       function to_a2u is
10395         new Unchecked_Conversion (a1, a2);
10396    begin
10397       return to_a2u (Input);
10398    end to_a2;
10399 end p2;
10400
10401 with p2; use p2;
10402 with p1; use p1;
10403 with Text_IO; use Text_IO;
10404 procedure m is
10405    v1 : a1 := new int1;
10406    v2 : a2 := to_a2 (v1);
10407 begin
10408    v1.all := 1;
10409    v2.all := 0;
10410    put_line (int1'image (v1.all));
10411 end;
10412 @end cartouche
10413 @end smallexample
10414
10415 @noindent
10416 This program prints out 0 in @option{-O0} or @option{-O1}
10417 mode, but it prints out 1 in @option{-O2} mode. That's
10418 because in strict aliasing mode, the compiler can and
10419 does assume that the assignment to @code{v2.all} could not
10420 affect the value of @code{v1.all}, since different types
10421 are involved.
10422
10423 This behavior is not a case of non-conformance with the standard, since
10424 the Ada RM specifies that an unchecked conversion where the resulting
10425 bit pattern is not a correct value of the target type can result in an
10426 abnormal value and attempting to reference an abnormal value makes the
10427 execution of a program erroneous.  That's the case here since the result
10428 does not point to an object of type @code{int2}.  This means that the
10429 effect is entirely unpredictable.
10430
10431 However, although that explanation may satisfy a language
10432 lawyer, in practice an applications programmer expects an
10433 unchecked conversion involving pointers to create true
10434 aliases and the behavior of printing 1 seems plain wrong.
10435 In this case, the strict aliasing optimization is unwelcome.
10436
10437 Indeed the compiler recognizes this possibility, and the
10438 unchecked conversion generates a warning:
10439
10440 @smallexample
10441 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10442 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10443 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10444 @end smallexample
10445
10446 @noindent
10447 Unfortunately the problem is recognized when compiling the body of
10448 package @code{p2}, but the actual "bad" code is generated while
10449 compiling the body of @code{m} and this latter compilation does not see
10450 the suspicious @code{Unchecked_Conversion}.
10451
10452 As implied by the warning message, there are approaches you can use to
10453 avoid the unwanted strict aliasing optimization in a case like this.
10454
10455 One possibility is to simply avoid the use of @option{-O2}, but
10456 that is a bit drastic, since it throws away a number of useful
10457 optimizations that do not involve strict aliasing assumptions.
10458
10459 A less drastic approach is to compile the program using the
10460 option @option{-fno-strict-aliasing}. Actually it is only the
10461 unit containing the dereferencing of the suspicious pointer
10462 that needs to be compiled. So in this case, if we compile
10463 unit @code{m} with this switch, then we get the expected
10464 value of zero printed. Analyzing which units might need
10465 the switch can be painful, so a more reasonable approach
10466 is to compile the entire program with options @option{-O2}
10467 and @option{-fno-strict-aliasing}. If the performance is
10468 satisfactory with this combination of options, then the
10469 advantage is that the entire issue of possible "wrong"
10470 optimization due to strict aliasing is avoided.
10471
10472 To avoid the use of compiler switches, the configuration
10473 pragma @code{No_Strict_Aliasing} with no parameters may be
10474 used to specify that for all access types, the strict
10475 aliasing optimization should be suppressed.
10476
10477 However, these approaches are still overkill, in that they causes
10478 all manipulations of all access values to be deoptimized. A more
10479 refined approach is to concentrate attention on the specific
10480 access type identified as problematic.
10481
10482 First, if a careful analysis of uses of the pointer shows
10483 that there are no possible problematic references, then
10484 the warning can be suppressed by bracketing the
10485 instantiation of @code{Unchecked_Conversion} to turn
10486 the warning off:
10487
10488 @smallexample @c ada
10489    pragma Warnings (Off);
10490    function to_a2u is
10491      new Unchecked_Conversion (a1, a2);
10492    pragma Warnings (On);
10493 @end smallexample
10494
10495 @noindent
10496 Of course that approach is not appropriate for this particular
10497 example, since indeed there is a problematic reference. In this
10498 case we can take one of two other approaches.
10499
10500 The first possibility is to move the instantiation of unchecked
10501 conversion to the unit in which the type is declared. In
10502 this example, we would move the instantiation of
10503 @code{Unchecked_Conversion} from the body of package
10504 @code{p2} to the spec of package @code{p1}. Now the
10505 warning disappears. That's because any use of the
10506 access type knows there is a suspicious unchecked
10507 conversion, and the strict aliasing optimization
10508 is automatically suppressed for the type.
10509
10510 If it is not practical to move the unchecked conversion to the same unit
10511 in which the destination access type is declared (perhaps because the
10512 source type is not visible in that unit), you may use pragma
10513 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10514 same declarative sequence as the declaration of the access type:
10515
10516 @smallexample @c ada
10517    type a2 is access int2;
10518    pragma No_Strict_Aliasing (a2);
10519 @end smallexample
10520
10521 @noindent
10522 Here again, the compiler now knows that the strict aliasing optimization
10523 should be suppressed for any reference to type @code{a2} and the
10524 expected behavior is obtained.
10525
10526 Finally, note that although the compiler can generate warnings for
10527 simple cases of unchecked conversions, there are tricker and more
10528 indirect ways of creating type incorrect aliases which the compiler
10529 cannot detect. Examples are the use of address overlays and unchecked
10530 conversions involving composite types containing access types as
10531 components. In such cases, no warnings are generated, but there can
10532 still be aliasing problems. One safe coding practice is to forbid the
10533 use of address clauses for type overlaying, and to allow unchecked
10534 conversion only for primitive types. This is not really a significant
10535 restriction since any possible desired effect can be achieved by
10536 unchecked conversion of access values.
10537
10538 The aliasing analysis done in strict aliasing mode can certainly
10539 have significant benefits. We have seen cases of large scale
10540 application code where the time is increased by up to 5% by turning
10541 this optimization off. If you have code that includes significant
10542 usage of unchecked conversion, you might want to just stick with
10543 @option{-O1} and avoid the entire issue. If you get adequate
10544 performance at this level of optimization level, that's probably
10545 the safest approach. If tests show that you really need higher
10546 levels of optimization, then you can experiment with @option{-O2}
10547 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10548 has on size and speed of the code. If you really need to use
10549 @option{-O2} with strict aliasing in effect, then you should
10550 review any uses of unchecked conversion of access types,
10551 particularly if you are getting the warnings described above.
10552
10553 @ifset vms
10554 @node Coverage Analysis
10555 @subsection Coverage Analysis
10556
10557 @noindent
10558 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10559 the user to determine the distribution of execution time across a program,
10560 @pxref{Profiling} for details of usage.
10561 @end ifset
10562
10563
10564 @node Text_IO Suggestions
10565 @section @code{Text_IO} Suggestions
10566 @cindex @code{Text_IO} and performance
10567
10568 @noindent
10569 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10570 the requirement of maintaining page and line counts. If performance
10571 is critical, a recommendation is to use @code{Stream_IO} instead of
10572 @code{Text_IO} for volume output, since this package has less overhead.
10573
10574 If @code{Text_IO} must be used, note that by default output to the standard
10575 output and standard error files is unbuffered (this provides better
10576 behavior when output statements are used for debugging, or if the
10577 progress of a program is observed by tracking the output, e.g. by
10578 using the Unix @command{tail -f} command to watch redirected output.
10579
10580 If you are generating large volumes of output with @code{Text_IO} and
10581 performance is an important factor, use a designated file instead
10582 of the standard output file, or change the standard output file to
10583 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10584
10585
10586
10587 @node Reducing Size of Ada Executables with gnatelim
10588 @section Reducing Size of Ada Executables with @code{gnatelim}
10589 @findex gnatelim
10590
10591 @noindent
10592 This section describes @command{gnatelim}, a tool which detects unused
10593 subprograms and helps the compiler to create a smaller executable for your
10594 program.
10595
10596 @menu
10597 * About gnatelim::
10598 * Running gnatelim::
10599 * Correcting the List of Eliminate Pragmas::
10600 * Making Your Executables Smaller::
10601 * Summary of the gnatelim Usage Cycle::
10602 @end menu
10603
10604 @node About gnatelim
10605 @subsection About @code{gnatelim}
10606
10607 @noindent
10608 When a program shares a set of Ada
10609 packages with other programs, it may happen that this program uses
10610 only a fraction of the subprograms defined in these packages. The code
10611 created for these unused subprograms increases the size of the executable.
10612
10613 @code{gnatelim} tracks unused subprograms in an Ada program and
10614 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10615 subprograms that are declared but never called. By placing the list of
10616 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10617 recompiling your program, you may decrease the size of its executable,
10618 because the compiler will not generate the code for 'eliminated' subprograms.
10619 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10620 information about this pragma.
10621
10622 @code{gnatelim} needs as its input data the name of the main subprogram
10623 and a bind file for a main subprogram.
10624
10625 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10626 the main subprogram. @code{gnatelim} can work with both Ada and C
10627 bind files; when both are present, it uses the Ada bind file.
10628 The following commands will build the program and create the bind file:
10629
10630 @smallexample
10631 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10632 $ gnatbind main_prog
10633 @end smallexample
10634
10635 Note that @code{gnatelim} needs neither object nor ALI files.
10636
10637 @node Running gnatelim
10638 @subsection Running @code{gnatelim}
10639
10640 @noindent
10641 @code{gnatelim} has the following command-line interface:
10642
10643 @smallexample
10644 $ gnatelim @ovar{options} name
10645 @end smallexample
10646
10647 @noindent
10648 @code{name} should be a name of a source file that contains the main subprogram
10649 of a program (partition).
10650
10651 @code{gnatelim} has the following switches:
10652
10653 @table @option
10654 @c !sort!
10655 @item ^-q^/QUIET^
10656 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10657 Quiet mode: by default @code{gnatelim} outputs to the standard error
10658 stream the number of program units left to be processed. This option turns
10659 this trace off.
10660
10661 @item ^-v^/VERBOSE^
10662 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10663 Verbose mode: @code{gnatelim} version information is printed as Ada
10664 comments to the standard output stream. Also, in addition to the number of
10665 program units left @code{gnatelim} will output the name of the current unit
10666 being processed.
10667
10668 @item ^-a^/ALL^
10669 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10670 Also look for subprograms from the GNAT run time that can be eliminated. Note
10671 that when @file{gnat.adc} is produced using this switch, the entire program
10672 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10673
10674 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10675 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10676 When looking for source files also look in directory @var{dir}. Specifying
10677 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10678 sources in the current directory.
10679
10680 @item ^-b^/BIND_FILE=^@var{bind_file}
10681 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10682 Specifies @var{bind_file} as the bind file to process. If not set, the name
10683 of the bind file is computed from the full expanded Ada name
10684 of a main subprogram.
10685
10686 @item ^-C^/CONFIG_FILE=^@var{config_file}
10687 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10688 Specifies a file @var{config_file} that contains configuration pragmas. The
10689 file must be specified with full path.
10690
10691 @item ^--GCC^/COMPILER^=@var{compiler_name}
10692 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10693 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10694 available on the path.
10695
10696 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10697 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10698 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10699 available on the path.
10700 @end table
10701
10702 @noindent
10703 @code{gnatelim} sends its output to the standard output stream, and all the
10704 tracing and debug information is sent to the standard error stream.
10705 In order to produce a proper GNAT configuration file
10706 @file{gnat.adc}, redirection must be used:
10707
10708 @smallexample
10709 @ifset vms
10710 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10711 @end ifset
10712 @ifclear vms
10713 $ gnatelim main_prog.adb > gnat.adc
10714 @end ifclear
10715 @end smallexample
10716
10717 @ifclear vms
10718 @noindent
10719 or
10720
10721 @smallexample
10722 $ gnatelim main_prog.adb >> gnat.adc
10723 @end smallexample
10724
10725 @noindent
10726 in order to append the @code{gnatelim} output to the existing contents of
10727 @file{gnat.adc}.
10728 @end ifclear
10729
10730 @node Correcting the List of Eliminate Pragmas
10731 @subsection Correcting the List of Eliminate Pragmas
10732
10733 @noindent
10734 In some rare cases @code{gnatelim} may try to eliminate
10735 subprograms that are actually called in the program. In this case, the
10736 compiler will generate an error message of the form:
10737
10738 @smallexample
10739 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10740 @end smallexample
10741
10742 @noindent
10743 You will need to manually remove the wrong @code{Eliminate} pragmas from
10744 the @file{gnat.adc} file. You should recompile your program
10745 from scratch after that, because you need a consistent @file{gnat.adc} file
10746 during the entire compilation.
10747
10748 @node Making Your Executables Smaller
10749 @subsection Making Your Executables Smaller
10750
10751 @noindent
10752 In order to get a smaller executable for your program you now have to
10753 recompile the program completely with the new @file{gnat.adc} file
10754 created by @code{gnatelim} in your current directory:
10755
10756 @smallexample
10757 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10758 @end smallexample
10759
10760 @noindent
10761 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10762 recompile everything
10763 with the set of pragmas @code{Eliminate} that you have obtained with
10764 @command{gnatelim}).
10765
10766 Be aware that the set of @code{Eliminate} pragmas is specific to each
10767 program. It is not recommended to merge sets of @code{Eliminate}
10768 pragmas created for different programs in one @file{gnat.adc} file.
10769
10770 @node Summary of the gnatelim Usage Cycle
10771 @subsection Summary of the gnatelim Usage Cycle
10772
10773 @noindent
10774 Here is a quick summary of the steps to be taken in order to reduce
10775 the size of your executables with @code{gnatelim}. You may use
10776 other GNAT options to control the optimization level,
10777 to produce the debugging information, to set search path, etc.
10778
10779 @enumerate
10780 @item
10781 Produce a bind file
10782
10783 @smallexample
10784 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10785 $ gnatbind main_prog
10786 @end smallexample
10787
10788 @item
10789 Generate a list of @code{Eliminate} pragmas
10790 @smallexample
10791 @ifset vms
10792 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10793 @end ifset
10794 @ifclear vms
10795 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10796 @end ifclear
10797 @end smallexample
10798
10799 @item
10800 Recompile the application
10801
10802 @smallexample
10803 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10804 @end smallexample
10805
10806 @end enumerate
10807
10808 @node Reducing Size of Executables with unused subprogram/data elimination
10809 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10810 @findex unused subprogram/data elimination
10811
10812 @noindent
10813 This section describes how you can eliminate unused subprograms and data from
10814 your executable just by setting options at compilation time.
10815
10816 @menu
10817 * About unused subprogram/data elimination::
10818 * Compilation options::
10819 * Example of unused subprogram/data elimination::
10820 @end menu
10821
10822 @node About unused subprogram/data elimination
10823 @subsection About unused subprogram/data elimination
10824
10825 @noindent
10826 By default, an executable contains all code and data of its composing objects
10827 (directly linked or coming from statically linked libraries), even data or code
10828 never used by this executable.
10829
10830 This feature will allow you to eliminate such unused code from your
10831 executable, making it smaller (in disk and in memory).
10832
10833 This functionality is available on all Linux platforms except for the IA-64
10834 architecture and on all cross platforms using the ELF binary file format.
10835 In both cases GNU binutils version 2.16 or later are required to enable it.
10836
10837 @node Compilation options
10838 @subsection Compilation options
10839
10840 @noindent
10841 The operation of eliminating the unused code and data from the final executable
10842 is directly performed by the linker.
10843
10844 In order to do this, it has to work with objects compiled with the
10845 following options:
10846 @option{-ffunction-sections} @option{-fdata-sections}.
10847 @cindex @option{-ffunction-sections} (@command{gcc})
10848 @cindex @option{-fdata-sections} (@command{gcc})
10849 These options are usable with C and Ada files.
10850 They will place respectively each
10851 function or data in a separate section in the resulting object file.
10852
10853 Once the objects and static libraries are created with these options, the
10854 linker can perform the dead code elimination. You can do this by setting
10855 the @option{-Wl,--gc-sections} option to gcc command or in the
10856 @option{-largs} section of @command{gnatmake}. This will perform a
10857 garbage collection of code and data never referenced.
10858
10859 If the linker performs a partial link (@option{-r} ld linker option), then you
10860 will need to provide one or several entry point using the
10861 @option{-e} / @option{--entry} ld option.
10862
10863 Note that objects compiled without the @option{-ffunction-sections} and
10864 @option{-fdata-sections} options can still be linked with the executable.
10865 However, no dead code elimination will be performed on those objects (they will
10866 be linked as is).
10867
10868 The GNAT static library is now compiled with -ffunction-sections and
10869 -fdata-sections on some platforms. This allows you to eliminate the unused code
10870 and data of the GNAT library from your executable.
10871
10872 @node Example of unused subprogram/data elimination
10873 @subsection Example of unused subprogram/data elimination
10874
10875 @noindent
10876 Here is a simple example:
10877
10878 @smallexample @c ada
10879 with Aux;
10880
10881 procedure Test is
10882 begin
10883    Aux.Used (10);
10884 end Test;
10885
10886 package Aux is
10887    Used_Data   : Integer;
10888    Unused_Data : Integer;
10889
10890    procedure Used   (Data : Integer);
10891    procedure Unused (Data : Integer);
10892 end Aux;
10893
10894 package body Aux is
10895    procedure Used (Data : Integer) is
10896    begin
10897       Used_Data := Data;
10898    end Used;
10899
10900    procedure Unused (Data : Integer) is
10901    begin
10902       Unused_Data := Data;
10903    end Unused;
10904 end Aux;
10905 @end smallexample
10906
10907 @noindent
10908 @code{Unused} and @code{Unused_Data} are never referenced in this code
10909 excerpt, and hence they may be safely removed from the final executable.
10910
10911 @smallexample
10912 $ gnatmake test
10913
10914 $ nm test | grep used
10915 020015f0 T aux__unused
10916 02005d88 B aux__unused_data
10917 020015cc T aux__used
10918 02005d84 B aux__used_data
10919
10920 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10921      -largs -Wl,--gc-sections
10922
10923 $ nm test | grep used
10924 02005350 T aux__used
10925 0201ffe0 B aux__used_data
10926 @end smallexample
10927
10928 @noindent
10929 It can be observed that the procedure @code{Unused} and the object
10930 @code{Unused_Data} are removed by the linker when using the
10931 appropriate options.
10932
10933 @c ********************************
10934 @node Renaming Files Using gnatchop
10935 @chapter Renaming Files Using @code{gnatchop}
10936 @findex gnatchop
10937
10938 @noindent
10939 This chapter discusses how to handle files with multiple units by using
10940 the @code{gnatchop} utility. This utility is also useful in renaming
10941 files to meet the standard GNAT default file naming conventions.
10942
10943 @menu
10944 * Handling Files with Multiple Units::
10945 * Operating gnatchop in Compilation Mode::
10946 * Command Line for gnatchop::
10947 * Switches for gnatchop::
10948 * Examples of gnatchop Usage::
10949 @end menu
10950
10951 @node Handling Files with Multiple Units
10952 @section Handling Files with Multiple Units
10953
10954 @noindent
10955 The basic compilation model of GNAT requires that a file submitted to the
10956 compiler have only one unit and there be a strict correspondence
10957 between the file name and the unit name.
10958
10959 The @code{gnatchop} utility allows both of these rules to be relaxed,
10960 allowing GNAT to process files which contain multiple compilation units
10961 and files with arbitrary file names. @code{gnatchop}
10962 reads the specified file and generates one or more output files,
10963 containing one unit per file. The unit and the file name correspond,
10964 as required by GNAT.
10965
10966 If you want to permanently restructure a set of ``foreign'' files so that
10967 they match the GNAT rules, and do the remaining development using the
10968 GNAT structure, you can simply use @command{gnatchop} once, generate the
10969 new set of files and work with them from that point on.
10970
10971 Alternatively, if you want to keep your files in the ``foreign'' format,
10972 perhaps to maintain compatibility with some other Ada compilation
10973 system, you can set up a procedure where you use @command{gnatchop} each
10974 time you compile, regarding the source files that it writes as temporary
10975 files that you throw away.
10976
10977 Note that if your file containing multiple units starts with a byte order
10978 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
10979 will each start with a copy of this BOM, meaning that they can be compiled
10980 automatically in UTF-8 mode without needing to specify an explicit encoding.
10981
10982 @node Operating gnatchop in Compilation Mode
10983 @section Operating gnatchop in Compilation Mode
10984
10985 @noindent
10986 The basic function of @code{gnatchop} is to take a file with multiple units
10987 and split it into separate files. The boundary between files is reasonably
10988 clear, except for the issue of comments and pragmas. In default mode, the
10989 rule is that any pragmas between units belong to the previous unit, except
10990 that configuration pragmas always belong to the following unit. Any comments
10991 belong to the following unit. These rules
10992 almost always result in the right choice of
10993 the split point without needing to mark it explicitly and most users will
10994 find this default to be what they want. In this default mode it is incorrect to
10995 submit a file containing only configuration pragmas, or one that ends in
10996 configuration pragmas, to @code{gnatchop}.
10997
10998 However, using a special option to activate ``compilation mode'',
10999 @code{gnatchop}
11000 can perform another function, which is to provide exactly the semantics
11001 required by the RM for handling of configuration pragmas in a compilation.
11002 In the absence of configuration pragmas (at the main file level), this
11003 option has no effect, but it causes such configuration pragmas to be handled
11004 in a quite different manner.
11005
11006 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11007 only configuration pragmas, then this file is appended to the
11008 @file{gnat.adc} file in the current directory. This behavior provides
11009 the required behavior described in the RM for the actions to be taken
11010 on submitting such a file to the compiler, namely that these pragmas
11011 should apply to all subsequent compilations in the same compilation
11012 environment. Using GNAT, the current directory, possibly containing a
11013 @file{gnat.adc} file is the representation
11014 of a compilation environment. For more information on the
11015 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11016
11017 Second, in compilation mode, if @code{gnatchop}
11018 is given a file that starts with
11019 configuration pragmas, and contains one or more units, then these
11020 configuration pragmas are prepended to each of the chopped files. This
11021 behavior provides the required behavior described in the RM for the
11022 actions to be taken on compiling such a file, namely that the pragmas
11023 apply to all units in the compilation, but not to subsequently compiled
11024 units.
11025
11026 Finally, if configuration pragmas appear between units, they are appended
11027 to the previous unit. This results in the previous unit being illegal,
11028 since the compiler does not accept configuration pragmas that follow
11029 a unit. This provides the required RM behavior that forbids configuration
11030 pragmas other than those preceding the first compilation unit of a
11031 compilation.
11032
11033 For most purposes, @code{gnatchop} will be used in default mode. The
11034 compilation mode described above is used only if you need exactly
11035 accurate behavior with respect to compilations, and you have files
11036 that contain multiple units and configuration pragmas. In this
11037 circumstance the use of @code{gnatchop} with the compilation mode
11038 switch provides the required behavior, and is for example the mode
11039 in which GNAT processes the ACVC tests.
11040
11041 @node Command Line for gnatchop
11042 @section Command Line for @code{gnatchop}
11043
11044 @noindent
11045 The @code{gnatchop} command has the form:
11046
11047 @smallexample
11048 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11049       @ovar{directory}
11050 @end smallexample
11051
11052 @noindent
11053 The only required argument is the file name of the file to be chopped.
11054 There are no restrictions on the form of this file name. The file itself
11055 contains one or more Ada units, in normal GNAT format, concatenated
11056 together. As shown, more than one file may be presented to be chopped.
11057
11058 When run in default mode, @code{gnatchop} generates one output file in
11059 the current directory for each unit in each of the files.
11060
11061 @var{directory}, if specified, gives the name of the directory to which
11062 the output files will be written. If it is not specified, all files are
11063 written to the current directory.
11064
11065 For example, given a
11066 file called @file{hellofiles} containing
11067
11068 @smallexample @c ada
11069 @group
11070 @cartouche
11071 procedure hello;
11072
11073 with Text_IO; use Text_IO;
11074 procedure hello is
11075 begin
11076    Put_Line ("Hello");
11077 end hello;
11078 @end cartouche
11079 @end group
11080 @end smallexample
11081
11082 @noindent
11083 the command
11084
11085 @smallexample
11086 $ gnatchop ^hellofiles^HELLOFILES.^
11087 @end smallexample
11088
11089 @noindent
11090 generates two files in the current directory, one called
11091 @file{hello.ads} containing the single line that is the procedure spec,
11092 and the other called @file{hello.adb} containing the remaining text. The
11093 original file is not affected. The generated files can be compiled in
11094 the normal manner.
11095
11096 @noindent
11097 When gnatchop is invoked on a file that is empty or that contains only empty
11098 lines and/or comments, gnatchop will not fail, but will not produce any
11099 new sources.
11100
11101 For example, given a
11102 file called @file{toto.txt} containing
11103
11104 @smallexample @c ada
11105 @group
11106 @cartouche
11107 --  Just a comment
11108 @end cartouche
11109 @end group
11110 @end smallexample
11111
11112 @noindent
11113 the command
11114
11115 @smallexample
11116 $ gnatchop ^toto.txt^TOT.TXT^
11117 @end smallexample
11118
11119 @noindent
11120 will not produce any new file and will result in the following warnings:
11121
11122 @smallexample
11123 toto.txt:1:01: warning: empty file, contains no compilation units
11124 no compilation units found
11125 no source files written
11126 @end smallexample
11127
11128 @node Switches for gnatchop
11129 @section Switches for @code{gnatchop}
11130
11131 @noindent
11132 @command{gnatchop} recognizes the following switches:
11133
11134 @table @option
11135 @c !sort!
11136
11137 @item --version
11138 @cindex @option{--version} @command{gnatchop}
11139 Display Copyright and version, then exit disregarding all other options.
11140
11141 @item --help
11142 @cindex @option{--help} @command{gnatchop}
11143 If @option{--version} was not used, display usage, then exit disregarding
11144 all other options.
11145
11146 @item ^-c^/COMPILATION^
11147 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11148 Causes @code{gnatchop} to operate in compilation mode, in which
11149 configuration pragmas are handled according to strict RM rules. See
11150 previous section for a full description of this mode.
11151
11152 @ifclear vms
11153 @item -gnat@var{xxx}
11154 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11155 used to parse the given file. Not all @var{xxx} options make sense,
11156 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11157 process a source file that uses Latin-2 coding for identifiers.
11158 @end ifclear
11159
11160 @item ^-h^/HELP^
11161 Causes @code{gnatchop} to generate a brief help summary to the standard
11162 output file showing usage information.
11163
11164 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11165 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11166 Limit generated file names to the specified number @code{mm}
11167 of characters.
11168 This is useful if the
11169 resulting set of files is required to be interoperable with systems
11170 which limit the length of file names.
11171 @ifset vms
11172 If no value is given, or
11173 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11174 a default of 39, suitable for OpenVMS Alpha
11175 Systems, is assumed
11176 @end ifset
11177 @ifclear vms
11178 No space is allowed between the @option{-k} and the numeric value. The numeric
11179 value may be omitted in which case a default of @option{-k8},
11180 suitable for use
11181 with DOS-like file systems, is used. If no @option{-k} switch
11182 is present then
11183 there is no limit on the length of file names.
11184 @end ifclear
11185
11186 @item ^-p^/PRESERVE^
11187 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11188 Causes the file ^modification^creation^ time stamp of the input file to be
11189 preserved and used for the time stamp of the output file(s). This may be
11190 useful for preserving coherency of time stamps in an environment where
11191 @code{gnatchop} is used as part of a standard build process.
11192
11193 @item ^-q^/QUIET^
11194 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11195 Causes output of informational messages indicating the set of generated
11196 files to be suppressed. Warnings and error messages are unaffected.
11197
11198 @item ^-r^/REFERENCE^
11199 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11200 @findex Source_Reference
11201 Generate @code{Source_Reference} pragmas. Use this switch if the output
11202 files are regarded as temporary and development is to be done in terms
11203 of the original unchopped file. This switch causes
11204 @code{Source_Reference} pragmas to be inserted into each of the
11205 generated files to refers back to the original file name and line number.
11206 The result is that all error messages refer back to the original
11207 unchopped file.
11208 In addition, the debugging information placed into the object file (when
11209 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11210 specified)
11211 also refers back to this original file so that tools like profilers and
11212 debuggers will give information in terms of the original unchopped file.
11213
11214 If the original file to be chopped itself contains
11215 a @code{Source_Reference}
11216 pragma referencing a third file, then gnatchop respects
11217 this pragma, and the generated @code{Source_Reference} pragmas
11218 in the chopped file refer to the original file, with appropriate
11219 line numbers. This is particularly useful when @code{gnatchop}
11220 is used in conjunction with @code{gnatprep} to compile files that
11221 contain preprocessing statements and multiple units.
11222
11223 @item ^-v^/VERBOSE^
11224 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11225 Causes @code{gnatchop} to operate in verbose mode. The version
11226 number and copyright notice are output, as well as exact copies of
11227 the gnat1 commands spawned to obtain the chop control information.
11228
11229 @item ^-w^/OVERWRITE^
11230 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11231 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11232 fatal error if there is already a file with the same name as a
11233 file it would otherwise output, in other words if the files to be
11234 chopped contain duplicated units. This switch bypasses this
11235 check, and causes all but the last instance of such duplicated
11236 units to be skipped.
11237
11238 @ifclear vms
11239 @item --GCC=@var{xxxx}
11240 @cindex @option{--GCC=} (@code{gnatchop})
11241 Specify the path of the GNAT parser to be used. When this switch is used,
11242 no attempt is made to add the prefix to the GNAT parser executable.
11243 @end ifclear
11244 @end table
11245
11246 @node Examples of gnatchop Usage
11247 @section Examples of @code{gnatchop} Usage
11248
11249 @table @code
11250 @ifset vms
11251 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11252 @end ifset
11253 @ifclear vms
11254 @item gnatchop -w hello_s.ada prerelease/files
11255 @end ifclear
11256
11257 Chops the source file @file{hello_s.ada}. The output files will be
11258 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11259 overwriting any
11260 files with matching names in that directory (no files in the current
11261 directory are modified).
11262
11263 @item gnatchop ^archive^ARCHIVE.^
11264 Chops the source file @file{^archive^ARCHIVE.^}
11265 into the current directory. One
11266 useful application of @code{gnatchop} is in sending sets of sources
11267 around, for example in email messages. The required sources are simply
11268 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11269 command), and then
11270 @command{gnatchop} is used at the other end to reconstitute the original
11271 file names.
11272
11273 @item gnatchop file1 file2 file3 direc
11274 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11275 the resulting files in the directory @file{direc}. Note that if any units
11276 occur more than once anywhere within this set of files, an error message
11277 is generated, and no files are written. To override this check, use the
11278 @option{^-w^/OVERWRITE^} switch,
11279 in which case the last occurrence in the last file will
11280 be the one that is output, and earlier duplicate occurrences for a given
11281 unit will be skipped.
11282 @end table
11283
11284 @node Configuration Pragmas
11285 @chapter Configuration Pragmas
11286 @cindex Configuration pragmas
11287 @cindex Pragmas, configuration
11288
11289 @noindent
11290 Configuration pragmas include those pragmas described as
11291 such in the Ada Reference Manual, as well as
11292 implementation-dependent pragmas that are configuration pragmas.
11293 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11294 for details on these additional GNAT-specific configuration pragmas.
11295 Most notably, the pragma @code{Source_File_Name}, which allows
11296 specifying non-default names for source files, is a configuration
11297 pragma. The following is a complete list of configuration pragmas
11298 recognized by GNAT:
11299
11300 @smallexample
11301    Ada_83
11302    Ada_95
11303    Ada_05
11304    Ada_2005
11305    Assertion_Policy
11306    C_Pass_By_Copy
11307    Check_Name
11308    Check_Policy
11309    Compile_Time_Error
11310    Compile_Time_Warning
11311    Compiler_Unit
11312    Component_Alignment
11313    Debug_Policy
11314    Detect_Blocking
11315    Discard_Names
11316    Elaboration_Checks
11317    Eliminate
11318    Extend_System
11319    External_Name_Casing
11320    Fast_Math
11321    Favor_Top_Level
11322    Float_Representation
11323    Implicit_Packing
11324    Initialize_Scalars
11325    Interrupt_State
11326    License
11327    Locking_Policy
11328    Long_Float
11329    No_Run_Time
11330    No_Strict_Aliasing
11331    Normalize_Scalars
11332    Optimize_Alignment
11333    Persistent_BSS
11334    Polling
11335    Priority_Specific_Dispatching
11336    Profile
11337    Profile_Warnings
11338    Propagate_Exceptions
11339    Queuing_Policy
11340    Ravenscar
11341    Restricted_Run_Time
11342    Restrictions
11343    Restrictions_Warnings
11344    Reviewable
11345    Source_File_Name
11346    Source_File_Name_Project
11347    Style_Checks
11348    Suppress
11349    Suppress_Exception_Locations
11350    Task_Dispatching_Policy
11351    Universal_Data
11352    Unsuppress
11353    Use_VADS_Size
11354    Validity_Checks
11355    Warnings
11356    Wide_Character_Encoding
11357
11358 @end smallexample
11359
11360 @menu
11361 * Handling of Configuration Pragmas::
11362 * The Configuration Pragmas Files::
11363 @end menu
11364
11365 @node Handling of Configuration Pragmas
11366 @section Handling of Configuration Pragmas
11367
11368 Configuration pragmas may either appear at the start of a compilation
11369 unit, in which case they apply only to that unit, or they may apply to
11370 all compilations performed in a given compilation environment.
11371
11372 GNAT also provides the @code{gnatchop} utility to provide an automatic
11373 way to handle configuration pragmas following the semantics for
11374 compilations (that is, files with multiple units), described in the RM.
11375 See @ref{Operating gnatchop in Compilation Mode} for details.
11376 However, for most purposes, it will be more convenient to edit the
11377 @file{gnat.adc} file that contains configuration pragmas directly,
11378 as described in the following section.
11379
11380 @node The Configuration Pragmas Files
11381 @section The Configuration Pragmas Files
11382 @cindex @file{gnat.adc}
11383
11384 @noindent
11385 In GNAT a compilation environment is defined by the current
11386 directory at the time that a compile command is given. This current
11387 directory is searched for a file whose name is @file{gnat.adc}. If
11388 this file is present, it is expected to contain one or more
11389 configuration pragmas that will be applied to the current compilation.
11390 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11391 considered.
11392
11393 Configuration pragmas may be entered into the @file{gnat.adc} file
11394 either by running @code{gnatchop} on a source file that consists only of
11395 configuration pragmas, or more conveniently  by
11396 direct editing of the @file{gnat.adc} file, which is a standard format
11397 source file.
11398
11399 In addition to @file{gnat.adc}, additional files containing configuration
11400 pragmas may be applied to the current compilation using the switch
11401 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11402 contains only configuration pragmas. These configuration pragmas are
11403 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11404 is present and switch @option{-gnatA} is not used).
11405
11406 It is allowed to specify several switches @option{-gnatec}, all of which
11407 will be taken into account.
11408
11409 If you are using project file, a separate mechanism is provided using
11410 project attributes, see @ref{Specifying Configuration Pragmas} for more
11411 details.
11412
11413 @ifset vms
11414 Of special interest to GNAT OpenVMS Alpha is the following
11415 configuration pragma:
11416
11417 @smallexample @c ada
11418 @cartouche
11419 pragma Extend_System (Aux_DEC);
11420 @end cartouche
11421 @end smallexample
11422
11423 @noindent
11424 In the presence of this pragma, GNAT adds to the definition of the
11425 predefined package SYSTEM all the additional types and subprograms that are
11426 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11427 @end ifset
11428
11429 @node Handling Arbitrary File Naming Conventions Using gnatname
11430 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11431 @cindex Arbitrary File Naming Conventions
11432
11433 @menu
11434 * Arbitrary File Naming Conventions::
11435 * Running gnatname::
11436 * Switches for gnatname::
11437 * Examples of gnatname Usage::
11438 @end menu
11439
11440 @node Arbitrary File Naming Conventions
11441 @section Arbitrary File Naming Conventions
11442
11443 @noindent
11444 The GNAT compiler must be able to know the source file name of a compilation
11445 unit.  When using the standard GNAT default file naming conventions
11446 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11447 does not need additional information.
11448
11449 @noindent
11450 When the source file names do not follow the standard GNAT default file naming
11451 conventions, the GNAT compiler must be given additional information through
11452 a configuration pragmas file (@pxref{Configuration Pragmas})
11453 or a project file.
11454 When the non-standard file naming conventions are well-defined,
11455 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11456 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11457 if the file naming conventions are irregular or arbitrary, a number
11458 of pragma @code{Source_File_Name} for individual compilation units
11459 must be defined.
11460 To help maintain the correspondence between compilation unit names and
11461 source file names within the compiler,
11462 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11463 set of files.
11464
11465 @node Running gnatname
11466 @section Running @code{gnatname}
11467
11468 @noindent
11469 The usual form of the @code{gnatname} command is
11470
11471 @smallexample
11472 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11473       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11474 @end smallexample
11475
11476 @noindent
11477 All of the arguments are optional. If invoked without any argument,
11478 @code{gnatname} will display its usage.
11479
11480 @noindent
11481 When used with at least one naming pattern, @code{gnatname} will attempt to
11482 find all the compilation units in files that follow at least one of the
11483 naming patterns. To find these compilation units,
11484 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11485 regular files.
11486
11487 @noindent
11488 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11489 Each Naming Pattern is enclosed between double quotes.
11490 A Naming Pattern is a regular expression similar to the wildcard patterns
11491 used in file names by the Unix shells or the DOS prompt.
11492
11493 @noindent
11494 @code{gnatname} may be called with several sections of directories/patterns.
11495 Sections are separated by switch @code{--and}. In each section, there must be
11496 at least one pattern. If no directory is specified in a section, the current
11497 directory (or the project directory is @code{-P} is used) is implied.
11498 The options other that the directory switches and the patterns apply globally
11499 even if they are in different sections.
11500
11501 @noindent
11502 Examples of Naming Patterns are
11503
11504 @smallexample
11505    "*.[12].ada"
11506    "*.ad[sb]*"
11507    "body_*"    "spec_*"
11508 @end smallexample
11509
11510 @noindent
11511 For a more complete description of the syntax of Naming Patterns,
11512 see the second kind of regular expressions described in @file{g-regexp.ads}
11513 (the ``Glob'' regular expressions).
11514
11515 @noindent
11516 When invoked with no switch @code{-P}, @code{gnatname} will create a
11517 configuration pragmas file @file{gnat.adc} in the current working directory,
11518 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11519 unit.
11520
11521 @node Switches for gnatname
11522 @section Switches for @code{gnatname}
11523
11524 @noindent
11525 Switches for @code{gnatname} must precede any specified Naming Pattern.
11526
11527 @noindent
11528 You may specify any of the following switches to @code{gnatname}:
11529
11530 @table @option
11531 @c !sort!
11532
11533 @item --version
11534 @cindex @option{--version} @command{gnatname}
11535 Display Copyright and version, then exit disregarding all other options.
11536
11537 @item --help
11538 @cindex @option{--help} @command{gnatname}
11539 If @option{--version} was not used, display usage, then exit disregarding
11540 all other options.
11541
11542 @item --and
11543 Start another section of directories/patterns.
11544
11545 @item ^-c^/CONFIG_FILE=^@file{file}
11546 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11547 Create a configuration pragmas file @file{file} (instead of the default
11548 @file{gnat.adc}).
11549 @ifclear vms
11550 There may be zero, one or more space between @option{-c} and
11551 @file{file}.
11552 @end ifclear
11553 @file{file} may include directory information. @file{file} must be
11554 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11555 When a switch @option{^-c^/CONFIG_FILE^} is
11556 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11557
11558 @item ^-d^/SOURCE_DIRS=^@file{dir}
11559 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11560 Look for source files in directory @file{dir}. There may be zero, one or more
11561 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11562 When a switch @option{^-d^/SOURCE_DIRS^}
11563 is specified, the current working directory will not be searched for source
11564 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11565 or @option{^-D^/DIR_FILES^} switch.
11566 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11567 If @file{dir} is a relative path, it is relative to the directory of
11568 the configuration pragmas file specified with switch
11569 @option{^-c^/CONFIG_FILE^},
11570 or to the directory of the project file specified with switch
11571 @option{^-P^/PROJECT_FILE^} or,
11572 if neither switch @option{^-c^/CONFIG_FILE^}
11573 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11574 current working directory. The directory
11575 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11576
11577 @item ^-D^/DIRS_FILE=^@file{file}
11578 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11579 Look for source files in all directories listed in text file @file{file}.
11580 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11581 and @file{file}.
11582 @file{file} must be an existing, readable text file.
11583 Each nonempty line in @file{file} must be a directory.
11584 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11585 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11586 @file{file}.
11587
11588 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11589 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11590 Foreign patterns. Using this switch, it is possible to add sources of languages
11591 other than Ada to the list of sources of a project file.
11592 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11593 For example,
11594 @smallexample
11595 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11596 @end smallexample
11597 @noindent
11598 will look for Ada units in all files with the @file{.ada} extension,
11599 and will add to the list of file for project @file{prj.gpr} the C files
11600 with extension @file{.^c^C^}.
11601
11602 @item ^-h^/HELP^
11603 @cindex @option{^-h^/HELP^} (@code{gnatname})
11604 Output usage (help) information. The output is written to @file{stdout}.
11605
11606 @item ^-P^/PROJECT_FILE=^@file{proj}
11607 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11608 Create or update project file @file{proj}. There may be zero, one or more space
11609 between @option{-P} and @file{proj}. @file{proj} may include directory
11610 information. @file{proj} must be writable.
11611 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11612 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11613 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11614
11615 @item ^-v^/VERBOSE^
11616 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11617 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11618 This includes name of the file written, the name of the directories to search
11619 and, for each file in those directories whose name matches at least one of
11620 the Naming Patterns, an indication of whether the file contains a unit,
11621 and if so the name of the unit.
11622
11623 @item ^-v -v^/VERBOSE /VERBOSE^
11624 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11625 Very Verbose mode. In addition to the output produced in verbose mode,
11626 for each file in the searched directories whose name matches none of
11627 the Naming Patterns, an indication is given that there is no match.
11628
11629 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11630 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11631 Excluded patterns. Using this switch, it is possible to exclude some files
11632 that would match the name patterns. For example,
11633 @smallexample
11634 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11635 @end smallexample
11636 @noindent
11637 will look for Ada units in all files with the @file{.ada} extension,
11638 except those whose names end with @file{_nt.ada}.
11639
11640 @end table
11641
11642 @node Examples of gnatname Usage
11643 @section Examples of @code{gnatname} Usage
11644
11645 @ifset vms
11646 @smallexample
11647 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11648 @end smallexample
11649 @end ifset
11650
11651 @ifclear vms
11652 @smallexample
11653 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11654 @end smallexample
11655 @end ifclear
11656
11657 @noindent
11658 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11659 and be writable. In addition, the directory
11660 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11661 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11662
11663 @ifclear vms
11664 Note the optional spaces after @option{-c} and @option{-d}.
11665 @end ifclear
11666
11667 @smallexample
11668 @ifclear vms
11669 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11670   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11671 @end ifclear
11672 @ifset vms
11673 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11674   /EXCLUDED_PATTERN=*_nt_body.ada
11675   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11676   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11677 @end ifset
11678 @end smallexample
11679
11680 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11681 even in conjunction with one or several switches
11682 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11683 are used in this example.
11684
11685 @c *****************************************
11686 @c * G N A T  P r o j e c t  M a n a g e r *
11687 @c *****************************************
11688 @node GNAT Project Manager
11689 @chapter GNAT Project Manager
11690
11691 @menu
11692 * Introduction::
11693 * Examples of Project Files::
11694 * Project File Syntax::
11695 * Objects and Sources in Project Files::
11696 * Importing Projects::
11697 * Project Extension::
11698 * Project Hierarchy Extension::
11699 * External References in Project Files::
11700 * Packages in Project Files::
11701 * Variables from Imported Projects::
11702 * Naming Schemes::
11703 * Library Projects::
11704 * Stand-alone Library Projects::
11705 * Switches Related to Project Files::
11706 * Tools Supporting Project Files::
11707 * An Extended Example::
11708 * Project File Complete Syntax::
11709 @end menu
11710
11711 @c ****************
11712 @c * Introduction *
11713 @c ****************
11714
11715 @node Introduction
11716 @section Introduction
11717
11718 @noindent
11719 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11720 you to manage complex builds involving a number of source files, directories,
11721 and compilation options for different system configurations. In particular,
11722 project files allow you to specify:
11723 @itemize @bullet
11724 @item
11725 The directory or set of directories containing the source files, and/or the
11726 names of the specific source files themselves
11727 @item
11728 The directory in which the compiler's output
11729 (@file{ALI} files, object files, tree files) is to be placed
11730 @item
11731 The directory in which the executable programs is to be placed
11732 @item
11733 ^Switch^Switch^ settings for any of the project-enabled tools
11734 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11735 @code{gnatfind}); you can apply these settings either globally or to individual
11736 compilation units.
11737 @item
11738 The source files containing the main subprogram(s) to be built
11739 @item
11740 The source programming language(s) (currently Ada and/or C)
11741 @item
11742 Source file naming conventions; you can specify these either globally or for
11743 individual compilation units
11744 @end itemize
11745
11746 @menu
11747 * Project Files::
11748 @end menu
11749
11750 @node Project Files
11751 @subsection Project Files
11752
11753 @noindent
11754 Project files are written in a syntax close to that of Ada, using  familiar
11755 notions such as packages, context clauses, declarations, default values,
11756 assignments, and inheritance. Finally, project files can be built
11757 hierarchically from other project files, simplifying complex system
11758 integration and project reuse.
11759
11760 A @dfn{project} is a specific set of values for various compilation properties.
11761 The settings for a given project are described by means of
11762 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11763 Property values in project files are either strings or lists of strings.
11764 Properties that are not explicitly set receive default values.  A project
11765 file may interrogate the values of @dfn{external variables} (user-defined
11766 command-line switches or environment variables), and it may specify property
11767 settings conditionally, based on the value of such variables.
11768
11769 In simple cases, a project's source files depend only on other source files
11770 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11771 used in
11772 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11773 the Project Manager also allows more sophisticated arrangements,
11774 where the source files in one project depend on source files in other
11775 projects:
11776 @itemize @bullet
11777 @item
11778 One project can @emph{import} other projects containing needed source files.
11779 @item
11780 You can organize GNAT projects in a hierarchy: a @emph{child} project
11781 can extend a @emph{parent} project, inheriting the parent's source files and
11782 optionally overriding any of them with alternative versions
11783 @end itemize
11784
11785 @noindent
11786 More generally, the Project Manager lets you structure large development
11787 efforts into hierarchical subsystems, where build decisions are delegated
11788 to the subsystem level, and thus different compilation environments
11789 (^switch^switch^ settings) used for different subsystems.
11790
11791 The Project Manager is invoked through the
11792 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11793 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11794 @ifclear vms
11795 There may be zero, one or more spaces between @option{-P} and
11796 @option{@emph{projectfile}}.
11797 @end ifclear
11798 If you want to define (on the command line) an external variable that is
11799 queried by the project file, you must use the
11800 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11801 The Project Manager parses and interprets the project file, and drives the
11802 invoked tool based on the project settings.
11803
11804 The Project Manager supports a wide range of development strategies,
11805 for systems of all sizes.  Here are some typical practices that are
11806 easily handled:
11807 @itemize @bullet
11808 @item
11809 Using a common set of source files, but generating object files in different
11810 directories via different ^switch^switch^ settings
11811 @item
11812 Using a mostly-shared set of source files, but with different versions of
11813 some unit or units
11814 @end itemize
11815
11816 @noindent
11817 The destination of an executable can be controlled inside a project file
11818 using the @option{^-o^-o^}
11819 ^switch^switch^.
11820 In the absence of such a ^switch^switch^ either inside
11821 the project file or on the command line, any executable files generated by
11822 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11823 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11824 in the object directory of the project.
11825
11826 You can use project files to achieve some of the effects of a source
11827 versioning system (for example, defining separate projects for
11828 the different sets of sources that comprise different releases) but the
11829 Project Manager is independent of any source configuration management tools
11830 that might be used by the developers.
11831
11832 The next section introduces the main features of GNAT's project facility
11833 through a sequence of examples; subsequent sections will present the syntax
11834 and semantics in more detail. A more formal description of the project
11835 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11836 Reference Manual}.
11837
11838 @c *****************************
11839 @c * Examples of Project Files *
11840 @c *****************************
11841
11842 @node Examples of Project Files
11843 @section Examples of Project Files
11844 @noindent
11845 This section illustrates some of the typical uses of project files and
11846 explains their basic structure and behavior.
11847
11848 @menu
11849 * Common Sources with Different ^Switches^Switches^ and Directories::
11850 * Using External Variables::
11851 * Importing Other Projects::
11852 * Extending a Project::
11853 @end menu
11854
11855 @node Common Sources with Different ^Switches^Switches^ and Directories
11856 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11857
11858 @menu
11859 * Source Files::
11860 * Specifying the Object Directory::
11861 * Specifying the Exec Directory::
11862 * Project File Packages::
11863 * Specifying ^Switch^Switch^ Settings::
11864 * Main Subprograms::
11865 * Executable File Names::
11866 * Source File Naming Conventions::
11867 * Source Language(s)::
11868 @end menu
11869
11870 @noindent
11871 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11872 @file{proc.adb} are in the @file{/common} directory.  The file
11873 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11874 package @code{Pack}.  We want to compile these source files under two sets
11875 of ^switches^switches^:
11876 @itemize @bullet
11877 @item
11878 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11879 and the @option{^-gnata^-gnata^},
11880 @option{^-gnato^-gnato^},
11881 and @option{^-gnatE^-gnatE^} switches to the
11882 compiler; the compiler's output is to appear in @file{/common/debug}
11883 @item
11884 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11885 to the compiler; the compiler's output is to appear in @file{/common/release}
11886 @end itemize
11887
11888 @noindent
11889 The GNAT project files shown below, respectively @file{debug.gpr} and
11890 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11891
11892 Schematically:
11893 @smallexample
11894 @group
11895 ^/common^[COMMON]^
11896   debug.gpr
11897   release.gpr
11898   pack.ads
11899   pack.adb
11900   proc.adb
11901 @end group
11902 @group
11903 ^/common/debug^[COMMON.DEBUG]^
11904   proc.ali, proc.o
11905   pack.ali, pack.o
11906 @end group
11907 @group
11908 ^/common/release^[COMMON.RELEASE]^
11909   proc.ali, proc.o
11910   pack.ali, pack.o
11911 @end group
11912 @end smallexample
11913 Here are the corresponding project files:
11914
11915 @smallexample @c projectfile
11916 @group
11917 project Debug is
11918   for Object_Dir use "debug";
11919   for Main use ("proc");
11920
11921   package Builder is
11922     for ^Default_Switches^Default_Switches^ ("Ada")
11923         use ("^-g^-g^");
11924     for Executable ("proc.adb") use "proc1";
11925   end Builder;
11926 @end group
11927
11928 @group
11929   package Compiler is
11930     for ^Default_Switches^Default_Switches^ ("Ada")
11931        use ("-fstack-check",
11932             "^-gnata^-gnata^",
11933             "^-gnato^-gnato^",
11934             "^-gnatE^-gnatE^");
11935   end Compiler;
11936 end Debug;
11937 @end group
11938 @end smallexample
11939
11940 @smallexample @c projectfile
11941 @group
11942 project Release is
11943   for Object_Dir use "release";
11944   for Exec_Dir use ".";
11945   for Main use ("proc");
11946
11947   package Compiler is
11948     for ^Default_Switches^Default_Switches^ ("Ada")
11949         use ("^-O2^-O2^");
11950   end Compiler;
11951 end Release;
11952 @end group
11953 @end smallexample
11954
11955 @noindent
11956 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11957 insensitive), and analogously the project defined by @file{release.gpr} is
11958 @code{"Release"}.  For consistency the file should have the same name as the
11959 project, and the project file's extension should be @code{"gpr"}. These
11960 conventions are not required, but a warning is issued if they are not followed.
11961
11962 If the current directory is @file{^/temp^[TEMP]^}, then the command
11963 @smallexample
11964 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11965 @end smallexample
11966
11967 @noindent
11968 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11969 as well as the @code{^proc1^PROC1.EXE^} executable,
11970 using the ^switch^switch^ settings defined in the project file.
11971
11972 Likewise, the command
11973 @smallexample
11974 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11975 @end smallexample
11976
11977 @noindent
11978 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11979 and the @code{^proc^PROC.EXE^}
11980 executable in @file{^/common^[COMMON]^},
11981 using the ^switch^switch^ settings from the project file.
11982
11983 @node Source Files
11984 @unnumberedsubsubsec Source Files
11985
11986 @noindent
11987 If a project file does not explicitly specify a set of source directories or
11988 a set of source files, then by default the project's source files are the
11989 Ada source files in the project file directory.  Thus @file{pack.ads},
11990 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11991
11992 @node Specifying the Object Directory
11993 @unnumberedsubsubsec Specifying the Object Directory
11994
11995 @noindent
11996 Several project properties are modeled by Ada-style @emph{attributes};
11997 a property is defined by supplying the equivalent of an Ada attribute
11998 definition clause in the project file.
11999 A project's object directory is another such a property; the corresponding
12000 attribute is @code{Object_Dir}, and its value is also a string expression,
12001 specified either as absolute or relative. In the later case,
12002 it is relative to the project file directory. Thus the compiler's
12003 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12004 (for the @code{Debug} project)
12005 and to @file{^/common/release^[COMMON.RELEASE]^}
12006 (for the @code{Release} project).
12007 If @code{Object_Dir} is not specified, then the default is the project file
12008 directory itself.
12009
12010 @node Specifying the Exec Directory
12011 @unnumberedsubsubsec Specifying the Exec Directory
12012
12013 @noindent
12014 A project's exec directory is another property; the corresponding
12015 attribute is @code{Exec_Dir}, and its value is also a string expression,
12016 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12017 then the default is the object directory (which may also be the project file
12018 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12019 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12020 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12021 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12022
12023 @node Project File Packages
12024 @unnumberedsubsubsec Project File Packages
12025
12026 @noindent
12027 A GNAT tool that is integrated with the Project Manager is modeled by a
12028 corresponding package in the project file. In the example above,
12029 The @code{Debug} project defines the packages @code{Builder}
12030 (for @command{gnatmake}) and @code{Compiler};
12031 the @code{Release} project defines only the @code{Compiler} package.
12032
12033 The Ada-like package syntax is not to be taken literally.  Although packages in
12034 project files bear a surface resemblance to packages in Ada source code, the
12035 notation is simply a way to convey a grouping of properties for a named
12036 entity.  Indeed, the package names permitted in project files are restricted
12037 to a predefined set, corresponding to the project-aware tools, and the contents
12038 of packages are limited to a small set of constructs.
12039 The packages in the example above contain attribute definitions.
12040
12041 @node Specifying ^Switch^Switch^ Settings
12042 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12043
12044 @noindent
12045 ^Switch^Switch^ settings for a project-aware tool can be specified through
12046 attributes in the package that corresponds to the tool.
12047 The example above illustrates one of the relevant attributes,
12048 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12049 in both project files.
12050 Unlike simple attributes like @code{Source_Dirs},
12051 @code{^Default_Switches^Default_Switches^} is
12052 known as an @emph{associative array}.  When you define this attribute, you must
12053 supply an ``index'' (a literal string), and the effect of the attribute
12054 definition is to set the value of the array at the specified index.
12055 For the @code{^Default_Switches^Default_Switches^} attribute,
12056 the index is a programming language (in our case, Ada),
12057 and the value specified (after @code{use}) must be a list
12058 of string expressions.
12059
12060 The attributes permitted in project files are restricted to a predefined set.
12061 Some may appear at project level, others in packages.
12062 For any attribute that is an associative array, the index must always be a
12063 literal string, but the restrictions on this string (e.g., a file name or a
12064 language name) depend on the individual attribute.
12065 Also depending on the attribute, its specified value will need to be either a
12066 string or a string list.
12067
12068 In the @code{Debug} project, we set the switches for two tools,
12069 @command{gnatmake} and the compiler, and thus we include the two corresponding
12070 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12071 attribute with index @code{"Ada"}.
12072 Note that the package corresponding to
12073 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12074 similar, but only includes the @code{Compiler} package.
12075
12076 In project @code{Debug} above, the ^switches^switches^ starting with
12077 @option{-gnat} that are specified in package @code{Compiler}
12078 could have been placed in package @code{Builder}, since @command{gnatmake}
12079 transmits all such ^switches^switches^ to the compiler.
12080
12081 @node Main Subprograms
12082 @unnumberedsubsubsec Main Subprograms
12083
12084 @noindent
12085 One of the specifiable properties of a project is a list of files that contain
12086 main subprograms.  This property is captured in the @code{Main} attribute,
12087 whose value is a list of strings.  If a project defines the @code{Main}
12088 attribute, it is not necessary to identify the main subprogram(s) when
12089 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12090
12091 @node Executable File Names
12092 @unnumberedsubsubsec Executable File Names
12093
12094 @noindent
12095 By default, the executable file name corresponding to a main source is
12096 deduced from the main source file name. Through the attributes
12097 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12098 it is possible to change this default.
12099 In project @code{Debug} above, the executable file name
12100 for main source @file{^proc.adb^PROC.ADB^} is
12101 @file{^proc1^PROC1.EXE^}.
12102 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12103 of the executable files, when no attribute @code{Executable} applies:
12104 its value replace the platform-specific executable suffix.
12105 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12106 specify a non-default executable file name when several mains are built at once
12107 in a single @command{gnatmake} command.
12108
12109 @node Source File Naming Conventions
12110 @unnumberedsubsubsec Source File Naming Conventions
12111
12112 @noindent
12113 Since the project files above do not specify any source file naming
12114 conventions, the GNAT defaults are used.  The mechanism for defining source
12115 file naming conventions -- a package named @code{Naming} --
12116 is described below (@pxref{Naming Schemes}).
12117
12118 @node Source Language(s)
12119 @unnumberedsubsubsec Source Language(s)
12120
12121 @noindent
12122 Since the project files do not specify a @code{Languages} attribute, by
12123 default the GNAT tools assume that the language of the project file is Ada.
12124 More generally, a project can comprise source files
12125 in Ada, C, and/or other languages.
12126
12127 @node Using External Variables
12128 @subsection Using External Variables
12129
12130 @noindent
12131 Instead of supplying different project files for debug and release, we can
12132 define a single project file that queries an external variable (set either
12133 on the command line or via an ^environment variable^logical name^) in order to
12134 conditionally define the appropriate settings.  Again, assume that the
12135 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12136 located in directory @file{^/common^[COMMON]^}.  The following project file,
12137 @file{build.gpr}, queries the external variable named @code{STYLE} and
12138 defines an object directory and ^switch^switch^ settings based on whether
12139 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12140 the default is @code{"deb"}.
12141
12142 @smallexample @c projectfile
12143 @group
12144 project Build is
12145   for Main use ("proc");
12146
12147   type Style_Type is ("deb", "rel");
12148   Style : Style_Type := external ("STYLE", "deb");
12149
12150   case Style is
12151     when "deb" =>
12152       for Object_Dir use "debug";
12153
12154     when "rel" =>
12155       for Object_Dir use "release";
12156       for Exec_Dir use ".";
12157   end case;
12158 @end group
12159
12160 @group
12161   package Builder is
12162
12163     case Style is
12164       when "deb" =>
12165         for ^Default_Switches^Default_Switches^ ("Ada")
12166             use ("^-g^-g^");
12167         for Executable ("proc") use "proc1";
12168       when others =>
12169         null;
12170     end case;
12171
12172   end Builder;
12173 @end group
12174
12175 @group
12176   package Compiler is
12177
12178     case Style is
12179       when "deb" =>
12180         for ^Default_Switches^Default_Switches^ ("Ada")
12181             use ("^-gnata^-gnata^",
12182                  "^-gnato^-gnato^",
12183                  "^-gnatE^-gnatE^");
12184
12185       when "rel" =>
12186         for ^Default_Switches^Default_Switches^ ("Ada")
12187             use ("^-O2^-O2^");
12188     end case;
12189
12190   end Compiler;
12191
12192 end Build;
12193 @end group
12194 @end smallexample
12195
12196 @noindent
12197 @code{Style_Type} is an example of a @emph{string type}, which is the project
12198 file analog of an Ada enumeration type but whose components are string literals
12199 rather than identifiers.  @code{Style} is declared as a variable of this type.
12200
12201 The form @code{external("STYLE", "deb")} is known as an
12202 @emph{external reference}; its first argument is the name of an
12203 @emph{external variable}, and the second argument is a default value to be
12204 used if the external variable doesn't exist.  You can define an external
12205 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12206 or you can use ^an environment variable^a logical name^
12207 as an external variable.
12208
12209 Each @code{case} construct is expanded by the Project Manager based on the
12210 value of @code{Style}. Thus the command
12211 @ifclear vms
12212 @smallexample
12213 gnatmake -P/common/build.gpr -XSTYLE=deb
12214 @end smallexample
12215 @end ifclear
12216
12217 @ifset vms
12218 @smallexample
12219 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12220 @end smallexample
12221 @end ifset
12222
12223 @noindent
12224 is equivalent to the @command{gnatmake} invocation using the project file
12225 @file{debug.gpr} in the earlier example.  So is the command
12226 @smallexample
12227 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12228 @end smallexample
12229
12230 @noindent
12231 since @code{"deb"} is the default for @code{STYLE}.
12232
12233 Analogously,
12234
12235 @ifclear vms
12236 @smallexample
12237 gnatmake -P/common/build.gpr -XSTYLE=rel
12238 @end smallexample
12239 @end ifclear
12240
12241 @ifset vms
12242 @smallexample
12243 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12244 @end smallexample
12245 @end ifset
12246
12247 @noindent
12248 is equivalent to the @command{gnatmake} invocation using the project file
12249 @file{release.gpr} in the earlier example.
12250
12251 @node Importing Other Projects
12252 @subsection Importing Other Projects
12253 @cindex @code{ADA_PROJECT_PATH}
12254
12255 @noindent
12256 A compilation unit in a source file in one project may depend on compilation
12257 units in source files in other projects.  To compile this unit under
12258 control of a project file, the
12259 dependent project must @emph{import} the projects containing the needed source
12260 files.
12261 This effect is obtained using syntax similar to an Ada @code{with} clause,
12262 but where @code{with}ed entities are strings that denote project files.
12263
12264 As an example, suppose that the two projects @code{GUI_Proj} and
12265 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12266 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12267 and @file{^/comm^[COMM]^}, respectively.
12268 Suppose that the source files for @code{GUI_Proj} are
12269 @file{gui.ads} and @file{gui.adb}, and that the source files for
12270 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12271 files is located in its respective project file directory.  Schematically:
12272
12273 @smallexample
12274 @group
12275 ^/gui^[GUI]^
12276   gui_proj.gpr
12277   gui.ads
12278   gui.adb
12279 @end group
12280
12281 @group
12282 ^/comm^[COMM]^
12283   comm_proj.gpr
12284   comm.ads
12285   comm.adb
12286 @end group
12287 @end smallexample
12288
12289 @noindent
12290 We want to develop an application in directory @file{^/app^[APP]^} that
12291 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12292 the corresponding project files (e.g.@: the ^switch^switch^ settings
12293 and object directory).
12294 Skeletal code for a main procedure might be something like the following:
12295
12296 @smallexample @c ada
12297 @group
12298 with GUI, Comm;
12299 procedure App_Main is
12300    @dots{}
12301 begin
12302    @dots{}
12303 end App_Main;
12304 @end group
12305 @end smallexample
12306
12307 @noindent
12308 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12309 effect:
12310
12311 @smallexample @c projectfile
12312 @group
12313 with "/gui/gui_proj", "/comm/comm_proj";
12314 project App_Proj is
12315    for Main use ("app_main");
12316 end App_Proj;
12317 @end group
12318 @end smallexample
12319
12320 @noindent
12321 Building an executable is achieved through the command:
12322 @smallexample
12323 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12324 @end smallexample
12325 @noindent
12326 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12327 in the directory where @file{app_proj.gpr} resides.
12328
12329 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12330 (as illustrated above) the @code{with} clause can omit the extension.
12331
12332 Our example specified an absolute path for each imported project file.
12333 Alternatively, the directory name of an imported object can be omitted
12334 if either
12335 @itemize @bullet
12336 @item
12337 The imported project file is in the same directory as the importing project
12338 file, or
12339 @item
12340 You have defined ^an environment variable^a logical name^
12341 that includes the directory containing
12342 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12343 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12344 directory names separated by colons (semicolons on Windows).
12345 @end itemize
12346
12347 @noindent
12348 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12349 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12350 as follows:
12351
12352 @smallexample @c projectfile
12353 @group
12354 with "gui_proj", "comm_proj";
12355 project App_Proj is
12356    for Main use ("app_main");
12357 end App_Proj;
12358 @end group
12359 @end smallexample
12360
12361 @noindent
12362 Importing other projects can create ambiguities.
12363 For example, the same unit might be present in different imported projects, or
12364 it might be present in both the importing project and in an imported project.
12365 Both of these conditions are errors.  Note that in the current version of
12366 the Project Manager, it is illegal to have an ambiguous unit even if the
12367 unit is never referenced by the importing project.  This restriction may be
12368 relaxed in a future release.
12369
12370 @node Extending a Project
12371 @subsection Extending a Project
12372
12373 @noindent
12374 In large software systems it is common to have multiple
12375 implementations of a common interface; in Ada terms, multiple versions of a
12376 package body for the same spec.  For example, one implementation
12377 might be safe for use in tasking programs, while another might only be used
12378 in sequential applications.  This can be modeled in GNAT using the concept
12379 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12380 another project (the ``parent'') then by default all source files of the
12381 parent project are inherited by the child, but the child project can
12382 override any of the parent's source files with new versions, and can also
12383 add new files.  This facility is the project analog of a type extension in
12384 Object-Oriented Programming.  Project hierarchies are permitted (a child
12385 project may be the parent of yet another project), and a project that
12386 inherits one project can also import other projects.
12387
12388 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12389 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12390 @file{pack.adb}, and @file{proc.adb}:
12391
12392 @smallexample
12393 @group
12394 ^/seq^[SEQ]^
12395   pack.ads
12396   pack.adb
12397   proc.adb
12398   seq_proj.gpr
12399 @end group
12400 @end smallexample
12401
12402 @noindent
12403 Note that the project file can simply be empty (that is, no attribute or
12404 package is defined):
12405
12406 @smallexample @c projectfile
12407 @group
12408 project Seq_Proj is
12409 end Seq_Proj;
12410 @end group
12411 @end smallexample
12412
12413 @noindent
12414 implying that its source files are all the Ada source files in the project
12415 directory.
12416
12417 Suppose we want to supply an alternate version of @file{pack.adb}, in
12418 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12419 @file{pack.ads} and @file{proc.adb}.  We can define a project
12420 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12421
12422 @smallexample
12423 @group
12424 ^/tasking^[TASKING]^
12425   pack.adb
12426   tasking_proj.gpr
12427 @end group
12428
12429 @group
12430 project Tasking_Proj extends "/seq/seq_proj" is
12431 end Tasking_Proj;
12432 @end group
12433 @end smallexample
12434
12435 @noindent
12436 The version of @file{pack.adb} used in a build depends on which project file
12437 is specified.
12438
12439 Note that we could have obtained the desired behavior using project import
12440 rather than project inheritance; a @code{base} project would contain the
12441 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12442 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12443 would import @code{base} and add a different version of @file{pack.adb}.  The
12444 choice depends on whether other sources in the original project need to be
12445 overridden.  If they do, then project extension is necessary, otherwise,
12446 importing is sufficient.
12447
12448 @noindent
12449 In a project file that extends another project file, it is possible to
12450 indicate that an inherited source is not part of the sources of the extending
12451 project. This is necessary sometimes when a package spec has been overloaded
12452 and no longer requires a body: in this case, it is necessary to indicate that
12453 the inherited body is not part of the sources of the project, otherwise there
12454 will be a compilation error when compiling the spec.
12455
12456 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12457 Its value is a string list: a list of file names. It is also possible to use
12458 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12459 the file name of a text file containing a list of file names, one per line.
12460
12461 @smallexample @c @projectfile
12462 project B extends "a" is
12463    for Source_Files use ("pkg.ads");
12464    --  New spec of Pkg does not need a completion
12465    for Excluded_Source_Files use ("pkg.adb");
12466 end B;
12467 @end smallexample
12468
12469 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12470 is still needed: if it is possible to build using @command{gnatmake} when such
12471 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12472 it is possible to remove the source completely from a system that includes
12473 project P.
12474
12475 @c ***********************
12476 @c * Project File Syntax *
12477 @c ***********************
12478
12479 @node Project File Syntax
12480 @section Project File Syntax
12481
12482 @menu
12483 * Basic Syntax::
12484 * Qualified Projects::
12485 * Packages::
12486 * Expressions::
12487 * String Types::
12488 * Variables::
12489 * Attributes::
12490 * Associative Array Attributes::
12491 * case Constructions::
12492 @end menu
12493
12494 @noindent
12495 This section describes the structure of project files.
12496
12497 A project may be an @emph{independent project}, entirely defined by a single
12498 project file. Any Ada source file in an independent project depends only
12499 on the predefined library and other Ada source files in the same project.
12500
12501 @noindent
12502 A project may also @dfn{depend on} other projects, in either or both of
12503 the following ways:
12504 @itemize @bullet
12505 @item It may import any number of projects
12506 @item It may extend at most one other project
12507 @end itemize
12508
12509 @noindent
12510 The dependence relation is a directed acyclic graph (the subgraph reflecting
12511 the ``extends'' relation is a tree).
12512
12513 A project's @dfn{immediate sources} are the source files directly defined by
12514 that project, either implicitly by residing in the project file's directory,
12515 or explicitly through any of the source-related attributes described below.
12516 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12517 of @var{proj} together with the immediate sources (unless overridden) of any
12518 project on which @var{proj} depends (either directly or indirectly).
12519
12520 @node Basic Syntax
12521 @subsection Basic Syntax
12522
12523 @noindent
12524 As seen in the earlier examples, project files have an Ada-like syntax.
12525 The minimal project file is:
12526 @smallexample @c projectfile
12527 @group
12528 project Empty is
12529
12530 end Empty;
12531 @end group
12532 @end smallexample
12533
12534 @noindent
12535 The identifier @code{Empty} is the name of the project.
12536 This project name must be present after the reserved
12537 word @code{end} at the end of the project file, followed by a semi-colon.
12538
12539 Any name in a project file, such as the project name or a variable name,
12540 has the same syntax as an Ada identifier.
12541
12542 The reserved words of project files are the Ada 95 reserved words plus
12543 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12544 reserved words currently used in project file syntax are:
12545
12546 @itemize @bullet
12547 @item
12548 @code{all}
12549 @item
12550 @code{at}
12551 @item
12552 @code{case}
12553 @item
12554 @code{end}
12555 @item
12556 @code{for}
12557 @item
12558 @code{is}
12559 @item
12560 @code{limited}
12561 @item
12562 @code{null}
12563 @item
12564 @code{others}
12565 @item
12566 @code{package}
12567 @item
12568 @code{renames}
12569 @item
12570 @code{type}
12571 @item
12572 @code{use}
12573 @item
12574 @code{when}
12575 @item
12576 @code{with}
12577 @end itemize
12578
12579 @noindent
12580 Comments in project files have the same syntax as in Ada, two consecutive
12581 hyphens through the end of the line.
12582
12583 @node Qualified Projects
12584 @subsection Qualified Projects
12585
12586 @noindent
12587 Before the reserved @code{project}, there may be one or two "qualifiers", that
12588 is identifiers or other reserved words, to qualify the project.
12589
12590 The current list of qualifiers is:
12591
12592 @itemize @bullet
12593 @item
12594 @code{abstract}: qualify a project with no sources. A qualified abstract
12595 project must either have no declaration of attributes @code{Source_Dirs},
12596 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12597 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12598 as empty. If it extends another project, the project it extends must also be a
12599 qualified abstract project.
12600
12601 @item
12602 @code{standard}: a standard project is a non library project with sources.
12603
12604 @item
12605 @code{aggregate}: for future extension
12606
12607 @item
12608 @code{aggregate library}: for future extension
12609
12610 @item
12611 @code{library}: a library project must declare both attributes
12612 @code{Library_Name} and @code{Library_Dir}.
12613
12614 @item
12615 @code{configuration}: a configuration project cannot be in a project tree.
12616 @end itemize
12617
12618 @node Packages
12619 @subsection Packages
12620
12621 @noindent
12622 A project file may contain @emph{packages}. The name of a package must be one
12623 of the identifiers from the following list. A package
12624 with a given name may only appear once in a project file. Package names are
12625 case insensitive. The following package names are legal:
12626
12627 @itemize @bullet
12628 @item
12629 @code{Naming}
12630 @item
12631 @code{Builder}
12632 @item
12633 @code{Compiler}
12634 @item
12635 @code{Binder}
12636 @item
12637 @code{Linker}
12638 @item
12639 @code{Finder}
12640 @item
12641 @code{Cross_Reference}
12642 @item
12643 @code{Eliminate}
12644 @item
12645 @code{Pretty_Printer}
12646 @item
12647 @code{Metrics}
12648 @item
12649 @code{gnatls}
12650 @item
12651 @code{gnatstub}
12652 @item
12653 @code{IDE}
12654 @item
12655 @code{Language_Processing}
12656 @end itemize
12657
12658 @noindent
12659 In its simplest form, a package may be empty:
12660
12661 @smallexample @c projectfile
12662 @group
12663 project Simple is
12664   package Builder is
12665   end Builder;
12666 end Simple;
12667 @end group
12668 @end smallexample
12669
12670 @noindent
12671 A package may contain @emph{attribute declarations},
12672 @emph{variable declarations} and @emph{case constructions}, as will be
12673 described below.
12674
12675 When there is ambiguity between a project name and a package name,
12676 the name always designates the project. To avoid possible confusion, it is
12677 always a good idea to avoid naming a project with one of the
12678 names allowed for packages or any name that starts with @code{gnat}.
12679
12680 @node Expressions
12681 @subsection Expressions
12682
12683 @noindent
12684 An @emph{expression} is either a @emph{string expression} or a
12685 @emph{string list expression}.
12686
12687 A @emph{string expression} is either a @emph{simple string expression} or a
12688 @emph{compound string expression}.
12689
12690 A @emph{simple string expression} is one of the following:
12691 @itemize @bullet
12692 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12693 @item A string-valued variable reference (@pxref{Variables})
12694 @item A string-valued attribute reference (@pxref{Attributes})
12695 @item An external reference (@pxref{External References in Project Files})
12696 @end itemize
12697
12698 @noindent
12699 A @emph{compound string expression} is a concatenation of string expressions,
12700 using the operator @code{"&"}
12701 @smallexample
12702        Path & "/" & File_Name & ".ads"
12703 @end smallexample
12704
12705 @noindent
12706 A @emph{string list expression} is either a
12707 @emph{simple string list expression} or a
12708 @emph{compound string list expression}.
12709
12710 A @emph{simple string list expression} is one of the following:
12711 @itemize @bullet
12712 @item A parenthesized list of zero or more string expressions,
12713 separated by commas
12714 @smallexample
12715    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12716    Empty_List := ();
12717 @end smallexample
12718 @item A string list-valued variable reference
12719 @item A string list-valued attribute reference
12720 @end itemize
12721
12722 @noindent
12723 A @emph{compound string list expression} is the concatenation (using
12724 @code{"&"}) of a simple string list expression and an expression.  Note that
12725 each term in a compound string list expression, except the first, may be
12726 either a string expression or a string list expression.
12727
12728 @smallexample @c projectfile
12729 @group
12730    File_Name_List := () & File_Name; --  One string in this list
12731    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12732    --  Two strings
12733    Big_List := File_Name_List & Extended_File_Name_List;
12734    --  Concatenation of two string lists: three strings
12735    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12736    --  Illegal: must start with a string list
12737 @end group
12738 @end smallexample
12739
12740 @node String Types
12741 @subsection String Types
12742
12743 @noindent
12744 A @emph{string type declaration} introduces a discrete set of string literals.
12745 If a string variable is declared to have this type, its value
12746 is restricted to the given set of literals.
12747
12748 Here is an example of a string type declaration:
12749
12750 @smallexample @c projectfile
12751    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12752 @end smallexample
12753
12754 @noindent
12755 Variables of a string type are called @emph{typed variables}; all other
12756 variables are called @emph{untyped variables}. Typed variables are
12757 particularly useful in @code{case} constructions, to support conditional
12758 attribute declarations.
12759 (@pxref{case Constructions}).
12760
12761 The string literals in the list are case sensitive and must all be different.
12762 They may include any graphic characters allowed in Ada, including spaces.
12763
12764 A string type may only be declared at the project level, not inside a package.
12765
12766 A string type may be referenced by its name if it has been declared in the same
12767 project file, or by an expanded name whose prefix is the name of the project
12768 in which it is declared.
12769
12770 @node Variables
12771 @subsection Variables
12772
12773 @noindent
12774 A variable may be declared at the project file level, or within a package.
12775 Here are some examples of variable declarations:
12776
12777 @smallexample @c projectfile
12778 @group
12779    This_OS : OS := external ("OS"); --  a typed variable declaration
12780    That_OS := "GNU/Linux";          --  an untyped variable declaration
12781 @end group
12782 @end smallexample
12783
12784 @noindent
12785 The syntax of a @emph{typed variable declaration} is identical to the Ada
12786 syntax for an object declaration. By contrast, the syntax of an untyped
12787 variable declaration is identical to an Ada assignment statement. In fact,
12788 variable declarations in project files have some of the characteristics of
12789 an assignment, in that successive declarations for the same variable are
12790 allowed. Untyped variable declarations do establish the expected kind of the
12791 variable (string or string list), and successive declarations for it must
12792 respect the initial kind.
12793
12794 @noindent
12795 A string variable declaration (typed or untyped) declares a variable
12796 whose value is a string. This variable may be used as a string expression.
12797 @smallexample @c projectfile
12798    File_Name       := "readme.txt";
12799    Saved_File_Name := File_Name & ".saved";
12800 @end smallexample
12801
12802 @noindent
12803 A string list variable declaration declares a variable whose value is a list
12804 of strings. The list may contain any number (zero or more) of strings.
12805
12806 @smallexample @c projectfile
12807    Empty_List := ();
12808    List_With_One_Element := ("^-gnaty^-gnaty^");
12809    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12810    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12811                  "pack2.ada", "util_.ada", "util.ada");
12812 @end smallexample
12813
12814 @noindent
12815 The same typed variable may not be declared more than once at project level,
12816 and it may not be declared more than once in any package; it is in effect
12817 a constant.
12818
12819 The same untyped variable may be declared several times. Declarations are
12820 elaborated in the order in which they appear, so  the new value replaces
12821 the old one, and any subsequent reference to the variable uses the new value.
12822 However, as noted above, if a variable has been declared as a string, all
12823 subsequent
12824 declarations must give it a string value. Similarly, if a variable has
12825 been declared as a string list, all subsequent declarations
12826 must give it a string list value.
12827
12828 A @emph{variable reference} may take several forms:
12829
12830 @itemize @bullet
12831 @item The simple variable name, for a variable in the current package (if any)
12832 or in the current project
12833 @item An expanded name, whose prefix is a context name.
12834 @end itemize
12835
12836 @noindent
12837 A @emph{context} may be one of the following:
12838
12839 @itemize @bullet
12840 @item The name of an existing package in the current project
12841 @item The name of an imported project of the current project
12842 @item The name of an ancestor project (i.e., a project extended by the current
12843 project, either directly or indirectly)
12844 @item An expanded name whose prefix is an imported/parent project name, and
12845 whose selector is a package name in that project.
12846 @end itemize
12847
12848 @noindent
12849 A variable reference may be used in an expression.
12850
12851 @node Attributes
12852 @subsection Attributes
12853
12854 @noindent
12855 A project (and its packages) may have @emph{attributes} that define
12856 the project's properties.  Some attributes have values that are strings;
12857 others have values that are string lists.
12858
12859 There are two categories of attributes: @emph{simple attributes}
12860 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12861
12862 Legal project attribute names, and attribute names for each legal package are
12863 listed below. Attributes names are case-insensitive.
12864
12865 The following attributes are defined on projects (all are simple attributes):
12866
12867 @multitable @columnfractions .4 .3
12868 @item @emph{Attribute Name}
12869 @tab @emph{Value}
12870 @item @code{Source_Files}
12871 @tab string list
12872 @item @code{Source_Dirs}
12873 @tab string list
12874 @item @code{Source_List_File}
12875 @tab string
12876 @item @code{Object_Dir}
12877 @tab string
12878 @item @code{Exec_Dir}
12879 @tab string
12880 @item @code{Excluded_Source_Dirs}
12881 @tab string list
12882 @item @code{Excluded_Source_Files}
12883 @tab string list
12884 @item @code{Excluded_Source_List_File}
12885 @tab string
12886 @item @code{Languages}
12887 @tab string list
12888 @item @code{Main}
12889 @tab string list
12890 @item @code{Library_Dir}
12891 @tab string
12892 @item @code{Library_Name}
12893 @tab string
12894 @item @code{Library_Kind}
12895 @tab string
12896 @item @code{Library_Version}
12897 @tab string
12898 @item @code{Library_Interface}
12899 @tab string
12900 @item @code{Library_Auto_Init}
12901 @tab string
12902 @item @code{Library_Options}
12903 @tab string list
12904 @item @code{Library_Src_Dir}
12905 @tab string
12906 @item @code{Library_ALI_Dir}
12907 @tab string
12908 @item @code{Library_GCC}
12909 @tab string
12910 @item @code{Library_Symbol_File}
12911 @tab string
12912 @item @code{Library_Symbol_Policy}
12913 @tab string
12914 @item @code{Library_Reference_Symbol_File}
12915 @tab string
12916 @item @code{Externally_Built}
12917 @tab string
12918 @end multitable
12919
12920 @noindent
12921 The following attributes are defined for package  @code{Naming}
12922 (@pxref{Naming Schemes}):
12923
12924 @multitable @columnfractions .4 .2 .2 .2
12925 @item Attribute Name @tab Category @tab Index @tab Value
12926 @item @code{Spec_Suffix}
12927 @tab associative array
12928 @tab language name
12929 @tab string
12930 @item @code{Body_Suffix}
12931 @tab associative array
12932 @tab language name
12933 @tab string
12934 @item @code{Separate_Suffix}
12935 @tab simple attribute
12936 @tab n/a
12937 @tab string
12938 @item @code{Casing}
12939 @tab simple attribute
12940 @tab n/a
12941 @tab string
12942 @item @code{Dot_Replacement}
12943 @tab simple attribute
12944 @tab n/a
12945 @tab string
12946 @item @code{Spec}
12947 @tab associative array
12948 @tab Ada unit name
12949 @tab string
12950 @item @code{Body}
12951 @tab associative array
12952 @tab Ada unit name
12953 @tab string
12954 @item @code{Specification_Exceptions}
12955 @tab associative array
12956 @tab language name
12957 @tab string list
12958 @item @code{Implementation_Exceptions}
12959 @tab associative array
12960 @tab language name
12961 @tab string list
12962 @end multitable
12963
12964 @noindent
12965 The following attributes are defined for packages @code{Builder},
12966 @code{Compiler}, @code{Binder},
12967 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12968 (@pxref{^Switches^Switches^ and Project Files}).
12969
12970 @multitable @columnfractions .4 .2 .2 .2
12971 @item Attribute Name @tab Category @tab Index @tab Value
12972 @item @code{^Default_Switches^Default_Switches^}
12973 @tab associative array
12974 @tab language name
12975 @tab string list
12976 @item @code{^Switches^Switches^}
12977 @tab associative array
12978 @tab file name
12979 @tab string list
12980 @end multitable
12981
12982 @noindent
12983 In addition, package @code{Compiler} has a single string attribute
12984 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12985 string attribute @code{Global_Configuration_Pragmas}.
12986
12987 @noindent
12988 Each simple attribute has a default value: the empty string (for string-valued
12989 attributes) and the empty list (for string list-valued attributes).
12990
12991 An attribute declaration defines a new value for an attribute.
12992
12993 Examples of simple attribute declarations:
12994
12995 @smallexample @c projectfile
12996    for Object_Dir use "objects";
12997    for Source_Dirs use ("units", "test/drivers");
12998 @end smallexample
12999
13000 @noindent
13001 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13002 attribute definition clause in Ada.
13003
13004 Attributes references may be appear in expressions.
13005 The general form for such a reference is @code{<entity>'<attribute>}:
13006 Associative array attributes are functions. Associative
13007 array attribute references must have an argument that is a string literal.
13008
13009 Examples are:
13010
13011 @smallexample @c projectfile
13012   project'Object_Dir
13013   Naming'Dot_Replacement
13014   Imported_Project'Source_Dirs
13015   Imported_Project.Naming'Casing
13016   Builder'^Default_Switches^Default_Switches^("Ada")
13017 @end smallexample
13018
13019 @noindent
13020 The prefix of an attribute may be:
13021 @itemize @bullet
13022 @item @code{project} for an attribute of the current project
13023 @item The name of an existing package of the current project
13024 @item The name of an imported project
13025 @item The name of a parent project that is extended by the current project
13026 @item An expanded name whose prefix is imported/parent project name,
13027 and whose selector is a package name
13028 @end itemize
13029
13030 @noindent
13031 Example:
13032 @smallexample @c projectfile
13033 @group
13034    project Prj is
13035      for Source_Dirs use project'Source_Dirs & "units";
13036      for Source_Dirs use project'Source_Dirs & "test/drivers"
13037    end Prj;
13038 @end group
13039 @end smallexample
13040
13041 @noindent
13042 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13043 has the default value: an empty string list. After this declaration,
13044 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13045 After the second attribute declaration @code{Source_Dirs} is a string list of
13046 two elements: @code{"units"} and @code{"test/drivers"}.
13047
13048 Note: this example is for illustration only. In practice,
13049 the project file would contain only one attribute declaration:
13050
13051 @smallexample @c projectfile
13052    for Source_Dirs use ("units", "test/drivers");
13053 @end smallexample
13054
13055 @node Associative Array Attributes
13056 @subsection Associative Array Attributes
13057
13058 @noindent
13059 Some attributes are defined as @emph{associative arrays}. An associative
13060 array may be regarded as a function that takes a string as a parameter
13061 and delivers a string or string list value as its result.
13062
13063 Here are some examples of single associative array attribute associations:
13064
13065 @smallexample @c projectfile
13066    for Body ("main") use "Main.ada";
13067    for ^Switches^Switches^ ("main.ada")
13068        use ("^-v^-v^",
13069             "^-gnatv^-gnatv^");
13070    for ^Switches^Switches^ ("main.ada")
13071             use Builder'^Switches^Switches^ ("main.ada")
13072               & "^-g^-g^";
13073 @end smallexample
13074
13075 @noindent
13076 Like untyped variables and simple attributes, associative array attributes
13077 may be declared several times. Each declaration supplies a new value for the
13078 attribute, and replaces the previous setting.
13079
13080 @noindent
13081 An associative array attribute may be declared as a full associative array
13082 declaration, with the value of the same attribute in an imported or extended
13083 project.
13084
13085 @smallexample @c projectfile
13086    package Builder is
13087       for Default_Switches use Default.Builder'Default_Switches;
13088    end Builder;
13089 @end smallexample
13090
13091 @noindent
13092 In this example, @code{Default} must be either a project imported by the
13093 current project, or the project that the current project extends. If the
13094 attribute is in a package (in this case, in package @code{Builder}), the same
13095 package needs to be specified.
13096
13097 @noindent
13098 A full associative array declaration replaces any other declaration for the
13099 attribute, including other full associative array declaration. Single
13100 associative array associations may be declare after a full associative
13101 declaration, modifying the value for a single association of the attribute.
13102
13103 @node case Constructions
13104 @subsection @code{case} Constructions
13105
13106 @noindent
13107 A @code{case} construction is used in a project file to effect conditional
13108 behavior.
13109 Here is a typical example:
13110
13111 @smallexample @c projectfile
13112 @group
13113 project MyProj is
13114    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13115
13116    OS : OS_Type := external ("OS", "GNU/Linux");
13117 @end group
13118
13119 @group
13120    package Compiler is
13121      case OS is
13122        when "GNU/Linux" | "Unix" =>
13123          for ^Default_Switches^Default_Switches^ ("Ada")
13124              use ("^-gnath^-gnath^");
13125        when "NT" =>
13126          for ^Default_Switches^Default_Switches^ ("Ada")
13127              use ("^-gnatP^-gnatP^");
13128        when others =>
13129      end case;
13130    end Compiler;
13131 end MyProj;
13132 @end group
13133 @end smallexample
13134
13135 @noindent
13136 The syntax of a @code{case} construction is based on the Ada case statement
13137 (although there is no @code{null} construction for empty alternatives).
13138
13139 The case expression must be a typed string variable.
13140 Each alternative comprises the reserved word @code{when}, either a list of
13141 literal strings separated by the @code{"|"} character or the reserved word
13142 @code{others},  and the @code{"=>"} token.
13143 Each literal string must belong to the string type that is the type of the
13144 case variable.
13145 An @code{others} alternative, if present, must occur last.
13146
13147 After each @code{=>}, there are zero or more constructions.  The only
13148 constructions allowed in a case construction are other case constructions,
13149 attribute declarations and variable declarations. String type declarations and
13150 package declarations are not allowed. Variable declarations are restricted to
13151 variables that have already been declared before the case construction.
13152
13153 The value of the case variable is often given by an external reference
13154 (@pxref{External References in Project Files}).
13155
13156 @c ****************************************
13157 @c * Objects and Sources in Project Files *
13158 @c ****************************************
13159
13160 @node Objects and Sources in Project Files
13161 @section Objects and Sources in Project Files
13162
13163 @menu
13164 * Object Directory::
13165 * Exec Directory::
13166 * Source Directories::
13167 * Source File Names::
13168 @end menu
13169
13170 @noindent
13171 Each project has exactly one object directory and one or more source
13172 directories. The source directories must contain at least one source file,
13173 unless  the project file explicitly specifies that no source files are present
13174 (@pxref{Source File Names}).
13175
13176 @node Object Directory
13177 @subsection Object Directory
13178
13179 @noindent
13180 The object directory for a project is the directory containing the compiler's
13181 output (such as @file{ALI} files and object files) for the project's immediate
13182 sources.
13183
13184 The object directory is given by the value of the attribute @code{Object_Dir}
13185 in the project file.
13186
13187 @smallexample @c projectfile
13188    for Object_Dir use "objects";
13189 @end smallexample
13190
13191 @noindent
13192 The attribute @code{Object_Dir} has a string value, the path name of the object
13193 directory. The path name may be absolute or relative to the directory of the
13194 project file. This directory must already exist, and be readable and writable.
13195
13196 By default, when the attribute @code{Object_Dir} is not given an explicit value
13197 or when its value is the empty string, the object directory is the same as the
13198 directory containing the project file.
13199
13200 @node Exec Directory
13201 @subsection Exec Directory
13202
13203 @noindent
13204 The exec directory for a project is the directory containing the executables
13205 for the project's main subprograms.
13206
13207 The exec directory is given by the value of the attribute @code{Exec_Dir}
13208 in the project file.
13209
13210 @smallexample @c projectfile
13211    for Exec_Dir use "executables";
13212 @end smallexample
13213
13214 @noindent
13215 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13216 directory. The path name may be absolute or relative to the directory of the
13217 project file. This directory must already exist, and be writable.
13218
13219 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13220 or when its value is the empty string, the exec directory is the same as the
13221 object directory of the project file.
13222
13223 @node Source Directories
13224 @subsection Source Directories
13225
13226 @noindent
13227 The source directories of a project are specified by the project file
13228 attribute @code{Source_Dirs}.
13229
13230 This attribute's value is a string list. If the attribute is not given an
13231 explicit value, then there is only one source directory, the one where the
13232 project file resides.
13233
13234 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13235 as in
13236
13237 @smallexample @c projectfile
13238     for Source_Dirs use ();
13239 @end smallexample
13240
13241 @noindent
13242 indicates that the project contains no source files.
13243
13244 Otherwise, each string in the string list designates one or more
13245 source directories.
13246
13247 @smallexample @c projectfile
13248    for Source_Dirs use ("sources", "test/drivers");
13249 @end smallexample
13250
13251 @noindent
13252 If a string in the list ends with @code{"/**"},  then the directory whose path
13253 name precedes the two asterisks, as well as all its subdirectories
13254 (recursively), are source directories.
13255
13256 @smallexample @c projectfile
13257    for Source_Dirs use ("/system/sources/**");
13258 @end smallexample
13259
13260 @noindent
13261 Here the directory @code{/system/sources} and all of its subdirectories
13262 (recursively) are source directories.
13263
13264 To specify that the source directories are the directory of the project file
13265 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13266 @smallexample @c projectfile
13267    for Source_Dirs use ("./**");
13268 @end smallexample
13269
13270 @noindent
13271 Each of the source directories must exist and be readable.
13272
13273 @node Source File Names
13274 @subsection Source File Names
13275
13276 @noindent
13277 In a project that contains source files, their names may be specified by the
13278 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13279 (a string). Source file names never include any directory information.
13280
13281 If the attribute @code{Source_Files} is given an explicit value, then each
13282 element of the list is a source file name.
13283
13284 @smallexample @c projectfile
13285    for Source_Files use ("main.adb");
13286    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13287 @end smallexample
13288
13289 @noindent
13290 If the attribute @code{Source_Files} is not given an explicit value,
13291 but the attribute @code{Source_List_File} is given a string value,
13292 then the source file names are contained in the text file whose path name
13293 (absolute or relative to the directory of the project file) is the
13294 value of the attribute @code{Source_List_File}.
13295
13296 Each line in the file that is not empty or is not a comment
13297 contains a source file name.
13298
13299 @smallexample @c projectfile
13300    for Source_List_File use "source_list.txt";
13301 @end smallexample
13302
13303 @noindent
13304 By default, if neither the attribute @code{Source_Files} nor the attribute
13305 @code{Source_List_File} is given an explicit value, then each file in the
13306 source directories that conforms to the project's naming scheme
13307 (@pxref{Naming Schemes}) is an immediate source of the project.
13308
13309 A warning is issued if both attributes @code{Source_Files} and
13310 @code{Source_List_File} are given explicit values. In this case, the attribute
13311 @code{Source_Files} prevails.
13312
13313 Each source file name must be the name of one existing source file
13314 in one of the source directories.
13315
13316 A @code{Source_Files} attribute whose value is an empty list
13317 indicates that there are no source files in the project.
13318
13319 If the order of the source directories is known statically, that is if
13320 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13321 be several files with the same source file name. In this case, only the file
13322 in the first directory is considered as an immediate source of the project
13323 file. If the order of the source directories is not known statically, it is
13324 an error to have several files with the same source file name.
13325
13326 Projects can be specified to have no Ada source
13327 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13328 list, or the @code{"Ada"} may be absent from @code{Languages}:
13329
13330 @smallexample @c projectfile
13331    for Source_Dirs use ();
13332    for Source_Files use ();
13333    for Languages use ("C", "C++");
13334 @end smallexample
13335
13336 @noindent
13337 Otherwise, a project must contain at least one immediate source.
13338
13339 Projects with no source files are useful as template packages
13340 (@pxref{Packages in Project Files}) for other projects; in particular to
13341 define a package @code{Naming} (@pxref{Naming Schemes}).
13342
13343 @c ****************************
13344 @c * Importing Projects *
13345 @c ****************************
13346
13347 @node  Importing Projects
13348 @section Importing Projects
13349 @cindex @code{ADA_PROJECT_PATH}
13350
13351 @noindent
13352 An immediate source of a project P may depend on source files that
13353 are neither immediate sources of P nor in the predefined library.
13354 To get this effect, P must @emph{import} the projects that contain the needed
13355 source files.
13356
13357 @smallexample @c projectfile
13358 @group
13359   with "project1", "utilities.gpr";
13360   with "/namings/apex.gpr";
13361   project Main is
13362     @dots{}
13363 @end group
13364 @end smallexample
13365
13366 @noindent
13367 As can be seen in this example, the syntax for importing projects is similar
13368 to the syntax for importing compilation units in Ada. However, project files
13369 use literal strings instead of names, and the @code{with} clause identifies
13370 project files rather than packages.
13371
13372 Each literal string is the file name or path name (absolute or relative) of a
13373 project file. If a string corresponds to a file name, with no path or a
13374 relative path, then its location is determined by the @emph{project path}. The
13375 latter can be queried using @code{gnatls -v}. It contains:
13376
13377 @itemize @bullet
13378 @item
13379 In first position, the directory containing the current project file.
13380 @item
13381 In last position, the default project directory. This default project directory
13382 is part of the GNAT installation and is the standard place to install project
13383 files giving access to standard support libraries.
13384 @ifclear vms
13385 @ref{Installing a library}
13386 @end ifclear
13387
13388 @item
13389 In between, all the directories referenced in the
13390 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13391 @end itemize
13392
13393 @noindent
13394 If a relative pathname is used, as in
13395
13396 @smallexample @c projectfile
13397   with "tests/proj";
13398 @end smallexample
13399
13400 @noindent
13401 then the full path for the project is constructed by concatenating this
13402 relative path to those in the project path, in order, until a matching file is
13403 found. Any symbolic link will be fully resolved in the directory of the
13404 importing project file before the imported project file is examined.
13405
13406 If the @code{with}'ed project file name does not have an extension,
13407 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13408 then the file name as specified in the @code{with} clause (no extension) will
13409 be used. In the above example, if a file @code{project1.gpr} is found, then it
13410 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13411 then it will be used; if neither file exists, this is an error.
13412
13413 A warning is issued if the name of the project file does not match the
13414 name of the project; this check is case insensitive.
13415
13416 Any source file that is an immediate source of the imported project can be
13417 used by the immediate sources of the importing project, transitively. Thus
13418 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13419 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13420 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13421 because if and when @code{B} ceases to import @code{C}, some sources in
13422 @code{A} will no longer compile.
13423
13424 A side effect of this capability is that normally cyclic dependencies are not
13425 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13426 is not allowed to import @code{A}. However, there are cases when cyclic
13427 dependencies would be beneficial. For these cases, another form of import
13428 between projects exists, the @code{limited with}: a project @code{A} that
13429 imports a project @code{B} with a straight @code{with} may also be imported,
13430 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13431 to @code{A} include at least one @code{limited with}.
13432
13433 @smallexample @c 0projectfile
13434 with "../b/b.gpr";
13435 with "../c/c.gpr";
13436 project A is
13437 end A;
13438
13439 limited with "../a/a.gpr";
13440 project B is
13441 end B;
13442
13443 with "../d/d.gpr";
13444 project C is
13445 end C;
13446
13447 limited with "../a/a.gpr";
13448 project D is
13449 end D;
13450 @end smallexample
13451
13452 @noindent
13453 In the above legal example, there are two project cycles:
13454 @itemize @bullet
13455 @item A-> B-> A
13456 @item A -> C -> D -> A
13457 @end itemize
13458
13459 @noindent
13460 In each of these cycle there is one @code{limited with}: import of @code{A}
13461 from @code{B} and import of @code{A} from @code{D}.
13462
13463 The difference between straight @code{with} and @code{limited with} is that
13464 the name of a project imported with a @code{limited with} cannot be used in the
13465 project that imports it. In particular, its packages cannot be renamed and
13466 its variables cannot be referred to.
13467
13468 An exception to the above rules for @code{limited with} is that for the main
13469 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13470 @code{limited with} is equivalent to a straight @code{with}. For example,
13471 in the example above, projects @code{B} and @code{D} could not be main
13472 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13473 each have a @code{limited with} that is the only one in a cycle of importing
13474 projects.
13475
13476 @c *********************
13477 @c * Project Extension *
13478 @c *********************
13479
13480 @node Project Extension
13481 @section Project Extension
13482
13483 @noindent
13484 During development of a large system, it is sometimes necessary to use
13485 modified versions of some of the source files, without changing the original
13486 sources. This can be achieved through the @emph{project extension} facility.
13487
13488 @smallexample @c projectfile
13489    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13490 @end smallexample
13491
13492 @noindent
13493 A project extension declaration introduces an extending project
13494 (the @emph{child}) and a project being extended (the @emph{parent}).
13495
13496 By default, a child project inherits all the sources of its parent.
13497 However, inherited sources can be overridden: a unit in a parent is hidden
13498 by a unit of the same name in the child.
13499
13500 Inherited sources are considered to be sources (but not immediate sources)
13501 of the child project; see @ref{Project File Syntax}.
13502
13503 An inherited source file retains any switches specified in the parent project.
13504
13505 For example if the project @code{Utilities} contains the spec and the
13506 body of an Ada package @code{Util_IO}, then the project
13507 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13508 The original body of @code{Util_IO} will not be considered in program builds.
13509 However, the package spec will still be found in the project
13510 @code{Utilities}.
13511
13512 A child project can have only one parent, except when it is qualified as
13513 abstract. But it may import any number of other projects.
13514
13515 A project is not allowed to import directly or indirectly at the same time a
13516 child project and any of its ancestors.
13517
13518 @c *******************************
13519 @c * Project Hierarchy Extension *
13520 @c *******************************
13521
13522 @node Project Hierarchy Extension
13523 @section Project Hierarchy Extension
13524
13525 @noindent
13526 When extending a large system spanning multiple projects, it is often
13527 inconvenient to extend every project in the hierarchy that is impacted by a
13528 small change introduced. In such cases, it is possible to create a virtual
13529 extension of entire hierarchy using @code{extends all} relationship.
13530
13531 When the project is extended using @code{extends all} inheritance, all projects
13532 that are imported by it, both directly and indirectly, are considered virtually
13533 extended. That is, the Project Manager creates "virtual projects"
13534 that extend every project in the hierarchy; all these virtual projects have
13535 no sources of their own and have as object directory the object directory of
13536 the root of "extending all" project.
13537
13538 It is possible to explicitly extend one or more projects in the hierarchy
13539 in order to modify the sources. These extending projects must be imported by
13540 the "extending all" project, which will replace the corresponding virtual
13541 projects with the explicit ones.
13542
13543 When building such a project hierarchy extension, the Project Manager will
13544 ensure that both modified sources and sources in virtual extending projects
13545 that depend on them, are recompiled.
13546
13547 By means of example, consider the following hierarchy of projects.
13548
13549 @enumerate
13550 @item
13551 project A, containing package P1
13552 @item
13553 project B importing A and containing package P2 which depends on P1
13554 @item
13555 project C importing B and containing package P3 which depends on P2
13556 @end enumerate
13557
13558 @noindent
13559 We want to modify packages P1 and P3.
13560
13561 This project hierarchy will need to be extended as follows:
13562
13563 @enumerate
13564 @item
13565 Create project A1 that extends A, placing modified P1 there:
13566
13567 @smallexample @c 0projectfile
13568 project A1 extends "(@dots{})/A" is
13569 end A1;
13570 @end smallexample
13571
13572 @item
13573 Create project C1 that "extends all" C and imports A1, placing modified
13574 P3 there:
13575
13576 @smallexample @c 0projectfile
13577 with "(@dots{})/A1";
13578 project C1 extends all "(@dots{})/C" is
13579 end C1;
13580 @end smallexample
13581 @end enumerate
13582
13583 When you build project C1, your entire modified project space will be
13584 recompiled, including the virtual project B1 that has been impacted by the
13585 "extending all" inheritance of project C.
13586
13587 Note that if a Library Project in the hierarchy is virtually extended,
13588 the virtual project that extends the Library Project is not a Library Project.
13589
13590 @c ****************************************
13591 @c * External References in Project Files *
13592 @c ****************************************
13593
13594 @node  External References in Project Files
13595 @section External References in Project Files
13596
13597 @noindent
13598 A project file may contain references to external variables; such references
13599 are called @emph{external references}.
13600
13601 An external variable is either defined as part of the environment (an
13602 environment variable in Unix, for example) or else specified on the command
13603 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13604 If both, then the command line value is used.
13605
13606 The value of an external reference is obtained by means of the built-in
13607 function @code{external}, which returns a string value.
13608 This function has two forms:
13609 @itemize @bullet
13610 @item @code{external (external_variable_name)}
13611 @item @code{external (external_variable_name, default_value)}
13612 @end itemize
13613
13614 @noindent
13615 Each parameter must be a string literal.  For example:
13616
13617 @smallexample @c projectfile
13618    external ("USER")
13619    external ("OS", "GNU/Linux")
13620 @end smallexample
13621
13622 @noindent
13623 In the form with one parameter, the function returns the value of
13624 the external variable given as parameter. If this name is not present in the
13625 environment, the function returns an empty string.
13626
13627 In the form with two string parameters, the second argument is
13628 the value returned when the variable given as the first argument is not
13629 present in the environment. In the example above, if @code{"OS"} is not
13630 the name of ^an environment variable^a logical name^ and is not passed on
13631 the command line, then the returned value is @code{"GNU/Linux"}.
13632
13633 An external reference may be part of a string expression or of a string
13634 list expression, and can therefore appear in a variable declaration or
13635 an attribute declaration.
13636
13637 @smallexample @c projectfile
13638 @group
13639    type Mode_Type is ("Debug", "Release");
13640    Mode : Mode_Type := external ("MODE");
13641    case Mode is
13642      when "Debug" =>
13643         @dots{}
13644 @end group
13645 @end smallexample
13646
13647 @c *****************************
13648 @c * Packages in Project Files *
13649 @c *****************************
13650
13651 @node  Packages in Project Files
13652 @section Packages in Project Files
13653
13654 @noindent
13655 A @emph{package} defines the settings for project-aware tools within a
13656 project.
13657 For each such tool one can declare a package; the names for these
13658 packages are preset (@pxref{Packages}).
13659 A package may contain variable declarations, attribute declarations, and case
13660 constructions.
13661
13662 @smallexample @c projectfile
13663 @group
13664    project Proj is
13665       package Builder is  -- used by gnatmake
13666          for ^Default_Switches^Default_Switches^ ("Ada")
13667              use ("^-v^-v^",
13668                   "^-g^-g^");
13669       end Builder;
13670    end Proj;
13671 @end group
13672 @end smallexample
13673
13674 @noindent
13675 The syntax of package declarations mimics that of package in Ada.
13676
13677 Most of the packages have an attribute
13678 @code{^Default_Switches^Default_Switches^}.
13679 This attribute is an associative array, and its value is a string list.
13680 The index of the associative array is the name of a programming language (case
13681 insensitive). This attribute indicates the ^switch^switch^
13682 or ^switches^switches^ to be used
13683 with the corresponding tool.
13684
13685 Some packages also have another attribute, @code{^Switches^Switches^},
13686 an associative array whose value is a string list.
13687 The index is the name of a source file.
13688 This attribute indicates the ^switch^switch^
13689 or ^switches^switches^ to be used by the corresponding
13690 tool when dealing with this specific file.
13691
13692 Further information on these ^switch^switch^-related attributes is found in
13693 @ref{^Switches^Switches^ and Project Files}.
13694
13695 A package may be declared as a @emph{renaming} of another package; e.g., from
13696 the project file for an imported project.
13697
13698 @smallexample @c projectfile
13699 @group
13700   with "/global/apex.gpr";
13701   project Example is
13702     package Naming renames Apex.Naming;
13703     @dots{}
13704   end Example;
13705 @end group
13706 @end smallexample
13707
13708 @noindent
13709 Packages that are renamed in other project files often come from project files
13710 that have no sources: they are just used as templates. Any modification in the
13711 template will be reflected automatically in all the project files that rename
13712 a package from the template.
13713
13714 In addition to the tool-oriented packages, you can also declare a package
13715 named @code{Naming} to establish specialized source file naming conventions
13716 (@pxref{Naming Schemes}).
13717
13718 @c ************************************
13719 @c * Variables from Imported Projects *
13720 @c ************************************
13721
13722 @node Variables from Imported Projects
13723 @section Variables from Imported Projects
13724
13725 @noindent
13726 An attribute or variable defined in an imported or parent project can
13727 be used in expressions in the importing / extending project.
13728 Such an attribute or variable is denoted by an expanded name whose prefix
13729 is either the name of the project or the expanded name of a package within
13730 a project.
13731
13732 @smallexample @c projectfile
13733 @group
13734   with "imported";
13735   project Main extends "base" is
13736      Var1 := Imported.Var;
13737      Var2 := Base.Var & ".new";
13738 @end group
13739
13740 @group
13741      package Builder is
13742         for ^Default_Switches^Default_Switches^ ("Ada")
13743             use Imported.Builder'Ada_^Switches^Switches^ &
13744                 "^-gnatg^-gnatg^" &
13745                 "^-v^-v^";
13746      end Builder;
13747 @end group
13748
13749 @group
13750      package Compiler is
13751         for ^Default_Switches^Default_Switches^ ("Ada")
13752             use Base.Compiler'Ada_^Switches^Switches^;
13753      end Compiler;
13754   end Main;
13755 @end group
13756 @end smallexample
13757
13758 @noindent
13759 In this example:
13760
13761 @itemize @bullet
13762 @item
13763 The value of @code{Var1} is a copy of the variable @code{Var} defined
13764 in the project file @file{"imported.gpr"}
13765 @item
13766 the value of @code{Var2} is a copy of the value of variable @code{Var}
13767 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13768 @item
13769 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13770 @code{Builder} is a string list that includes in its value a copy of the value
13771 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13772 in project file @file{imported.gpr} plus two new elements:
13773 @option{"^-gnatg^-gnatg^"}
13774 and @option{"^-v^-v^"};
13775 @item
13776 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13777 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13778 defined in the @code{Compiler} package in project file @file{base.gpr},
13779 the project being extended.
13780 @end itemize
13781
13782 @c ******************
13783 @c * Naming Schemes *
13784 @c ******************
13785
13786 @node  Naming Schemes
13787 @section Naming Schemes
13788
13789 @noindent
13790 Sometimes an Ada software system is ported from a foreign compilation
13791 environment to GNAT, and the file names do not use the default GNAT
13792 conventions. Instead of changing all the file names (which for a variety
13793 of reasons might not be possible), you can define the relevant file
13794 naming scheme in the @code{Naming} package in your project file.
13795
13796 @noindent
13797 Note that the use of pragmas described in
13798 @ref{Alternative File Naming Schemes} by mean of a configuration
13799 pragmas file is not supported when using project files. You must use
13800 the features described in this paragraph. You can however use specify
13801 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13802
13803 @ifclear vms
13804 For example, the following
13805 package models the Apex file naming rules:
13806
13807 @smallexample @c projectfile
13808 @group
13809   package Naming is
13810     for Casing               use "lowercase";
13811     for Dot_Replacement      use ".";
13812     for Spec_Suffix ("Ada")  use ".1.ada";
13813     for Body_Suffix ("Ada")  use ".2.ada";
13814   end Naming;
13815 @end group
13816 @end smallexample
13817 @end ifclear
13818
13819 @ifset vms
13820 For example, the following package models the HP Ada file naming rules:
13821
13822 @smallexample @c projectfile
13823 @group
13824   package Naming is
13825     for Casing               use "lowercase";
13826     for Dot_Replacement      use "__";
13827     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13828     for Body_Suffix ("Ada")  use ".^ada^ada^";
13829   end Naming;
13830 @end group
13831 @end smallexample
13832
13833 @noindent
13834 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13835 names in lower case)
13836 @end ifset
13837
13838 @noindent
13839 You can define the following attributes in package @code{Naming}:
13840
13841 @table @code
13842
13843 @item @code{Casing}
13844 This must be a string with one of the three values @code{"lowercase"},
13845 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13846
13847 @noindent
13848 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13849
13850 @item @code{Dot_Replacement}
13851 This must be a string whose value satisfies the following conditions:
13852
13853 @itemize @bullet
13854 @item It must not be empty
13855 @item It cannot start or end with an alphanumeric character
13856 @item It cannot be a single underscore
13857 @item It cannot start with an underscore followed by an alphanumeric
13858 @item It cannot contain a dot @code{'.'} except if the entire string
13859 is @code{"."}
13860 @end itemize
13861
13862 @noindent
13863 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13864
13865 @item @code{Spec_Suffix}
13866 This is an associative array (indexed by the programming language name, case
13867 insensitive) whose value is a string that must satisfy the following
13868 conditions:
13869
13870 @itemize @bullet
13871 @item It must not be empty
13872 @item It must include at least one dot
13873 @end itemize
13874 @noindent
13875 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13876 @code{"^.ads^.ADS^"}.
13877
13878 @item @code{Body_Suffix}
13879 This is an associative array (indexed by the programming language name, case
13880 insensitive) whose value is a string that must satisfy the following
13881 conditions:
13882
13883 @itemize @bullet
13884 @item It must not be empty
13885 @item It must include at least one dot
13886 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13887 @end itemize
13888 @noindent
13889 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13890 same string, then a file name that ends with the longest of these two suffixes
13891 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13892 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13893
13894 If the suffix does not start with a '.', a file with a name exactly equal
13895 to the suffix will also be part of the project (for instance if you define
13896 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13897 of the project. This is not interesting in general when using projects to
13898 compile. However, it might become useful when a project is also used to
13899 find the list of source files in an editor, like the GNAT Programming System
13900 (GPS).
13901
13902 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13903 @code{"^.adb^.ADB^"}.
13904
13905 @item @code{Separate_Suffix}
13906 This must be a string whose value satisfies the same conditions as
13907 @code{Body_Suffix}. The same "longest suffix" rules apply.
13908
13909 @noindent
13910 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13911 value as @code{Body_Suffix ("Ada")}.
13912
13913 @item @code{Spec}
13914 @noindent
13915 You can use the associative array attribute @code{Spec}  to define
13916 the source file name for an individual Ada compilation unit's spec. The array
13917 index must be a string literal that identifies the Ada unit (case insensitive).
13918 The value of this attribute must be a string that identifies the file that
13919 contains this unit's spec (case sensitive or insensitive depending on the
13920 operating system).
13921
13922 @smallexample @c projectfile
13923    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13924 @end smallexample
13925
13926 When the source file contains several units, you can indicate at what
13927 position the unit occurs in the file, with the following. The first unit
13928 in the file has index 1
13929
13930 @smallexample @c projectfile
13931   for Body ("top") use "foo.a" at 1;
13932   for Body ("foo") use "foo.a" at 2;
13933 @end smallexample
13934
13935 @item @code{Body}
13936
13937 You can use the associative array attribute @code{Body} to
13938 define the source file name for an individual Ada compilation unit's body
13939 (possibly a subunit).  The array index must be a string literal that identifies
13940 the Ada unit (case insensitive).  The value of this attribute must be a string
13941 that identifies the file that contains this unit's body or subunit (case
13942 sensitive or insensitive depending on the operating system).
13943
13944 @smallexample @c projectfile
13945    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13946 @end smallexample
13947 @end table
13948
13949 @c ********************
13950 @c * Library Projects *
13951 @c ********************
13952
13953 @node Library Projects
13954 @section Library Projects
13955
13956 @noindent
13957 @emph{Library projects} are projects whose object code is placed in a library.
13958 (Note that this facility is not yet supported on all platforms).
13959
13960 @code{gnatmake} or @code{gprbuild} will collect all object files into a
13961 single archive, which might either be a shared or a static library. This
13962 library can later on be linked with multiple executables, potentially
13963 reducing their sizes.
13964
13965 If your project file specifies languages other than Ada, but you are still
13966 using @code{gnatmake} to compile and link, the latter will not try to
13967 compile your sources other than Ada (you should use @code{gprbuild} if that
13968 is your intent). However, @code{gnatmake} will automatically link all object
13969 files found in the object directory, whether or not they were compiled from
13970 an Ada source file. This specific behavior only applies when multiple
13971 languages are specified.
13972
13973 To create a library project, you need to define in its project file
13974 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13975 Additionally, you may define other library-related attributes such as
13976 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13977 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13978
13979 The @code{Library_Name} attribute has a string value. There is no restriction
13980 on the name of a library. It is the responsibility of the developer to
13981 choose a name that will be accepted by the platform. It is recommended to
13982 choose names that could be Ada identifiers; such names are almost guaranteed
13983 to be acceptable on all platforms.
13984
13985 The @code{Library_Dir} attribute has a string value that designates the path
13986 (absolute or relative) of the directory where the library will reside.
13987 It must designate an existing directory, and this directory must be writable,
13988 different from the project's object directory and from any source directory
13989 in the project tree.
13990
13991 If both @code{Library_Name} and @code{Library_Dir} are specified and
13992 are legal, then the project file defines a library project.  The optional
13993 library-related attributes are checked only for such project files.
13994
13995 The @code{Library_Kind} attribute has a string value that must be one of the
13996 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13997 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13998 attribute is not specified, the library is a static library, that is
13999 an archive of object files that can be potentially linked into a
14000 static executable. Otherwise, the library may be dynamic or
14001 relocatable, that is a library that is loaded only at the start of execution.
14002
14003 If you need to build both a static and a dynamic library, you should use two
14004 different object directories, since in some cases some extra code needs to
14005 be generated for the latter. For such cases, it is recommended to either use
14006 two different project files, or a single one which uses external variables
14007 to indicate what kind of library should be build.
14008
14009 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14010 directory where the ALI files of the library will be copied. When it is
14011 not specified, the ALI files are copied to the directory specified in
14012 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14013 must be writable and different from the project's object directory and from
14014 any source directory in the project tree.
14015
14016 The @code{Library_Version} attribute has a string value whose interpretation
14017 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14018 used only for dynamic/relocatable libraries as the internal name of the
14019 library (the @code{"soname"}). If the library file name (built from the
14020 @code{Library_Name}) is different from the @code{Library_Version}, then the
14021 library file will be a symbolic link to the actual file whose name will be
14022 @code{Library_Version}.
14023
14024 Example (on Unix):
14025
14026 @smallexample @c projectfile
14027 @group
14028 project Plib is
14029
14030    Version := "1";
14031
14032    for Library_Dir use "lib_dir";
14033    for Library_Name use "dummy";
14034    for Library_Kind use "relocatable";
14035    for Library_Version use "libdummy.so." & Version;
14036
14037 end Plib;
14038 @end group
14039 @end smallexample
14040
14041 @noindent
14042 Directory @file{lib_dir} will contain the internal library file whose name
14043 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14044 @file{libdummy.so.1}.
14045
14046 When @command{gnatmake} detects that a project file
14047 is a library project file, it will check all immediate sources of the project
14048 and rebuild the library if any of the sources have been recompiled.
14049
14050 Standard project files can import library project files. In such cases,
14051 the libraries will only be rebuilt if some of its sources are recompiled
14052 because they are in the closure of some other source in an importing project.
14053 Sources of the library project files that are not in such a closure will
14054 not be checked, unless the full library is checked, because one of its sources
14055 needs to be recompiled.
14056
14057 For instance, assume the project file @code{A} imports the library project file
14058 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14059 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14060 @file{l2.ads}, @file{l2.adb}.
14061
14062 If @file{l1.adb} has been modified, then the library associated with @code{L}
14063 will be rebuilt when compiling all the immediate sources of @code{A} only
14064 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14065 @code{"with L1;"}.
14066
14067 To be sure that all the sources in the library associated with @code{L} are
14068 up to date, and that all the sources of project @code{A} are also up to date,
14069 the following two commands needs to be used:
14070
14071 @smallexample
14072 gnatmake -Pl.gpr
14073 gnatmake -Pa.gpr
14074 @end smallexample
14075
14076 When a library is built or rebuilt, an attempt is made first to delete all
14077 files in the library directory.
14078 All @file{ALI} files will also be copied from the object directory to the
14079 library directory. To build executables, @command{gnatmake} will use the
14080 library rather than the individual object files.
14081
14082 @ifclear vms
14083 It is also possible to create library project files for third-party libraries
14084 that are precompiled and cannot be compiled locally thanks to the
14085 @code{externally_built} attribute. (See @ref{Installing a library}).
14086 @end ifclear
14087
14088 @c *******************************
14089 @c * Stand-alone Library Projects *
14090 @c *******************************
14091
14092 @node Stand-alone Library Projects
14093 @section Stand-alone Library Projects
14094
14095 @noindent
14096 A Stand-alone Library is a library that contains the necessary code to
14097 elaborate the Ada units that are included in the library. A Stand-alone
14098 Library is suitable to be used in an executable when the main is not
14099 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14100 subprogram.
14101
14102 A Stand-alone Library Project is a Library Project where the library is
14103 a Stand-alone Library.
14104
14105 To be a Stand-alone Library Project, in addition to the two attributes
14106 that make a project a Library Project (@code{Library_Name} and
14107 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14108 @code{Library_Interface} must be defined.
14109
14110 @smallexample @c projectfile
14111 @group
14112    for Library_Dir use "lib_dir";
14113    for Library_Name use "dummy";
14114    for Library_Interface use ("int1", "int1.child");
14115 @end group
14116 @end smallexample
14117
14118 Attribute @code{Library_Interface} has a nonempty string list value,
14119 each string in the list designating a unit contained in an immediate source
14120 of the project file.
14121
14122 When a Stand-alone Library is built, first the binder is invoked to build
14123 a package whose name depends on the library name
14124 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14125 This binder-generated package includes initialization and
14126 finalization procedures whose
14127 names depend on the library name (dummyinit and dummyfinal in the example
14128 above). The object corresponding to this package is included in the library.
14129
14130 A dynamic or relocatable Stand-alone Library is automatically initialized
14131 if automatic initialization of Stand-alone Libraries is supported on the
14132 platform and if attribute @code{Library_Auto_Init} is not specified or
14133 is specified with the value "true". A static Stand-alone Library is never
14134 automatically initialized.
14135
14136 Single string attribute @code{Library_Auto_Init} may be specified with only
14137 two possible values: "false" or "true" (case-insensitive). Specifying
14138 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14139 initialization of dynamic or relocatable libraries.
14140
14141 When a non-automatically initialized Stand-alone Library is used
14142 in an executable, its initialization procedure must be called before
14143 any service of the library is used.
14144 When the main subprogram is in Ada, it may mean that the initialization
14145 procedure has to be called during elaboration of another package.
14146
14147 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14148 (those that are listed in attribute @code{Library_Interface}) are copied to
14149 the Library Directory. As a consequence, only the Interface Units may be
14150 imported from Ada units outside of the library. If other units are imported,
14151 the binding phase will fail.
14152
14153 When a Stand-Alone Library is bound, the switches that are specified in
14154 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14155 used in the call to @command{gnatbind}.
14156
14157 The string list attribute @code{Library_Options} may be used to specified
14158 additional switches to the call to @command{gcc} to link the library.
14159
14160 The attribute @code{Library_Src_Dir}, may be specified for a
14161 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14162 single string value. Its value must be the path (absolute or relative to the
14163 project directory) of an existing directory. This directory cannot be the
14164 object directory or one of the source directories, but it can be the same as
14165 the library directory. The sources of the Interface
14166 Units of the library, necessary to an Ada client of the library, will be
14167 copied to the designated directory, called Interface Copy directory.
14168 These sources includes the specs of the Interface Units, but they may also
14169 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14170 are used, or when there is a generic units in the spec. Before the sources
14171 are copied to the Interface Copy directory, an attempt is made to delete all
14172 files in the Interface Copy directory.
14173
14174 @c *************************************
14175 @c * Switches Related to Project Files *
14176 @c *************************************
14177 @node Switches Related to Project Files
14178 @section Switches Related to Project Files
14179
14180 @noindent
14181 The following switches are used by GNAT tools that support project files:
14182
14183 @table @option
14184
14185 @item ^-P^/PROJECT_FILE=^@var{project}
14186 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14187 Indicates the name of a project file. This project file will be parsed with
14188 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14189 if any, and using the external references indicated
14190 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14191 @ifclear vms
14192 There may zero, one or more spaces between @option{-P} and @var{project}.
14193 @end ifclear
14194
14195 @noindent
14196 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14197
14198 @noindent
14199 Since the Project Manager parses the project file only after all the switches
14200 on the command line are checked, the order of the switches
14201 @option{^-P^/PROJECT_FILE^},
14202 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14203 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14204
14205 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14206 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14207 Indicates that external variable @var{name} has the value @var{value}.
14208 The Project Manager will use this value for occurrences of
14209 @code{external(name)} when parsing the project file.
14210
14211 @ifclear vms
14212 @noindent
14213 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14214 put between quotes.
14215 @smallexample
14216   -XOS=NT
14217   -X"user=John Doe"
14218 @end smallexample
14219 @end ifclear
14220
14221 @noindent
14222 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14223 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14224 @var{name}, only the last one is used.
14225
14226 @noindent
14227 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14228 takes precedence over the value of the same name in the environment.
14229
14230 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14231 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14232 Indicates the verbosity of the parsing of GNAT project files.
14233
14234 @ifclear vms
14235 @option{-vP0} means Default;
14236 @option{-vP1} means Medium;
14237 @option{-vP2} means High.
14238 @end ifclear
14239
14240 @ifset vms
14241 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14242 HIGH.
14243 @end ifset
14244
14245 @noindent
14246 The default is ^Default^DEFAULT^: no output for syntactically correct
14247 project files.
14248 @noindent
14249 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14250 only the last one is used.
14251
14252 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14253 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14254 Add directory <dir> at the beginning of the project search path, in order,
14255 after the current working directory.
14256
14257 @ifclear vms
14258 @item -eL
14259 @cindex @option{-eL} (any project-aware tool)
14260 Follow all symbolic links when processing project files.
14261 @end ifclear
14262
14263 @item ^--subdirs^/SUBDIRS^=<subdir>
14264 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14265 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14266 directories (except the source directories) are the subdirectories <subdir>
14267 of the directories specified in the project files. This applies in particular
14268 to object directories, library directories and exec directories. If the
14269 subdirectories do not exist, they are created automatically.
14270
14271 @end table
14272
14273 @c **********************************
14274 @c * Tools Supporting Project Files *
14275 @c **********************************
14276
14277 @node  Tools Supporting Project Files
14278 @section Tools Supporting Project Files
14279
14280 @menu
14281 * gnatmake and Project Files::
14282 * The GNAT Driver and Project Files::
14283 @end menu
14284
14285 @node gnatmake and Project Files
14286 @subsection gnatmake and Project Files
14287
14288 @noindent
14289 This section covers several topics related to @command{gnatmake} and
14290 project files: defining ^switches^switches^ for @command{gnatmake}
14291 and for the tools that it invokes; specifying configuration pragmas;
14292 the use of the @code{Main} attribute; building and rebuilding library project
14293 files.
14294
14295 @menu
14296 * ^Switches^Switches^ and Project Files::
14297 * Specifying Configuration Pragmas::
14298 * Project Files and Main Subprograms::
14299 * Library Project Files::
14300 @end menu
14301
14302 @node ^Switches^Switches^ and Project Files
14303 @subsubsection ^Switches^Switches^ and Project Files
14304
14305 @ifset vms
14306 It is not currently possible to specify VMS style qualifiers in the project
14307 files; only Unix style ^switches^switches^ may be specified.
14308 @end ifset
14309
14310 @noindent
14311 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14312 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14313 attribute, a @code{^Switches^Switches^} attribute, or both;
14314 as their names imply, these ^switch^switch^-related
14315 attributes affect the ^switches^switches^ that are used for each of these GNAT
14316 components when
14317 @command{gnatmake} is invoked.  As will be explained below, these
14318 component-specific ^switches^switches^ precede
14319 the ^switches^switches^ provided on the @command{gnatmake} command line.
14320
14321 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14322 array indexed by language name (case insensitive) whose value is a string list.
14323 For example:
14324
14325 @smallexample @c projectfile
14326 @group
14327 package Compiler is
14328   for ^Default_Switches^Default_Switches^ ("Ada")
14329       use ("^-gnaty^-gnaty^",
14330            "^-v^-v^");
14331 end Compiler;
14332 @end group
14333 @end smallexample
14334
14335 @noindent
14336 The @code{^Switches^Switches^} attribute is also an associative array,
14337 indexed by a file name (which may or may not be case sensitive, depending
14338 on the operating system) whose value is a string list.  For example:
14339
14340 @smallexample @c projectfile
14341 @group
14342 package Builder is
14343    for ^Switches^Switches^ ("main1.adb")
14344        use ("^-O2^-O2^");
14345    for ^Switches^Switches^ ("main2.adb")
14346        use ("^-g^-g^");
14347 end Builder;
14348 @end group
14349 @end smallexample
14350
14351 @noindent
14352 For the @code{Builder} package, the file names must designate source files
14353 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14354 file names must designate @file{ALI} or source files for main subprograms.
14355 In each case just the file name without an explicit extension is acceptable.
14356
14357 For each tool used in a program build (@command{gnatmake}, the compiler, the
14358 binder, and the linker), the corresponding package @dfn{contributes} a set of
14359 ^switches^switches^ for each file on which the tool is invoked, based on the
14360 ^switch^switch^-related attributes defined in the package.
14361 In particular, the ^switches^switches^
14362 that each of these packages contributes for a given file @var{f} comprise:
14363
14364 @itemize @bullet
14365 @item
14366 the value of attribute @code{^Switches^Switches^ (@var{f})},
14367 if it is specified in the package for the given file,
14368 @item
14369 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14370 if it is specified in the package.
14371 @end itemize
14372
14373 @noindent
14374 If neither of these attributes is defined in the package, then the package does
14375 not contribute any ^switches^switches^ for the given file.
14376
14377 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14378 two sets, in the following order: those contributed for the file
14379 by the @code{Builder} package;
14380 and the switches passed on the command line.
14381
14382 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14383 the ^switches^switches^ passed to the tool comprise three sets,
14384 in the following order:
14385
14386 @enumerate
14387 @item
14388 the applicable ^switches^switches^ contributed for the file
14389 by the @code{Builder} package in the project file supplied on the command line;
14390
14391 @item
14392 those contributed for the file by the package (in the relevant project file --
14393 see below) corresponding to the tool; and
14394
14395 @item
14396 the applicable switches passed on the command line.
14397 @end enumerate
14398
14399 @noindent
14400 The term @emph{applicable ^switches^switches^} reflects the fact that
14401 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14402 tools, depending on the individual ^switch^switch^.
14403
14404 @command{gnatmake} may invoke the compiler on source files from different
14405 projects. The Project Manager will use the appropriate project file to
14406 determine the @code{Compiler} package for each source file being compiled.
14407 Likewise for the @code{Binder} and @code{Linker} packages.
14408
14409 As an example, consider the following package in a project file:
14410
14411 @smallexample @c projectfile
14412 @group
14413 project Proj1 is
14414    package Compiler is
14415       for ^Default_Switches^Default_Switches^ ("Ada")
14416           use ("^-g^-g^");
14417       for ^Switches^Switches^ ("a.adb")
14418           use ("^-O1^-O1^");
14419       for ^Switches^Switches^ ("b.adb")
14420           use ("^-O2^-O2^",
14421                "^-gnaty^-gnaty^");
14422    end Compiler;
14423 end Proj1;
14424 @end group
14425 @end smallexample
14426
14427 @noindent
14428 If @command{gnatmake} is invoked with this project file, and it needs to
14429 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14430 @file{a.adb} will be compiled with the ^switch^switch^
14431 @option{^-O1^-O1^},
14432 @file{b.adb} with ^switches^switches^
14433 @option{^-O2^-O2^}
14434 and @option{^-gnaty^-gnaty^},
14435 and @file{c.adb} with @option{^-g^-g^}.
14436
14437 The following example illustrates the ordering of the ^switches^switches^
14438 contributed by different packages:
14439
14440 @smallexample @c projectfile
14441 @group
14442 project Proj2 is
14443    package Builder is
14444       for ^Switches^Switches^ ("main.adb")
14445           use ("^-g^-g^",
14446                "^-O1^-)1^",
14447                "^-f^-f^");
14448    end Builder;
14449 @end group
14450
14451 @group
14452    package Compiler is
14453       for ^Switches^Switches^ ("main.adb")
14454           use ("^-O2^-O2^");
14455    end Compiler;
14456 end Proj2;
14457 @end group
14458 @end smallexample
14459
14460 @noindent
14461 If you issue the command:
14462
14463 @smallexample
14464     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14465 @end smallexample
14466
14467 @noindent
14468 then the compiler will be invoked on @file{main.adb} with the following
14469 sequence of ^switches^switches^
14470
14471 @smallexample
14472    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14473 @end smallexample
14474
14475 with the last @option{^-O^-O^}
14476 ^switch^switch^ having precedence over the earlier ones;
14477 several other ^switches^switches^
14478 (such as @option{^-c^-c^}) are added implicitly.
14479
14480 The ^switches^switches^
14481 @option{^-g^-g^}
14482 and @option{^-O1^-O1^} are contributed by package
14483 @code{Builder},  @option{^-O2^-O2^} is contributed
14484 by the package @code{Compiler}
14485 and @option{^-O0^-O0^} comes from the command line.
14486
14487 The @option{^-g^-g^}
14488 ^switch^switch^ will also be passed in the invocation of
14489 @command{Gnatlink.}
14490
14491 A final example illustrates switch contributions from packages in different
14492 project files:
14493
14494 @smallexample @c projectfile
14495 @group
14496 project Proj3 is
14497    for Source_Files use ("pack.ads", "pack.adb");
14498    package Compiler is
14499       for ^Default_Switches^Default_Switches^ ("Ada")
14500           use ("^-gnata^-gnata^");
14501    end Compiler;
14502 end Proj3;
14503 @end group
14504
14505 @group
14506 with "Proj3";
14507 project Proj4 is
14508    for Source_Files use ("foo_main.adb", "bar_main.adb");
14509    package Builder is
14510       for ^Switches^Switches^ ("foo_main.adb")
14511           use ("^-s^-s^",
14512                "^-g^-g^");
14513    end Builder;
14514 end Proj4;
14515 @end group
14516
14517 @group
14518 -- Ada source file:
14519 with Pack;
14520 procedure Foo_Main is
14521    @dots{}
14522 end Foo_Main;
14523 @end group
14524 @end smallexample
14525
14526 If the command is
14527 @smallexample
14528 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14529 @end smallexample
14530
14531 @noindent
14532 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14533 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14534 @option{^-gnato^-gnato^} (passed on the command line).
14535 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14536 are @option{^-g^-g^} from @code{Proj4.Builder},
14537 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14538 and @option{^-gnato^-gnato^} from the command line.
14539
14540 @noindent
14541 When using @command{gnatmake} with project files, some ^switches^switches^ or
14542 arguments may be expressed as relative paths. As the working directory where
14543 compilation occurs may change, these relative paths are converted to absolute
14544 paths. For the ^switches^switches^ found in a project file, the relative paths
14545 are relative to the project file directory, for the switches on the command
14546 line, they are relative to the directory where @command{gnatmake} is invoked.
14547 The ^switches^switches^ for which this occurs are:
14548 ^-I^-I^,
14549 ^-A^-A^,
14550 ^-L^-L^,
14551 ^-aO^-aO^,
14552 ^-aL^-aL^,
14553 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14554 ^switch^switch^
14555 ^-o^-o^, object files specified in package @code{Linker} or after
14556 -largs on the command line). The exception to this rule is the ^switch^switch^
14557 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14558
14559 @node Specifying Configuration Pragmas
14560 @subsubsection Specifying Configuration Pragmas
14561
14562 When using @command{gnatmake} with project files, if there exists a file
14563 @file{gnat.adc} that contains configuration pragmas, this file will be
14564 ignored.
14565
14566 Configuration pragmas can be defined by means of the following attributes in
14567 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14568 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14569
14570 Both these attributes are single string attributes. Their values is the path
14571 name of a file containing configuration pragmas. If a path name is relative,
14572 then it is relative to the project directory of the project file where the
14573 attribute is defined.
14574
14575 When compiling a source, the configuration pragmas used are, in order,
14576 those listed in the file designated by attribute
14577 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14578 project file, if it is specified, and those listed in the file designated by
14579 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14580 the project file of the source, if it exists.
14581
14582 @node Project Files and Main Subprograms
14583 @subsubsection Project Files and Main Subprograms
14584
14585 @noindent
14586 When using a project file, you can invoke @command{gnatmake}
14587 with one or several main subprograms, by specifying their source files on the
14588 command line.
14589
14590 @smallexample
14591     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14592 @end smallexample
14593
14594 @noindent
14595 Each of these needs to be a source file of the same project, except
14596 when the switch ^-u^/UNIQUE^ is used.
14597
14598 @noindent
14599 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14600 same project, one of the project in the tree rooted at the project specified
14601 on the command line. The package @code{Builder} of this common project, the
14602 "main project" is the one that is considered by @command{gnatmake}.
14603
14604 @noindent
14605 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14606 imported directly or indirectly by the project specified on the command line.
14607 Note that if such a source file is not part of the project specified on the
14608 command line, the ^switches^switches^ found in package @code{Builder} of the
14609 project specified on the command line, if any, that are transmitted
14610 to the compiler will still be used, not those found in the project file of
14611 the source file.
14612
14613 @noindent
14614 When using a project file, you can also invoke @command{gnatmake} without
14615 explicitly specifying any main, and the effect depends on whether you have
14616 defined the @code{Main} attribute.  This attribute has a string list value,
14617 where each element in the list is the name of a source file (the file
14618 extension is optional) that contains a unit that can be a main subprogram.
14619
14620 If the @code{Main} attribute is defined in a project file as a non-empty
14621 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14622 line, then invoking @command{gnatmake} with this project file but without any
14623 main on the command line is equivalent to invoking @command{gnatmake} with all
14624 the file names in the @code{Main} attribute on the command line.
14625
14626 Example:
14627 @smallexample @c projectfile
14628 @group
14629    project Prj is
14630       for Main use ("main1", "main2", "main3");
14631    end Prj;
14632 @end group
14633 @end smallexample
14634
14635 @noindent
14636 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14637 is equivalent to
14638 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14639
14640 When the project attribute @code{Main} is not specified, or is specified
14641 as an empty string list, or when the switch @option{-u} is used on the command
14642 line, then invoking @command{gnatmake} with no main on the command line will
14643 result in all immediate sources of the project file being checked, and
14644 potentially recompiled. Depending on the presence of the switch @option{-u},
14645 sources from other project files on which the immediate sources of the main
14646 project file depend are also checked and potentially recompiled. In other
14647 words, the @option{-u} switch is applied to all of the immediate sources of the
14648 main project file.
14649
14650 When no main is specified on the command line and attribute @code{Main} exists
14651 and includes several mains, or when several mains are specified on the
14652 command line, the default ^switches^switches^ in package @code{Builder} will
14653 be used for all mains, even if there are specific ^switches^switches^
14654 specified for one or several mains.
14655
14656 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14657 the specific ^switches^switches^ for each main, if they are specified.
14658
14659 @node Library Project Files
14660 @subsubsection Library Project Files
14661
14662 @noindent
14663 When @command{gnatmake} is invoked with a main project file that is a library
14664 project file, it is not allowed to specify one or more mains on the command
14665 line.
14666
14667 @noindent
14668 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14669 ^-l^/ACTION=LINK^ have special meanings.
14670
14671 @itemize @bullet
14672 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14673 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14674 library.
14675
14676 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14677 to @command{gnatmake} that the binder generated file should be compiled
14678 (in the case of a stand-alone library) and that the library should be built.
14679
14680 @end itemize
14681
14682 @node The GNAT Driver and Project Files
14683 @subsection The GNAT Driver and Project Files
14684
14685 @noindent
14686 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14687 can benefit from project files:
14688 @command{^gnatbind^gnatbind^},
14689 @command{^gnatcheck^gnatcheck^}),
14690 @command{^gnatclean^gnatclean^}),
14691 @command{^gnatelim^gnatelim^},
14692 @command{^gnatfind^gnatfind^},
14693 @command{^gnatlink^gnatlink^},
14694 @command{^gnatls^gnatls^},
14695 @command{^gnatmetric^gnatmetric^},
14696 @command{^gnatpp^gnatpp^},
14697 @command{^gnatstub^gnatstub^},
14698 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14699 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14700 They must be invoked through the @command{gnat} driver.
14701
14702 The @command{gnat} driver is a wrapper that accepts a number of commands and
14703 calls the corresponding tool. It was designed initially for VMS platforms (to
14704 convert VMS qualifiers to Unix-style switches), but it is now available on all
14705 GNAT platforms.
14706
14707 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14708 (case insensitive):
14709
14710 @itemize @bullet
14711 @item
14712 BIND to invoke @command{^gnatbind^gnatbind^}
14713 @item
14714 CHOP to invoke @command{^gnatchop^gnatchop^}
14715 @item
14716 CLEAN to invoke @command{^gnatclean^gnatclean^}
14717 @item
14718 COMP or COMPILE to invoke the compiler
14719 @item
14720 ELIM to invoke @command{^gnatelim^gnatelim^}
14721 @item
14722 FIND to invoke @command{^gnatfind^gnatfind^}
14723 @item
14724 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14725 @item
14726 LINK to invoke @command{^gnatlink^gnatlink^}
14727 @item
14728 LS or LIST to invoke @command{^gnatls^gnatls^}
14729 @item
14730 MAKE to invoke @command{^gnatmake^gnatmake^}
14731 @item
14732 NAME to invoke @command{^gnatname^gnatname^}
14733 @item
14734 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14735 @item
14736 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14737 @item
14738 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14739 @item
14740 STUB to invoke @command{^gnatstub^gnatstub^}
14741 @item
14742 XREF to invoke @command{^gnatxref^gnatxref^}
14743 @end itemize
14744
14745 @noindent
14746 (note that the compiler is invoked using the command
14747 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14748
14749 @noindent
14750 On non-VMS platforms, between @command{gnat} and the command, two
14751 special switches may be used:
14752
14753 @itemize @bullet
14754 @item
14755 @command{-v} to display the invocation of the tool.
14756 @item
14757 @command{-dn} to prevent the @command{gnat} driver from removing
14758 the temporary files it has created. These temporary files are
14759 configuration files and temporary file list files.
14760 @end itemize
14761
14762 @noindent
14763 The command may be followed by switches and arguments for the invoked
14764 tool.
14765
14766 @smallexample
14767   gnat bind -C main.ali
14768   gnat ls -a main
14769   gnat chop foo.txt
14770 @end smallexample
14771
14772 @noindent
14773 Switches may also be put in text files, one switch per line, and the text
14774 files may be specified with their path name preceded by '@@'.
14775
14776 @smallexample
14777    gnat bind @@args.txt main.ali
14778 @end smallexample
14779
14780 @noindent
14781 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14782 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14783 (@option{^-P^/PROJECT_FILE^},
14784 @option{^-X^/EXTERNAL_REFERENCE^} and
14785 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14786 the switches of the invoking tool.
14787
14788 @noindent
14789 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14790 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14791 the immediate sources of the specified project file.
14792
14793 @noindent
14794 When GNAT METRIC is used with a project file, but with no source
14795 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14796 with all the immediate sources of the specified project file and with
14797 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14798 of the project.
14799
14800 @noindent
14801 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14802 a project file, no source is specified on the command line and
14803 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14804 the underlying tool (^gnatpp^gnatpp^ or
14805 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14806 not only for the immediate sources of the main project.
14807 @ifclear vms
14808 (-U stands for Universal or Union of the project files of the project tree)
14809 @end ifclear
14810
14811 @noindent
14812 For each of the following commands, there is optionally a corresponding
14813 package in the main project.
14814
14815 @itemize @bullet
14816 @item
14817 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14818
14819 @item
14820 package @code{Check} for command CHECK (invoking
14821 @code{^gnatcheck^gnatcheck^})
14822
14823 @item
14824 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14825
14826 @item
14827 package @code{Cross_Reference} for command XREF (invoking
14828 @code{^gnatxref^gnatxref^})
14829
14830 @item
14831 package @code{Eliminate} for command ELIM (invoking
14832 @code{^gnatelim^gnatelim^})
14833
14834 @item
14835 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14836
14837 @item
14838 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14839
14840 @item
14841 package @code{Gnatstub} for command STUB
14842 (invoking @code{^gnatstub^gnatstub^})
14843
14844 @item
14845 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14846
14847 @item
14848 package @code{Metrics} for command METRIC
14849 (invoking @code{^gnatmetric^gnatmetric^})
14850
14851 @item
14852 package @code{Pretty_Printer} for command PP or PRETTY
14853 (invoking @code{^gnatpp^gnatpp^})
14854
14855 @end itemize
14856
14857 @noindent
14858 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14859 a simple variable with a string list value. It contains ^switches^switches^
14860 for the invocation of @code{^gnatls^gnatls^}.
14861
14862 @smallexample @c projectfile
14863 @group
14864 project Proj1 is
14865    package gnatls is
14866       for ^Switches^Switches^
14867           use ("^-a^-a^",
14868                "^-v^-v^");
14869    end gnatls;
14870 end Proj1;
14871 @end group
14872 @end smallexample
14873
14874 @noindent
14875 All other packages have two attribute @code{^Switches^Switches^} and
14876 @code{^Default_Switches^Default_Switches^}.
14877
14878 @noindent
14879 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14880 source file name, that has a string list value: the ^switches^switches^ to be
14881 used when the tool corresponding to the package is invoked for the specific
14882 source file.
14883
14884 @noindent
14885 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14886 indexed by  the programming language that has a string list value.
14887 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14888 ^switches^switches^ for the invocation of the tool corresponding
14889 to the package, except if a specific @code{^Switches^Switches^} attribute
14890 is specified for the source file.
14891
14892 @smallexample @c projectfile
14893 @group
14894 project Proj is
14895
14896    for Source_Dirs use ("./**");
14897
14898    package gnatls is
14899       for ^Switches^Switches^ use
14900           ("^-a^-a^",
14901            "^-v^-v^");
14902    end gnatls;
14903 @end group
14904 @group
14905
14906    package Compiler is
14907       for ^Default_Switches^Default_Switches^ ("Ada")
14908           use ("^-gnatv^-gnatv^",
14909                "^-gnatwa^-gnatwa^");
14910    end Binder;
14911 @end group
14912 @group
14913
14914    package Binder is
14915       for ^Default_Switches^Default_Switches^ ("Ada")
14916           use ("^-C^-C^",
14917                "^-e^-e^");
14918    end Binder;
14919 @end group
14920 @group
14921
14922    package Linker is
14923       for ^Default_Switches^Default_Switches^ ("Ada")
14924           use ("^-C^-C^");
14925       for ^Switches^Switches^ ("main.adb")
14926           use ("^-C^-C^",
14927                "^-v^-v^",
14928                "^-v^-v^");
14929    end Linker;
14930 @end group
14931 @group
14932
14933    package Finder is
14934       for ^Default_Switches^Default_Switches^ ("Ada")
14935            use ("^-a^-a^",
14936                 "^-f^-f^");
14937    end Finder;
14938 @end group
14939 @group
14940
14941    package Cross_Reference is
14942       for ^Default_Switches^Default_Switches^ ("Ada")
14943           use ("^-a^-a^",
14944                "^-f^-f^",
14945                "^-d^-d^",
14946                "^-u^-u^");
14947    end Cross_Reference;
14948 end Proj;
14949 @end group
14950 @end smallexample
14951
14952 @noindent
14953 With the above project file, commands such as
14954
14955 @smallexample
14956    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14957    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14958    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14959    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14960    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14961 @end smallexample
14962
14963 @noindent
14964 will set up the environment properly and invoke the tool with the switches
14965 found in the package corresponding to the tool:
14966 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14967 except @code{^Switches^Switches^ ("main.adb")}
14968 for @code{^gnatlink^gnatlink^}.
14969 It is also possible to invoke some of the tools,
14970 @code{^gnatcheck^gnatcheck^}),
14971 @code{^gnatmetric^gnatmetric^}),
14972 and @code{^gnatpp^gnatpp^})
14973 on a set of project units thanks to the combination of the switches
14974 @option{-P}, @option{-U} and possibly the main unit when one is interested
14975 in its closure. For instance,
14976 @smallexample
14977 gnat metric -Pproj
14978 @end smallexample
14979 will compute the metrics for all the immediate units of project
14980 @code{proj}.
14981 @smallexample
14982 gnat metric -Pproj -U
14983 @end smallexample
14984 will compute the metrics for all the units of the closure of projects
14985 rooted at @code{proj}.
14986 @smallexample
14987 gnat metric -Pproj -U main_unit
14988 @end smallexample
14989 will compute the metrics for the closure of units rooted at
14990 @code{main_unit}. This last possibility relies implicitly
14991 on @command{gnatbind}'s option @option{-R}.
14992
14993 @c **********************
14994 @node An Extended Example
14995 @section An Extended Example
14996
14997 @noindent
14998 Suppose that we have two programs, @var{prog1} and @var{prog2},
14999 whose sources are in corresponding directories. We would like
15000 to build them with a single @command{gnatmake} command, and we want to place
15001 their object files into @file{build} subdirectories of the source directories.
15002 Furthermore, we want to have to have two separate subdirectories
15003 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15004 the object files compiled with different set of compilation flags.
15005
15006 In other words, we have the following structure:
15007
15008 @smallexample
15009 @group
15010    main
15011      |- prog1
15012      |    |- build
15013      |         | debug
15014      |         | release
15015      |- prog2
15016           |- build
15017                | debug
15018                | release
15019 @end group
15020 @end smallexample
15021
15022 @noindent
15023 Here are the project files that we must place in a directory @file{main}
15024 to maintain this structure:
15025
15026 @enumerate
15027
15028 @item We create a @code{Common} project with a package @code{Compiler} that
15029 specifies the compilation ^switches^switches^:
15030
15031 @smallexample
15032 File "common.gpr":
15033 @group
15034 @b{project} Common @b{is}
15035
15036    @b{for} Source_Dirs @b{use} (); -- No source files
15037 @end group
15038
15039 @group
15040    @b{type} Build_Type @b{is} ("release", "debug");
15041    Build : Build_Type := External ("BUILD", "debug");
15042 @end group
15043 @group
15044    @b{package} Compiler @b{is}
15045       @b{case} Build @b{is}
15046          @b{when} "release" =>
15047            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15048                    @b{use} ("^-O2^-O2^");
15049          @b{when} "debug"   =>
15050            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15051                    @b{use} ("^-g^-g^");
15052       @b{end case};
15053    @b{end} Compiler;
15054
15055 @b{end} Common;
15056 @end group
15057 @end smallexample
15058
15059 @item We create separate projects for the two programs:
15060
15061 @smallexample
15062 @group
15063 File "prog1.gpr":
15064
15065 @b{with} "common";
15066 @b{project} Prog1 @b{is}
15067
15068     @b{for} Source_Dirs @b{use} ("prog1");
15069     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15070
15071     @b{package} Compiler @b{renames} Common.Compiler;
15072
15073 @b{end} Prog1;
15074 @end group
15075 @end smallexample
15076
15077 @smallexample
15078 @group
15079 File "prog2.gpr":
15080
15081 @b{with} "common";
15082 @b{project} Prog2 @b{is}
15083
15084     @b{for} Source_Dirs @b{use} ("prog2");
15085     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15086
15087     @b{package} Compiler @b{renames} Common.Compiler;
15088
15089 @end group
15090 @b{end} Prog2;
15091 @end smallexample
15092
15093 @item We create a wrapping project @code{Main}:
15094
15095 @smallexample
15096 @group
15097 File "main.gpr":
15098
15099 @b{with} "common";
15100 @b{with} "prog1";
15101 @b{with} "prog2";
15102 @b{project} Main @b{is}
15103
15104    @b{package} Compiler @b{renames} Common.Compiler;
15105
15106 @b{end} Main;
15107 @end group
15108 @end smallexample
15109
15110 @item Finally we need to create a dummy procedure that @code{with}s (either
15111 explicitly or implicitly) all the sources of our two programs.
15112
15113 @end enumerate
15114
15115 @noindent
15116 Now we can build the programs using the command
15117
15118 @smallexample
15119    gnatmake ^-P^/PROJECT_FILE=^main dummy
15120 @end smallexample
15121
15122 @noindent
15123 for the Debug mode, or
15124
15125 @ifclear vms
15126 @smallexample
15127    gnatmake -Pmain -XBUILD=release
15128 @end smallexample
15129 @end ifclear
15130
15131 @ifset vms
15132 @smallexample
15133    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15134 @end smallexample
15135 @end ifset
15136
15137 @noindent
15138 for the Release mode.
15139
15140 @c ********************************
15141 @c * Project File Complete Syntax *
15142 @c ********************************
15143
15144 @node Project File Complete Syntax
15145 @section Project File Complete Syntax
15146
15147 @smallexample
15148 project ::=
15149   context_clause project_declaration
15150
15151 context_clause ::=
15152   @{with_clause@}
15153
15154 with_clause ::=
15155   @b{with} path_name @{ , path_name @} ;
15156
15157 path_name ::=
15158    string_literal
15159
15160 project_declaration ::=
15161   simple_project_declaration | project_extension
15162
15163 simple_project_declaration ::=
15164   @b{project} <project_>simple_name @b{is}
15165     @{declarative_item@}
15166   @b{end} <project_>simple_name;
15167
15168 project_extension ::=
15169   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15170     @{declarative_item@}
15171   @b{end} <project_>simple_name;
15172
15173 declarative_item ::=
15174   package_declaration |
15175   typed_string_declaration |
15176   other_declarative_item
15177
15178 package_declaration ::=
15179   package_spec | package_renaming
15180
15181 package_spec ::=
15182   @b{package} package_identifier @b{is}
15183     @{simple_declarative_item@}
15184   @b{end} package_identifier ;
15185
15186 package_identifier ::=
15187   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15188   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15189   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15190
15191 package_renaming ::==
15192   @b{package} package_identifier @b{renames}
15193        <project_>simple_name.package_identifier ;
15194
15195 typed_string_declaration ::=
15196   @b{type} <typed_string_>_simple_name @b{is}
15197    ( string_literal @{, string_literal@} );
15198
15199 other_declarative_item ::=
15200   attribute_declaration |
15201   typed_variable_declaration |
15202   variable_declaration |
15203   case_construction
15204
15205 attribute_declaration ::=
15206   full_associative_array_declaration |
15207   @b{for} attribute_designator @b{use} expression ;
15208
15209 full_associative_array_declaration ::=
15210   @b{for} <associative_array_attribute_>simple_name @b{use}
15211   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15212
15213 attribute_designator ::=
15214   <simple_attribute_>simple_name |
15215   <associative_array_attribute_>simple_name ( string_literal )
15216
15217 typed_variable_declaration ::=
15218   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15219
15220 variable_declaration ::=
15221   <variable_>simple_name := expression;
15222
15223 expression ::=
15224   term @{& term@}
15225
15226 term ::=
15227   literal_string |
15228   string_list |
15229   <variable_>name |
15230   external_value |
15231   attribute_reference
15232
15233 string_literal ::=
15234   (same as Ada)
15235
15236 string_list ::=
15237   ( <string_>expression @{ , <string_>expression @} )
15238
15239 external_value ::=
15240   @b{external} ( string_literal [, string_literal] )
15241
15242 attribute_reference ::=
15243   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15244
15245 attribute_prefix ::=
15246   @b{project} |
15247   <project_>simple_name | package_identifier |
15248   <project_>simple_name . package_identifier
15249
15250 case_construction ::=
15251   @b{case} <typed_variable_>name @b{is}
15252     @{case_item@}
15253   @b{end case} ;
15254
15255 case_item ::=
15256   @b{when} discrete_choice_list =>
15257       @{case_construction | attribute_declaration@}
15258
15259 discrete_choice_list ::=
15260   string_literal @{| string_literal@} |
15261   @b{others}
15262
15263 name ::=
15264   simple_name @{. simple_name@}
15265
15266 simple_name ::=
15267   identifier (same as Ada)
15268
15269 @end smallexample
15270
15271 @node The Cross-Referencing Tools gnatxref and gnatfind
15272 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15273 @findex gnatxref
15274 @findex gnatfind
15275
15276 @noindent
15277 The compiler generates cross-referencing information (unless
15278 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15279 This information indicates where in the source each entity is declared and
15280 referenced. Note that entities in package Standard are not included, but
15281 entities in all other predefined units are included in the output.
15282
15283 Before using any of these two tools, you need to compile successfully your
15284 application, so that GNAT gets a chance to generate the cross-referencing
15285 information.
15286
15287 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15288 information to provide the user with the capability to easily locate the
15289 declaration and references to an entity. These tools are quite similar,
15290 the difference being that @code{gnatfind} is intended for locating
15291 definitions and/or references to a specified entity or entities, whereas
15292 @code{gnatxref} is oriented to generating a full report of all
15293 cross-references.
15294
15295 To use these tools, you must not compile your application using the
15296 @option{-gnatx} switch on the @command{gnatmake} command line
15297 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15298 information will not be generated.
15299
15300 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15301 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15302
15303 @menu
15304 * gnatxref Switches::
15305 * gnatfind Switches::
15306 * Project Files for gnatxref and gnatfind::
15307 * Regular Expressions in gnatfind and gnatxref::
15308 * Examples of gnatxref Usage::
15309 * Examples of gnatfind Usage::
15310 @end menu
15311
15312 @node gnatxref Switches
15313 @section @code{gnatxref} Switches
15314
15315 @noindent
15316 The command invocation for @code{gnatxref} is:
15317 @smallexample
15318 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15319 @end smallexample
15320
15321 @noindent
15322 where
15323
15324 @table @var
15325 @item sourcefile1
15326 @itemx sourcefile2
15327 identifies the source files for which a report is to be generated. The
15328 ``with''ed units will be processed too. You must provide at least one file.
15329
15330 These file names are considered to be regular expressions, so for instance
15331 specifying @file{source*.adb} is the same as giving every file in the current
15332 directory whose name starts with @file{source} and whose extension is
15333 @file{adb}.
15334
15335 You shouldn't specify any directory name, just base names. @command{gnatxref}
15336 and @command{gnatfind} will be able to locate these files by themselves using
15337 the source path. If you specify directories, no result is produced.
15338
15339 @end table
15340
15341 @noindent
15342 The switches can be:
15343 @table @option
15344 @c !sort!
15345 @item --version
15346 @cindex @option{--version} @command{gnatxref}
15347 Display Copyright and version, then exit disregarding all other options.
15348
15349 @item --help
15350 @cindex @option{--help} @command{gnatxref}
15351 If @option{--version} was not used, display usage, then exit disregarding
15352 all other options.
15353
15354 @item ^-a^/ALL_FILES^
15355 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15356 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15357 the read-only files found in the library search path. Otherwise, these files
15358 will be ignored. This option can be used to protect Gnat sources or your own
15359 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15360 much faster, and their output much smaller. Read-only here refers to access
15361 or permissions status in the file system for the current user.
15362
15363 @item -aIDIR
15364 @cindex @option{-aIDIR} (@command{gnatxref})
15365 When looking for source files also look in directory DIR. The order in which
15366 source file search is undertaken is the same as for @command{gnatmake}.
15367
15368 @item -aODIR
15369 @cindex @option{-aODIR} (@command{gnatxref})
15370 When searching for library and object files, look in directory
15371 DIR. The order in which library files are searched is the same as for
15372 @command{gnatmake}.
15373
15374 @item -nostdinc
15375 @cindex @option{-nostdinc} (@command{gnatxref})
15376 Do not look for sources in the system default directory.
15377
15378 @item -nostdlib
15379 @cindex @option{-nostdlib} (@command{gnatxref})
15380 Do not look for library files in the system default directory.
15381
15382 @item --RTS=@var{rts-path}
15383 @cindex @option{--RTS} (@command{gnatxref})
15384 Specifies the default location of the runtime library. Same meaning as the
15385 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15386
15387 @item ^-d^/DERIVED_TYPES^
15388 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15389 If this switch is set @code{gnatxref} will output the parent type
15390 reference for each matching derived types.
15391
15392 @item ^-f^/FULL_PATHNAME^
15393 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15394 If this switch is set, the output file names will be preceded by their
15395 directory (if the file was found in the search path). If this switch is
15396 not set, the directory will not be printed.
15397
15398 @item ^-g^/IGNORE_LOCALS^
15399 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15400 If this switch is set, information is output only for library-level
15401 entities, ignoring local entities. The use of this switch may accelerate
15402 @code{gnatfind} and @code{gnatxref}.
15403
15404 @item -IDIR
15405 @cindex @option{-IDIR} (@command{gnatxref})
15406 Equivalent to @samp{-aODIR -aIDIR}.
15407
15408 @item -pFILE
15409 @cindex @option{-pFILE} (@command{gnatxref})
15410 Specify a project file to use @xref{Project Files}.
15411 If you need to use the @file{.gpr}
15412 project files, you should use gnatxref through the GNAT driver
15413 (@command{gnat xref -Pproject}).
15414
15415 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15416 project file in the current directory.
15417
15418 If a project file is either specified or found by the tools, then the content
15419 of the source directory and object directory lines are added as if they
15420 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15421 and @samp{^-aO^OBJECT_SEARCH^}.
15422 @item ^-u^/UNUSED^
15423 Output only unused symbols. This may be really useful if you give your
15424 main compilation unit on the command line, as @code{gnatxref} will then
15425 display every unused entity and 'with'ed package.
15426
15427 @ifclear vms
15428 @item -v
15429 Instead of producing the default output, @code{gnatxref} will generate a
15430 @file{tags} file that can be used by vi. For examples how to use this
15431 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15432 to the standard output, thus you will have to redirect it to a file.
15433 @end ifclear
15434
15435 @end table
15436
15437 @noindent
15438 All these switches may be in any order on the command line, and may even
15439 appear after the file names. They need not be separated by spaces, thus
15440 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15441 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15442
15443 @node gnatfind Switches
15444 @section @code{gnatfind} Switches
15445
15446 @noindent
15447 The command line for @code{gnatfind} is:
15448
15449 @smallexample
15450 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15451       @r{[}@var{file1} @var{file2} @dots{}]
15452 @end smallexample
15453
15454 @noindent
15455 where
15456
15457 @table @var
15458 @item pattern
15459 An entity will be output only if it matches the regular expression found
15460 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15461
15462 Omitting the pattern is equivalent to specifying @samp{*}, which
15463 will match any entity. Note that if you do not provide a pattern, you
15464 have to provide both a sourcefile and a line.
15465
15466 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15467 for matching purposes. At the current time there is no support for
15468 8-bit codes other than Latin-1, or for wide characters in identifiers.
15469
15470 @item sourcefile
15471 @code{gnatfind} will look for references, bodies or declarations
15472 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15473 and column @var{column}. See @ref{Examples of gnatfind Usage}
15474 for syntax examples.
15475
15476 @item line
15477 is a decimal integer identifying the line number containing
15478 the reference to the entity (or entities) to be located.
15479
15480 @item column
15481 is a decimal integer identifying the exact location on the
15482 line of the first character of the identifier for the
15483 entity reference. Columns are numbered from 1.
15484
15485 @item file1 file2 @dots{}
15486 The search will be restricted to these source files. If none are given, then
15487 the search will be done for every library file in the search path.
15488 These file must appear only after the pattern or sourcefile.
15489
15490 These file names are considered to be regular expressions, so for instance
15491 specifying @file{source*.adb} is the same as giving every file in the current
15492 directory whose name starts with @file{source} and whose extension is
15493 @file{adb}.
15494
15495 The location of the spec of the entity will always be displayed, even if it
15496 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15497 occurrences of the entity in the separate units of the ones given on the
15498 command line will also be displayed.
15499
15500 Note that if you specify at least one file in this part, @code{gnatfind} may
15501 sometimes not be able to find the body of the subprograms.
15502
15503 @end table
15504
15505 @noindent
15506 At least one of 'sourcefile' or 'pattern' has to be present on
15507 the command line.
15508
15509 The following switches are available:
15510 @table @option
15511 @c !sort!
15512
15513 @cindex @option{--version} @command{gnatfind}
15514 Display Copyright and version, then exit disregarding all other options.
15515
15516 @item --help
15517 @cindex @option{--help} @command{gnatfind}
15518 If @option{--version} was not used, display usage, then exit disregarding
15519 all other options.
15520
15521 @item ^-a^/ALL_FILES^
15522 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15523 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15524 the read-only files found in the library search path. Otherwise, these files
15525 will be ignored. This option can be used to protect Gnat sources or your own
15526 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15527 much faster, and their output much smaller. Read-only here refers to access
15528 or permission status in the file system for the current user.
15529
15530 @item -aIDIR
15531 @cindex @option{-aIDIR} (@command{gnatfind})
15532 When looking for source files also look in directory DIR. The order in which
15533 source file search is undertaken is the same as for @command{gnatmake}.
15534
15535 @item -aODIR
15536 @cindex @option{-aODIR} (@command{gnatfind})
15537 When searching for library and object files, look in directory
15538 DIR. The order in which library files are searched is the same as for
15539 @command{gnatmake}.
15540
15541 @item -nostdinc
15542 @cindex @option{-nostdinc} (@command{gnatfind})
15543 Do not look for sources in the system default directory.
15544
15545 @item -nostdlib
15546 @cindex @option{-nostdlib} (@command{gnatfind})
15547 Do not look for library files in the system default directory.
15548
15549 @item --RTS=@var{rts-path}
15550 @cindex @option{--RTS} (@command{gnatfind})
15551 Specifies the default location of the runtime library. Same meaning as the
15552 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15553
15554 @item ^-d^/DERIVED_TYPE_INFORMATION^
15555 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15556 If this switch is set, then @code{gnatfind} will output the parent type
15557 reference for each matching derived types.
15558
15559 @item ^-e^/EXPRESSIONS^
15560 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15561 By default, @code{gnatfind} accept the simple regular expression set for
15562 @samp{pattern}. If this switch is set, then the pattern will be
15563 considered as full Unix-style regular expression.
15564
15565 @item ^-f^/FULL_PATHNAME^
15566 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15567 If this switch is set, the output file names will be preceded by their
15568 directory (if the file was found in the search path). If this switch is
15569 not set, the directory will not be printed.
15570
15571 @item ^-g^/IGNORE_LOCALS^
15572 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15573 If this switch is set, information is output only for library-level
15574 entities, ignoring local entities. The use of this switch may accelerate
15575 @code{gnatfind} and @code{gnatxref}.
15576
15577 @item -IDIR
15578 @cindex @option{-IDIR} (@command{gnatfind})
15579 Equivalent to @samp{-aODIR -aIDIR}.
15580
15581 @item -pFILE
15582 @cindex @option{-pFILE} (@command{gnatfind})
15583 Specify a project file (@pxref{Project Files}) to use.
15584 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15585 project file in the current directory.
15586
15587 If a project file is either specified or found by the tools, then the content
15588 of the source directory and object directory lines are added as if they
15589 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15590 @samp{^-aO^/OBJECT_SEARCH^}.
15591
15592 @item ^-r^/REFERENCES^
15593 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15594 By default, @code{gnatfind} will output only the information about the
15595 declaration, body or type completion of the entities. If this switch is
15596 set, the @code{gnatfind} will locate every reference to the entities in
15597 the files specified on the command line (or in every file in the search
15598 path if no file is given on the command line).
15599
15600 @item ^-s^/PRINT_LINES^
15601 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15602 If this switch is set, then @code{gnatfind} will output the content
15603 of the Ada source file lines were the entity was found.
15604
15605 @item ^-t^/TYPE_HIERARCHY^
15606 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15607 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15608 the specified type. It act like -d option but recursively from parent
15609 type to parent type. When this switch is set it is not possible to
15610 specify more than one file.
15611
15612 @end table
15613
15614 @noindent
15615 All these switches may be in any order on the command line, and may even
15616 appear after the file names. They need not be separated by spaces, thus
15617 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15618 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15619
15620 As stated previously, gnatfind will search in every directory in the
15621 search path. You can force it to look only in the current directory if
15622 you specify @code{*} at the end of the command line.
15623
15624 @node Project Files for gnatxref and gnatfind
15625 @section Project Files for @command{gnatxref} and @command{gnatfind}
15626
15627 @noindent
15628 Project files allow a programmer to specify how to compile its
15629 application, where to find sources, etc.  These files are used
15630 @ifclear vms
15631 primarily by GPS, but they can also be used
15632 @end ifclear
15633 by the two tools
15634 @code{gnatxref} and @code{gnatfind}.
15635
15636 A project file name must end with @file{.gpr}. If a single one is
15637 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15638 extract the information from it. If multiple project files are found, none of
15639 them is read, and you have to use the @samp{-p} switch to specify the one
15640 you want to use.
15641
15642 The following lines can be included, even though most of them have default
15643 values which can be used in most cases.
15644 The lines can be entered in any order in the file.
15645 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15646 each line. If you have multiple instances, only the last one is taken into
15647 account.
15648
15649 @table @code
15650 @item src_dir=DIR
15651 [default: @code{"^./^[]^"}]
15652 specifies a directory where to look for source files. Multiple @code{src_dir}
15653 lines can be specified and they will be searched in the order they
15654 are specified.
15655
15656 @item obj_dir=DIR
15657 [default: @code{"^./^[]^"}]
15658 specifies a directory where to look for object and library files. Multiple
15659 @code{obj_dir} lines can be specified, and they will be searched in the order
15660 they are specified
15661
15662 @item comp_opt=SWITCHES
15663 [default: @code{""}]
15664 creates a variable which can be referred to subsequently by using
15665 the @code{$@{comp_opt@}} notation. This is intended to store the default
15666 switches given to @command{gnatmake} and @command{gcc}.
15667
15668 @item bind_opt=SWITCHES
15669 [default: @code{""}]
15670 creates a variable which can be referred to subsequently by using
15671 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15672 switches given to @command{gnatbind}.
15673
15674 @item link_opt=SWITCHES
15675 [default: @code{""}]
15676 creates a variable which can be referred to subsequently by using
15677 the @samp{$@{link_opt@}} notation. This is intended to store the default
15678 switches given to @command{gnatlink}.
15679
15680 @item main=EXECUTABLE
15681 [default: @code{""}]
15682 specifies the name of the executable for the application. This variable can
15683 be referred to in the following lines by using the @samp{$@{main@}} notation.
15684
15685 @ifset vms
15686 @item comp_cmd=COMMAND
15687 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15688 @end ifset
15689 @ifclear vms
15690 @item comp_cmd=COMMAND
15691 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15692 @end ifclear
15693 specifies the command used to compile a single file in the application.
15694
15695 @ifset vms
15696 @item make_cmd=COMMAND
15697 [default: @code{"GNAT MAKE $@{main@}
15698 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15699 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15700 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15701 @end ifset
15702 @ifclear vms
15703 @item make_cmd=COMMAND
15704 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15705 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15706 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15707 @end ifclear
15708 specifies the command used to recompile the whole application.
15709
15710 @item run_cmd=COMMAND
15711 [default: @code{"$@{main@}"}]
15712 specifies the command used to run the application.
15713
15714 @item debug_cmd=COMMAND
15715 [default: @code{"gdb $@{main@}"}]
15716 specifies the command used to debug the application
15717
15718 @end table
15719
15720 @noindent
15721 @command{gnatxref} and @command{gnatfind} only take into account the
15722 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15723
15724 @node Regular Expressions in gnatfind and gnatxref
15725 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15726
15727 @noindent
15728 As specified in the section about @command{gnatfind}, the pattern can be a
15729 regular expression. Actually, there are to set of regular expressions
15730 which are recognized by the program:
15731
15732 @table @code
15733 @item globbing patterns
15734 These are the most usual regular expression. They are the same that you
15735 generally used in a Unix shell command line, or in a DOS session.
15736
15737 Here is a more formal grammar:
15738 @smallexample
15739 @group
15740 @iftex
15741 @leftskip=.5cm
15742 @end iftex
15743 regexp ::= term
15744 term   ::= elmt            -- matches elmt
15745 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15746 term   ::= *               -- any string of 0 or more characters
15747 term   ::= ?               -- matches any character
15748 term   ::= [char @{char@}]   -- matches any character listed
15749 term   ::= [char - char]   -- matches any character in range
15750 @end group
15751 @end smallexample
15752
15753 @item full regular expression
15754 The second set of regular expressions is much more powerful. This is the
15755 type of regular expressions recognized by utilities such a @file{grep}.
15756
15757 The following is the form of a regular expression, expressed in Ada
15758 reference manual style BNF is as follows
15759
15760 @smallexample
15761 @iftex
15762 @leftskip=.5cm
15763 @end iftex
15764 @group
15765 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15766
15767 term ::= item @{item@}       -- concatenation (item then item)
15768
15769 item ::= elmt              -- match elmt
15770 item ::= elmt *            -- zero or more elmt's
15771 item ::= elmt +            -- one or more elmt's
15772 item ::= elmt ?            -- matches elmt or nothing
15773 @end group
15774 @group
15775 elmt ::= nschar            -- matches given character
15776 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15777 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15778 elmt ::= [char - char]     -- matches chars in given range
15779 elmt ::= \ char            -- matches given character
15780 elmt ::= .                 -- matches any single character
15781 elmt ::= ( regexp )        -- parens used for grouping
15782
15783 char ::= any character, including special characters
15784 nschar ::= any character except ()[].*+?^^^
15785 @end group
15786 @end smallexample
15787
15788 Following are a few examples:
15789
15790 @table @samp
15791 @item abcde|fghi
15792 will match any of the two strings @samp{abcde} and @samp{fghi},
15793
15794 @item abc*d
15795 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15796 @samp{abcccd}, and so on,
15797
15798 @item [a-z]+
15799 will match any string which has only lowercase characters in it (and at
15800 least one character.
15801
15802 @end table
15803 @end table
15804
15805 @node Examples of gnatxref Usage
15806 @section Examples of @code{gnatxref} Usage
15807
15808 @subsection General Usage
15809
15810 @noindent
15811 For the following examples, we will consider the following units:
15812
15813 @smallexample @c ada
15814 @group
15815 @cartouche
15816 main.ads:
15817 1: with Bar;
15818 2: package Main is
15819 3:     procedure Foo (B : in Integer);
15820 4:     C : Integer;
15821 5: private
15822 6:     D : Integer;
15823 7: end Main;
15824
15825 main.adb:
15826 1: package body Main is
15827 2:     procedure Foo (B : in Integer) is
15828 3:     begin
15829 4:        C := B;
15830 5:        D := B;
15831 6:        Bar.Print (B);
15832 7:        Bar.Print (C);
15833 8:     end Foo;
15834 9: end Main;
15835
15836 bar.ads:
15837 1: package Bar is
15838 2:     procedure Print (B : Integer);
15839 3: end bar;
15840 @end cartouche
15841 @end group
15842 @end smallexample
15843
15844 @table @code
15845
15846 @noindent
15847 The first thing to do is to recompile your application (for instance, in
15848 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15849 the cross-referencing information.
15850 You can then issue any of the following commands:
15851
15852 @item gnatxref main.adb
15853 @code{gnatxref} generates cross-reference information for main.adb
15854 and every unit 'with'ed by main.adb.
15855
15856 The output would be:
15857 @smallexample
15858 @iftex
15859 @leftskip=0cm
15860 @end iftex
15861 B                                                      Type: Integer
15862   Decl: bar.ads           2:22
15863 B                                                      Type: Integer
15864   Decl: main.ads          3:20
15865   Body: main.adb          2:20
15866   Ref:  main.adb          4:13     5:13     6:19
15867 Bar                                                    Type: Unit
15868   Decl: bar.ads           1:9
15869   Ref:  main.adb          6:8      7:8
15870        main.ads           1:6
15871 C                                                      Type: Integer
15872   Decl: main.ads          4:5
15873   Modi: main.adb          4:8
15874   Ref:  main.adb          7:19
15875 D                                                      Type: Integer
15876   Decl: main.ads          6:5
15877   Modi: main.adb          5:8
15878 Foo                                                    Type: Unit
15879   Decl: main.ads          3:15
15880   Body: main.adb          2:15
15881 Main                                                    Type: Unit
15882   Decl: main.ads          2:9
15883   Body: main.adb          1:14
15884 Print                                                   Type: Unit
15885   Decl: bar.ads           2:15
15886   Ref:  main.adb          6:12     7:12
15887 @end smallexample
15888
15889 @noindent
15890 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15891 its body is in main.adb, line 1, column 14 and is not referenced any where.
15892
15893 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15894 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15895
15896 @item gnatxref package1.adb package2.ads
15897 @code{gnatxref} will generates cross-reference information for
15898 package1.adb, package2.ads and any other package 'with'ed by any
15899 of these.
15900
15901 @end table
15902
15903 @ifclear vms
15904 @subsection Using gnatxref with vi
15905
15906 @code{gnatxref} can generate a tags file output, which can be used
15907 directly from @command{vi}. Note that the standard version of @command{vi}
15908 will not work properly with overloaded symbols. Consider using another
15909 free implementation of @command{vi}, such as @command{vim}.
15910
15911 @smallexample
15912 $ gnatxref -v gnatfind.adb > tags
15913 @end smallexample
15914
15915 @noindent
15916 will generate the tags file for @code{gnatfind} itself (if the sources
15917 are in the search path!).
15918
15919 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15920 (replacing @var{entity} by whatever you are looking for), and vi will
15921 display a new file with the corresponding declaration of entity.
15922 @end ifclear
15923
15924 @node Examples of gnatfind Usage
15925 @section Examples of @code{gnatfind} Usage
15926
15927 @table @code
15928
15929 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15930 Find declarations for all entities xyz referenced at least once in
15931 main.adb. The references are search in every library file in the search
15932 path.
15933
15934 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15935 switch is set)
15936
15937 The output will look like:
15938 @smallexample
15939 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15940 ^directory/^[directory]^main.adb:24:10: xyz <= body
15941 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15942 @end smallexample
15943
15944 @noindent
15945 that is to say, one of the entities xyz found in main.adb is declared at
15946 line 12 of main.ads (and its body is in main.adb), and another one is
15947 declared at line 45 of foo.ads
15948
15949 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15950 This is the same command as the previous one, instead @code{gnatfind} will
15951 display the content of the Ada source file lines.
15952
15953 The output will look like:
15954
15955 @smallexample
15956 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15957    procedure xyz;
15958 ^directory/^[directory]^main.adb:24:10: xyz <= body
15959    procedure xyz is
15960 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15961    xyz : Integer;
15962 @end smallexample
15963
15964 @noindent
15965 This can make it easier to find exactly the location your are looking
15966 for.
15967
15968 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15969 Find references to all entities containing an x that are
15970 referenced on line 123 of main.ads.
15971 The references will be searched only in main.ads and foo.adb.
15972
15973 @item gnatfind main.ads:123
15974 Find declarations and bodies for all entities that are referenced on
15975 line 123 of main.ads.
15976
15977 This is the same as @code{gnatfind "*":main.adb:123}.
15978
15979 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15980 Find the declaration for the entity referenced at column 45 in
15981 line 123 of file main.adb in directory mydir. Note that it
15982 is usual to omit the identifier name when the column is given,
15983 since the column position identifies a unique reference.
15984
15985 The column has to be the beginning of the identifier, and should not
15986 point to any character in the middle of the identifier.
15987
15988 @end table
15989
15990 @c *********************************
15991 @node The GNAT Pretty-Printer gnatpp
15992 @chapter The GNAT Pretty-Printer @command{gnatpp}
15993 @findex gnatpp
15994 @cindex Pretty-Printer
15995
15996 @noindent
15997 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15998 for source reformatting / pretty-printing.
15999 It takes an Ada source file as input and generates a reformatted
16000 version as output.
16001 You can specify various style directives via switches; e.g.,
16002 identifier case conventions, rules of indentation, and comment layout.
16003
16004 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16005 tree for the input source and thus requires the input to be syntactically and
16006 semantically legal.
16007 If this condition is not met, @command{gnatpp} will terminate with an
16008 error message; no output file will be generated.
16009
16010 If the source files presented to @command{gnatpp} contain
16011 preprocessing directives, then the output file will
16012 correspond to the generated source after all
16013 preprocessing is carried out. There is no way
16014 using @command{gnatpp} to obtain pretty printed files that
16015 include the preprocessing directives.
16016
16017 If the compilation unit
16018 contained in the input source depends semantically upon units located
16019 outside the current directory, you have to provide the source search path
16020 when invoking @command{gnatpp}, if these units are contained in files with
16021 names that do not follow the GNAT file naming rules, you have to provide
16022 the configuration file describing the corresponding naming scheme;
16023 see the description of the @command{gnatpp}
16024 switches below. Another possibility is to use a project file and to
16025 call @command{gnatpp} through the @command{gnat} driver
16026
16027 The @command{gnatpp} command has the form
16028
16029 @smallexample
16030 $ gnatpp @ovar{switches} @var{filename}
16031 @end smallexample
16032
16033 @noindent
16034 where
16035 @itemize @bullet
16036 @item
16037 @var{switches} is an optional sequence of switches defining such properties as
16038 the formatting rules, the source search path, and the destination for the
16039 output source file
16040
16041 @item
16042 @var{filename} is the name (including the extension) of the source file to
16043 reformat; ``wildcards'' or several file names on the same gnatpp command are
16044 allowed.  The file name may contain path information; it does not have to
16045 follow the GNAT file naming rules
16046 @end itemize
16047
16048 @menu
16049 * Switches for gnatpp::
16050 * Formatting Rules::
16051 @end menu
16052
16053 @node Switches for gnatpp
16054 @section Switches for @command{gnatpp}
16055
16056 @noindent
16057 The following subsections describe the various switches accepted by
16058 @command{gnatpp}, organized by category.
16059
16060 @ifclear vms
16061 You specify a switch by supplying a name and generally also a value.
16062 In many cases the values for a switch with a given name are incompatible with
16063 each other
16064 (for example the switch that controls the casing of a reserved word may have
16065 exactly one value: upper case, lower case, or
16066 mixed case) and thus exactly one such switch can be in effect for an
16067 invocation of @command{gnatpp}.
16068 If more than one is supplied, the last one is used.
16069 However, some values for the same switch are mutually compatible.
16070 You may supply several such switches to @command{gnatpp}, but then
16071 each must be specified in full, with both the name and the value.
16072 Abbreviated forms (the name appearing once, followed by each value) are
16073 not permitted.
16074 For example, to set
16075 the alignment of the assignment delimiter both in declarations and in
16076 assignment statements, you must write @option{-A2A3}
16077 (or @option{-A2 -A3}), but not @option{-A23}.
16078 @end ifclear
16079
16080 @ifset vms
16081 In many cases the set of options for a given qualifier are incompatible with
16082 each other (for example the qualifier that controls the casing of a reserved
16083 word may have exactly one option, which specifies either upper case, lower
16084 case, or mixed case), and thus exactly one such option can be in effect for
16085 an invocation of @command{gnatpp}.
16086 If more than one is supplied, the last one is used.
16087 However, some qualifiers have options that are mutually compatible,
16088 and then you may then supply several such options when invoking
16089 @command{gnatpp}.
16090 @end ifset
16091
16092 In most cases, it is obvious whether or not the
16093 ^values for a switch with a given name^options for a given qualifier^
16094 are compatible with each other.
16095 When the semantics might not be evident, the summaries below explicitly
16096 indicate the effect.
16097
16098 @menu
16099 * Alignment Control::
16100 * Casing Control::
16101 * Construct Layout Control::
16102 * General Text Layout Control::
16103 * Other Formatting Options::
16104 * Setting the Source Search Path::
16105 * Output File Control::
16106 * Other gnatpp Switches::
16107 @end menu
16108
16109 @node Alignment Control
16110 @subsection Alignment Control
16111 @cindex Alignment control in @command{gnatpp}
16112
16113 @noindent
16114 Programs can be easier to read if certain constructs are vertically aligned.
16115 By default all alignments are set ON.
16116 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16117 OFF, and then use one or more of the other
16118 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16119 to activate alignment for specific constructs.
16120
16121 @table @option
16122 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16123
16124 @ifset vms
16125 @item /ALIGN=ON
16126 Set all alignments to ON
16127 @end ifset
16128
16129 @item ^-A0^/ALIGN=OFF^
16130 Set all alignments to OFF
16131
16132 @item ^-A1^/ALIGN=COLONS^
16133 Align @code{:} in declarations
16134
16135 @item ^-A2^/ALIGN=DECLARATIONS^
16136 Align @code{:=} in initializations in declarations
16137
16138 @item ^-A3^/ALIGN=STATEMENTS^
16139 Align @code{:=} in assignment statements
16140
16141 @item ^-A4^/ALIGN=ARROWS^
16142 Align @code{=>} in associations
16143
16144 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16145 Align @code{at} keywords in the component clauses in record
16146 representation clauses
16147 @end table
16148
16149 @noindent
16150 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16151 is allowed.
16152
16153 @node Casing Control
16154 @subsection Casing Control
16155 @cindex Casing control in @command{gnatpp}
16156
16157 @noindent
16158 @command{gnatpp} allows you to specify the casing for reserved words,
16159 pragma names, attribute designators and identifiers.
16160 For identifiers you may define a
16161 general rule for name casing but also override this rule
16162 via a set of dictionary files.
16163
16164 Three types of casing are supported: lower case, upper case, and mixed case.
16165 Lower and upper case are self-explanatory (but since some letters in
16166 Latin1 and other GNAT-supported character sets
16167 exist only in lower-case form, an upper case conversion will have no
16168 effect on them.)
16169 ``Mixed case'' means that the first letter, and also each letter immediately
16170 following an underscore, are converted to their uppercase forms;
16171 all the other letters are converted to their lowercase forms.
16172
16173 @table @option
16174 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16175 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16176 Attribute designators are lower case
16177
16178 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16179 Attribute designators are upper case
16180
16181 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16182 Attribute designators are mixed case (this is the default)
16183
16184 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16185 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16186 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16187 lower case (this is the default)
16188
16189 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16190 Keywords are upper case
16191
16192 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16193 @item ^-nD^/NAME_CASING=AS_DECLARED^
16194 Name casing for defining occurrences are as they appear in the source file
16195 (this is the default)
16196
16197 @item ^-nU^/NAME_CASING=UPPER_CASE^
16198 Names are in upper case
16199
16200 @item ^-nL^/NAME_CASING=LOWER_CASE^
16201 Names are in lower case
16202
16203 @item ^-nM^/NAME_CASING=MIXED_CASE^
16204 Names are in mixed case
16205
16206 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16207 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16208 Pragma names are lower case
16209
16210 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16211 Pragma names are upper case
16212
16213 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16214 Pragma names are mixed case (this is the default)
16215
16216 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16217 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16218 Use @var{file} as a @emph{dictionary file} that defines
16219 the casing for a set of specified names,
16220 thereby overriding the effect on these names by
16221 any explicit or implicit
16222 ^-n^/NAME_CASING^ switch.
16223 To supply more than one dictionary file,
16224 use ^several @option{-D} switches^a list of files as options^.
16225
16226 @noindent
16227 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16228 to define the casing for the Ada predefined names and
16229 the names declared in the GNAT libraries.
16230
16231 @item ^-D-^/SPECIFIC_CASING^
16232 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16233 Do not use the default dictionary file;
16234 instead, use the casing
16235 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16236 dictionary file(s)
16237 @end table
16238
16239 @noindent
16240 The structure of a dictionary file, and details on the conventions
16241 used in the default dictionary file, are defined in @ref{Name Casing}.
16242
16243 The @option{^-D-^/SPECIFIC_CASING^} and
16244 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16245 compatible.
16246
16247 @node Construct Layout Control
16248 @subsection Construct Layout Control
16249 @cindex Layout control in @command{gnatpp}
16250
16251 @noindent
16252 This group of @command{gnatpp} switches controls the layout of comments and
16253 complex syntactic constructs.  See @ref{Formatting Comments} for details
16254 on their effect.
16255
16256 @table @option
16257 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16258 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16259 All the comments remain unchanged
16260
16261 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16262 GNAT-style comment line indentation (this is the default).
16263
16264 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16265 Reference-manual comment line indentation.
16266
16267 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16268 GNAT-style comment beginning
16269
16270 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16271 Reformat comment blocks
16272
16273 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16274 Keep unchanged special form comments
16275
16276 Reformat comment blocks
16277
16278 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16279 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16280 GNAT-style layout (this is the default)
16281
16282 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16283 Compact layout
16284
16285 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16286 Uncompact layout
16287
16288 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16289 @item ^-N^/NOTABS^
16290 All the VT characters are removed from the comment text. All the HT characters
16291 are expanded with the sequences of space characters to get to the next tab
16292 stops.
16293
16294 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16295 @item ^--no-separate-is^/NO_SEPARATE_IS^
16296 Do not place the keyword @code{is} on a separate line in a subprogram body in
16297 case if the spec occupies more then one line.
16298
16299 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16300 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16301 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16302 keyword @code{then} in IF statements on a separate line.
16303
16304 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16305 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16306 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16307 keyword @code{then} in IF statements on a separate line. This option is
16308 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16309
16310 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16311 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16312 Start each USE clause in a context clause from a separate line.
16313
16314 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16315 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16316 Use a separate line for a loop or block statement name, but do not use an extra
16317 indentation level for the statement itself.
16318
16319 @end table
16320
16321 @ifclear vms
16322 @noindent
16323 The @option{-c1} and @option{-c2} switches are incompatible.
16324 The @option{-c3} and @option{-c4} switches are compatible with each other and
16325 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16326 the other comment formatting switches.
16327
16328 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16329 @end ifclear
16330
16331 @ifset vms
16332 @noindent
16333 For the @option{/COMMENTS_LAYOUT} qualifier:
16334 @itemize @bullet
16335 @item
16336 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16337 @item
16338 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16339 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16340 @end itemize
16341
16342 @noindent
16343 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16344 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16345 @end ifset
16346
16347 @node General Text Layout Control
16348 @subsection General Text Layout Control
16349
16350 @noindent
16351 These switches allow control over line length and indentation.
16352
16353 @table @option
16354 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16355 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16356 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16357
16358 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16359 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16360 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16361
16362 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16363 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16364 Indentation level for continuation lines (relative to the line being
16365 continued), @var{nnn} from 1@dots{}9.
16366 The default
16367 value is one less then the (normal) indentation level, unless the
16368 indentation is set to 1 (in which case the default value for continuation
16369 line indentation is also 1)
16370 @end table
16371
16372 @node Other Formatting Options
16373 @subsection Other Formatting Options
16374
16375 @noindent
16376 These switches control the inclusion of missing end/exit labels, and
16377 the indentation level in @b{case} statements.
16378
16379 @table @option
16380 @item ^-e^/NO_MISSED_LABELS^
16381 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16382 Do not insert missing end/exit labels. An end label is the name of
16383 a construct that may optionally be repeated at the end of the
16384 construct's declaration;
16385 e.g., the names of packages, subprograms, and tasks.
16386 An exit label is the name of a loop that may appear as target
16387 of an exit statement within the loop.
16388 By default, @command{gnatpp} inserts these end/exit labels when
16389 they are absent from the original source. This option suppresses such
16390 insertion, so that the formatted source reflects the original.
16391
16392 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16393 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16394 Insert a Form Feed character after a pragma Page.
16395
16396 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16397 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16398 Do not use an additional indentation level for @b{case} alternatives
16399 and variants if there are @var{nnn} or more (the default
16400 value is 10).
16401 If @var{nnn} is 0, an additional indentation level is
16402 used for @b{case} alternatives and variants regardless of their number.
16403 @end table
16404
16405 @node Setting the Source Search Path
16406 @subsection Setting the Source Search Path
16407
16408 @noindent
16409 To define the search path for the input source file, @command{gnatpp}
16410 uses the same switches as the GNAT compiler, with the same effects.
16411
16412 @table @option
16413 @item ^-I^/SEARCH=^@var{dir}
16414 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16415 The same as the corresponding gcc switch
16416
16417 @item ^-I-^/NOCURRENT_DIRECTORY^
16418 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16419 The same as the corresponding gcc switch
16420
16421 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16422 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16423 The same as the corresponding gcc switch
16424
16425 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16426 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16427 The same as the corresponding gcc switch
16428
16429 @end table
16430
16431 @node Output File Control
16432 @subsection Output File Control
16433
16434 @noindent
16435 By default the output is sent to the file whose name is obtained by appending
16436 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16437 (if the file with this name already exists, it is unconditionally overwritten).
16438 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16439 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16440 as output file.
16441 The output may be redirected by the following switches:
16442
16443 @table @option
16444 @item ^-pipe^/STANDARD_OUTPUT^
16445 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16446 Send the output to @code{Standard_Output}
16447
16448 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16449 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16450 Write the output into @var{output_file}.
16451 If @var{output_file} already exists, @command{gnatpp} terminates without
16452 reading or processing the input file.
16453
16454 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16455 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16456 Write the output into @var{output_file}, overwriting the existing file
16457 (if one is present).
16458
16459 @item ^-r^/REPLACE^
16460 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16461 Replace the input source file with the reformatted output, and copy the
16462 original input source into the file whose name is obtained by appending the
16463 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16464 If a file with this name already exists, @command{gnatpp} terminates without
16465 reading or processing the input file.
16466
16467 @item ^-rf^/OVERRIDING_REPLACE^
16468 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16469 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16470 already exists, it is overwritten.
16471
16472 @item ^-rnb^/REPLACE_NO_BACKUP^
16473 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16474 Replace the input source file with the reformatted output without
16475 creating any backup copy of the input source.
16476
16477 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16478 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16479 Specifies the format of the reformatted output file. The @var{xxx}
16480 ^string specified with the switch^option^ may be either
16481 @itemize @bullet
16482 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16483 @item ``@option{^crlf^CRLF^}''
16484 the same as @option{^crlf^CRLF^}
16485 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16486 @item ``@option{^lf^LF^}''
16487 the same as @option{^unix^UNIX^}
16488 @end itemize
16489
16490 @item ^-W^/RESULT_ENCODING=^@var{e}
16491 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16492 Specify the wide character encoding method used to write the code in the
16493 result file
16494 @var{e} is one of the following:
16495
16496 @itemize @bullet
16497
16498 @item ^h^HEX^
16499 Hex encoding
16500
16501 @item ^u^UPPER^
16502 Upper half encoding
16503
16504 @item ^s^SHIFT_JIS^
16505 Shift/JIS encoding
16506
16507 @item ^e^EUC^
16508 EUC encoding
16509
16510 @item ^8^UTF8^
16511 UTF-8 encoding
16512
16513 @item ^b^BRACKETS^
16514 Brackets encoding (default value)
16515 @end itemize
16516
16517 @end table
16518
16519 @noindent
16520 Options @option{^-pipe^/STANDARD_OUTPUT^},
16521 @option{^-o^/OUTPUT^} and
16522 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16523 contains only one file to reformat.
16524 Option
16525 @option{^--eol^/END_OF_LINE^}
16526 and
16527 @option{^-W^/RESULT_ENCODING^}
16528 cannot be used together
16529 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16530
16531 @node Other gnatpp Switches
16532 @subsection Other @code{gnatpp} Switches
16533
16534 @noindent
16535 The additional @command{gnatpp} switches are defined in this subsection.
16536
16537 @table @option
16538 @item ^-files @var{filename}^/FILES=@var{output_file}^
16539 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16540 Take the argument source files from the specified file. This file should be an
16541 ordinary textual file containing file names separated by spaces or
16542 line breaks. You can use this switch more then once in the same call to
16543 @command{gnatpp}. You also can combine this switch with explicit list of
16544 files.
16545
16546 @item ^-v^/VERBOSE^
16547 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16548 Verbose mode;
16549 @command{gnatpp} generates version information and then
16550 a trace of the actions it takes to produce or obtain the ASIS tree.
16551
16552 @item ^-w^/WARNINGS^
16553 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16554 Warning mode;
16555 @command{gnatpp} generates a warning whenever it cannot provide
16556 a required layout in the result source.
16557 @end table
16558
16559 @node Formatting Rules
16560 @section Formatting Rules
16561
16562 @noindent
16563 The following subsections show how @command{gnatpp} treats ``white space'',
16564 comments, program layout, and name casing.
16565 They provide the detailed descriptions of the switches shown above.
16566
16567 @menu
16568 * White Space and Empty Lines::
16569 * Formatting Comments::
16570 * Construct Layout::
16571 * Name Casing::
16572 @end menu
16573
16574 @node White Space and Empty Lines
16575 @subsection White Space and Empty Lines
16576
16577 @noindent
16578 @command{gnatpp} does not have an option to control space characters.
16579 It will add or remove spaces according to the style illustrated by the
16580 examples in the @cite{Ada Reference Manual}.
16581
16582 The only format effectors
16583 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16584 that will appear in the output file are platform-specific line breaks,
16585 and also format effectors within (but not at the end of) comments.
16586 In particular, each horizontal tab character that is not inside
16587 a comment will be treated as a space and thus will appear in the
16588 output file as zero or more spaces depending on
16589 the reformatting of the line in which it appears.
16590 The only exception is a Form Feed character, which is inserted after a
16591 pragma @code{Page} when @option{-ff} is set.
16592
16593 The output file will contain no lines with trailing ``white space'' (spaces,
16594 format effectors).
16595
16596 Empty lines in the original source are preserved
16597 only if they separate declarations or statements.
16598 In such contexts, a
16599 sequence of two or more empty lines is replaced by exactly one empty line.
16600 Note that a blank line will be removed if it separates two ``comment blocks''
16601 (a comment block is a sequence of whole-line comments).
16602 In order to preserve a visual separation between comment blocks, use an
16603 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16604 Likewise, if for some reason you wish to have a sequence of empty lines,
16605 use a sequence of empty comments instead.
16606
16607 @node Formatting Comments
16608 @subsection Formatting Comments
16609
16610 @noindent
16611 Comments in Ada code are of two kinds:
16612 @itemize @bullet
16613 @item
16614 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16615 ``white space'') on a line
16616
16617 @item
16618 an @emph{end-of-line comment}, which follows some other Ada lexical element
16619 on the same line.
16620 @end itemize
16621
16622 @noindent
16623 The indentation of a whole-line comment is that of either
16624 the preceding or following line in
16625 the formatted source, depending on switch settings as will be described below.
16626
16627 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16628 between the end of the preceding Ada lexical element and the beginning
16629 of the comment as appear in the original source,
16630 unless either the comment has to be split to
16631 satisfy the line length limitation, or else the next line contains a
16632 whole line comment that is considered a continuation of this end-of-line
16633 comment (because it starts at the same position).
16634 In the latter two
16635 cases, the start of the end-of-line comment is moved right to the nearest
16636 multiple of the indentation level.
16637 This may result in a ``line overflow'' (the right-shifted comment extending
16638 beyond the maximum line length), in which case the comment is split as
16639 described below.
16640
16641 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16642 (GNAT-style comment line indentation)
16643 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16644 (reference-manual comment line indentation).
16645 With reference-manual style, a whole-line comment is indented as if it
16646 were a declaration or statement at the same place
16647 (i.e., according to the indentation of the preceding line(s)).
16648 With GNAT style, a whole-line comment that is immediately followed by an
16649 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16650 word @b{begin}, is indented based on the construct that follows it.
16651
16652 For example:
16653 @smallexample @c ada
16654 @cartouche
16655 if A then
16656     null;
16657        -- some comment
16658 else
16659    null;
16660 end if;
16661 @end cartouche
16662 @end smallexample
16663
16664 @noindent
16665 Reference-manual indentation produces:
16666
16667 @smallexample @c ada
16668 @cartouche
16669 if A then
16670    null;
16671    --  some comment
16672 else
16673    null;
16674 end if;
16675 @end cartouche
16676 @end smallexample
16677
16678 @noindent
16679 while GNAT-style indentation produces:
16680
16681 @smallexample @c ada
16682 @cartouche
16683 if A then
16684    null;
16685 --  some comment
16686 else
16687    null;
16688 end if;
16689 @end cartouche
16690 @end smallexample
16691
16692 @noindent
16693 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16694 (GNAT style comment beginning) has the following
16695 effect:
16696
16697 @itemize @bullet
16698 @item
16699 For each whole-line comment that does not end with two hyphens,
16700 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16701 to ensure that there are at least two spaces between these hyphens and the
16702 first non-blank character of the comment.
16703 @end itemize
16704
16705 @noindent
16706 For an end-of-line comment, if in the original source the next line is a
16707 whole-line comment that starts at the same position
16708 as the end-of-line comment,
16709 then the whole-line comment (and all whole-line comments
16710 that follow it and that start at the same position)
16711 will start at this position in the output file.
16712
16713 @noindent
16714 That is, if in the original source we have:
16715
16716 @smallexample @c ada
16717 @cartouche
16718 begin
16719 A := B + C;            --  B must be in the range Low1..High1
16720                        --  C must be in the range Low2..High2
16721              --B+C will be in the range Low1+Low2..High1+High2
16722 X := X + 1;
16723 @end cartouche
16724 @end smallexample
16725
16726 @noindent
16727 Then in the formatted source we get
16728
16729 @smallexample @c ada
16730 @cartouche
16731 begin
16732    A := B + C;            --  B must be in the range Low1..High1
16733                           --  C must be in the range Low2..High2
16734    --  B+C will be in the range Low1+Low2..High1+High2
16735    X := X + 1;
16736 @end cartouche
16737 @end smallexample
16738
16739 @noindent
16740 A comment that exceeds the line length limit will be split.
16741 Unless switch
16742 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16743 the line belongs to a reformattable block, splitting the line generates a
16744 @command{gnatpp} warning.
16745 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16746 comments may be reformatted in typical
16747 word processor style (that is, moving words between lines and putting as
16748 many words in a line as possible).
16749
16750 @noindent
16751 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16752 that has a special format (that is, a character that is neither a letter nor digit
16753 not white space nor line break immediately following the leading @code{--} of
16754 the comment) should be without any change moved from the argument source
16755 into reformatted source. This switch allows to preserve comments that are used
16756 as a special marks in the code (e.g.@: SPARK annotation).
16757
16758 @node Construct Layout
16759 @subsection Construct Layout
16760
16761 @noindent
16762 In several cases the suggested layout in the Ada Reference Manual includes
16763 an extra level of indentation that many programmers prefer to avoid. The
16764 affected cases include:
16765
16766 @itemize @bullet
16767
16768 @item Record type declaration (RM 3.8)
16769
16770 @item Record representation clause (RM 13.5.1)
16771
16772 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16773
16774 @item Block statement in case if a block has a statement identifier (RM 5.6)
16775 @end itemize
16776
16777 @noindent
16778 In compact mode (when GNAT style layout or compact layout is set),
16779 the pretty printer uses one level of indentation instead
16780 of two. This is achieved in the record definition and record representation
16781 clause cases by putting the @code{record} keyword on the same line as the
16782 start of the declaration or representation clause, and in the block and loop
16783 case by putting the block or loop header on the same line as the statement
16784 identifier.
16785
16786 @noindent
16787 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16788 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16789 layout on the one hand, and uncompact layout
16790 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16791 can be illustrated by the following examples:
16792
16793 @iftex
16794 @cartouche
16795 @multitable @columnfractions .5 .5
16796 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16797
16798 @item
16799 @smallexample @c ada
16800 type q is record
16801    a : integer;
16802    b : integer;
16803 end record;
16804 @end smallexample
16805 @tab
16806 @smallexample @c ada
16807 type q is
16808    record
16809       a : integer;
16810       b : integer;
16811    end record;
16812 @end smallexample
16813
16814 @item
16815 @smallexample @c ada
16816 for q use record
16817    a at 0 range  0 .. 31;
16818    b at 4 range  0 .. 31;
16819 end record;
16820 @end smallexample
16821 @tab
16822 @smallexample @c ada
16823 for q use
16824    record
16825       a at 0 range  0 .. 31;
16826       b at 4 range  0 .. 31;
16827    end record;
16828 @end smallexample
16829
16830 @item
16831 @smallexample @c ada
16832 Block : declare
16833    A : Integer := 3;
16834 begin
16835    Proc (A, A);
16836 end Block;
16837 @end smallexample
16838 @tab
16839 @smallexample @c ada
16840 Block :
16841    declare
16842       A : Integer := 3;
16843    begin
16844       Proc (A, A);
16845    end Block;
16846 @end smallexample
16847
16848 @item
16849 @smallexample @c ada
16850 Clear : for J in 1 .. 10 loop
16851    A (J) := 0;
16852 end loop Clear;
16853 @end smallexample
16854 @tab
16855 @smallexample @c ada
16856 Clear :
16857    for J in 1 .. 10 loop
16858       A (J) := 0;
16859    end loop Clear;
16860 @end smallexample
16861 @end multitable
16862 @end cartouche
16863 @end iftex
16864
16865 @ifnottex
16866 @smallexample
16867 @cartouche
16868 GNAT style, compact layout              Uncompact layout
16869
16870 type q is record                        type q is
16871    a : integer;                            record
16872    b : integer;                               a : integer;
16873 end record;                                   b : integer;
16874                                            end record;
16875
16876 for q use record                        for q use
16877    a at 0 range  0 .. 31;                  record
16878    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16879 end record;                                   b at 4 range  0 .. 31;
16880                                            end record;
16881
16882 Block : declare                         Block :
16883    A : Integer := 3;                       declare
16884 begin                                         A : Integer := 3;
16885    Proc (A, A);                            begin
16886 end Block;                                    Proc (A, A);
16887                                            end Block;
16888
16889 Clear : for J in 1 .. 10 loop           Clear :
16890    A (J) := 0;                             for J in 1 .. 10 loop
16891 end loop Clear;                               A (J) := 0;
16892                                            end loop Clear;
16893 @end cartouche
16894 @end smallexample
16895 @end ifnottex
16896
16897 @noindent
16898 A further difference between GNAT style layout and compact layout is that
16899 GNAT style layout inserts empty lines as separation for
16900 compound statements, return statements and bodies.
16901
16902 Note that the layout specified by
16903 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16904 for named block and loop statements overrides the layout defined by these
16905 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16906 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16907 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16908
16909 @node Name Casing
16910 @subsection Name Casing
16911
16912 @noindent
16913 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16914 the same casing as the corresponding defining identifier.
16915
16916 You control the casing for defining occurrences via the
16917 @option{^-n^/NAME_CASING^} switch.
16918 @ifclear vms
16919 With @option{-nD} (``as declared'', which is the default),
16920 @end ifclear
16921 @ifset vms
16922 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16923 @end ifset
16924 defining occurrences appear exactly as in the source file
16925 where they are declared.
16926 The other ^values for this switch^options for this qualifier^ ---
16927 @option{^-nU^UPPER_CASE^},
16928 @option{^-nL^LOWER_CASE^},
16929 @option{^-nM^MIXED_CASE^} ---
16930 result in
16931 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16932 If @command{gnatpp} changes the casing of a defining
16933 occurrence, it analogously changes the casing of all the
16934 usage occurrences of this name.
16935
16936 If the defining occurrence of a name is not in the source compilation unit
16937 currently being processed by @command{gnatpp}, the casing of each reference to
16938 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16939 switch (subject to the dictionary file mechanism described below).
16940 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16941 had affected the
16942 casing for the defining occurrence of the name.
16943
16944 Some names may need to be spelled with casing conventions that are not
16945 covered by the upper-, lower-, and mixed-case transformations.
16946 You can arrange correct casing by placing such names in a
16947 @emph{dictionary file},
16948 and then supplying a @option{^-D^/DICTIONARY^} switch.
16949 The casing of names from dictionary files overrides
16950 any @option{^-n^/NAME_CASING^} switch.
16951
16952 To handle the casing of Ada predefined names and the names from GNAT libraries,
16953 @command{gnatpp} assumes a default dictionary file.
16954 The name of each predefined entity is spelled with the same casing as is used
16955 for the entity in the @cite{Ada Reference Manual}.
16956 The name of each entity in the GNAT libraries is spelled with the same casing
16957 as is used in the declaration of that entity.
16958
16959 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16960 default dictionary file.
16961 Instead, the casing for predefined and GNAT-defined names will be established
16962 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16963 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16964 will appear as just shown,
16965 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16966 To ensure that even such names are rendered in uppercase,
16967 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16968 (or else, less conveniently, place these names in upper case in a dictionary
16969 file).
16970
16971 A dictionary file is
16972 a plain text file; each line in this file can be either a blank line
16973 (containing only space characters and ASCII.HT characters), an Ada comment
16974 line, or the specification of exactly one @emph{casing schema}.
16975
16976 A casing schema is a string that has the following syntax:
16977
16978 @smallexample
16979 @cartouche
16980   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16981
16982   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16983 @end cartouche
16984 @end smallexample
16985
16986 @noindent
16987 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16988 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16989
16990 The casing schema string can be followed by white space and/or an Ada-style
16991 comment; any amount of white space is allowed before the string.
16992
16993 If a dictionary file is passed as
16994 @ifclear vms
16995 the value of a @option{-D@var{file}} switch
16996 @end ifclear
16997 @ifset vms
16998 an option to the @option{/DICTIONARY} qualifier
16999 @end ifset
17000 then for every
17001 simple name and every identifier, @command{gnatpp} checks if the dictionary
17002 defines the casing for the name or for some of its parts (the term ``subword''
17003 is used below to denote the part of a name which is delimited by ``_'' or by
17004 the beginning or end of the word and which does not contain any ``_'' inside):
17005
17006 @itemize @bullet
17007 @item
17008 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17009 the casing defined by the dictionary; no subwords are checked for this word
17010
17011 @item
17012 for every subword @command{gnatpp} checks if the dictionary contains the
17013 corresponding string of the form @code{*@var{simple_identifier}*},
17014 and if it does, the casing of this @var{simple_identifier} is used
17015 for this subword
17016
17017 @item
17018 if the whole name does not contain any ``_'' inside, and if for this name
17019 the dictionary contains two entries - one of the form @var{identifier},
17020 and another - of the form *@var{simple_identifier}*, then the first one
17021 is applied to define the casing of this name
17022
17023 @item
17024 if more than one dictionary file is passed as @command{gnatpp} switches, each
17025 dictionary adds new casing exceptions and overrides all the existing casing
17026 exceptions set by the previous dictionaries
17027
17028 @item
17029 when @command{gnatpp} checks if the word or subword is in the dictionary,
17030 this check is not case sensitive
17031 @end itemize
17032
17033 @noindent
17034 For example, suppose we have the following source to reformat:
17035
17036 @smallexample @c ada
17037 @cartouche
17038 procedure test is
17039    name1 : integer := 1;
17040    name4_name3_name2 : integer := 2;
17041    name2_name3_name4 : Boolean;
17042    name1_var : Float;
17043 begin
17044    name2_name3_name4 := name4_name3_name2 > name1;
17045 end;
17046 @end cartouche
17047 @end smallexample
17048
17049 @noindent
17050 And suppose we have two dictionaries:
17051
17052 @smallexample
17053 @cartouche
17054 @i{dict1:}
17055    NAME1
17056    *NaMe3*
17057    *Name1*
17058 @end cartouche
17059
17060 @cartouche
17061 @i{dict2:}
17062   *NAME3*
17063 @end cartouche
17064 @end smallexample
17065
17066 @noindent
17067 If @command{gnatpp} is called with the following switches:
17068
17069 @smallexample
17070 @ifclear vms
17071 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17072 @end ifclear
17073 @ifset vms
17074 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17075 @end ifset
17076 @end smallexample
17077
17078 @noindent
17079 then we will get the following name casing in the @command{gnatpp} output:
17080
17081 @smallexample @c ada
17082 @cartouche
17083 procedure Test is
17084    NAME1             : Integer := 1;
17085    Name4_NAME3_Name2 : Integer := 2;
17086    Name2_NAME3_Name4 : Boolean;
17087    Name1_Var         : Float;
17088 begin
17089    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17090 end Test;
17091 @end cartouche
17092 @end smallexample
17093
17094 @c *********************************
17095 @node The GNAT Metric Tool gnatmetric
17096 @chapter The GNAT Metric Tool @command{gnatmetric}
17097 @findex gnatmetric
17098 @cindex Metric tool
17099
17100 @noindent
17101 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17102 for computing various program metrics.
17103 It takes an Ada source file as input and generates a file containing the
17104 metrics data as output. Various switches control which
17105 metrics are computed and output.
17106
17107 @command{gnatmetric} generates and uses the ASIS
17108 tree for the input source and thus requires the input to be syntactically and
17109 semantically legal.
17110 If this condition is not met, @command{gnatmetric} will generate
17111 an error message; no metric information for this file will be
17112 computed and reported.
17113
17114 If the compilation unit contained in the input source depends semantically
17115 upon units in files located outside the current directory, you have to provide
17116 the source search path when invoking @command{gnatmetric}.
17117 If it depends semantically upon units that are contained
17118 in files with names that do not follow the GNAT file naming rules, you have to
17119 provide the configuration file describing the corresponding naming scheme (see
17120 the description of the @command{gnatmetric} switches below.)
17121 Alternatively, you may use a project file and invoke @command{gnatmetric}
17122 through the @command{gnat} driver.
17123
17124 The @command{gnatmetric} command has the form
17125
17126 @smallexample
17127 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17128 @end smallexample
17129
17130 @noindent
17131 where
17132 @itemize @bullet
17133 @item
17134 @var{switches} specify the metrics to compute and define the destination for
17135 the output
17136
17137 @item
17138 Each @var{filename} is the name (including the extension) of a source
17139 file to process. ``Wildcards'' are allowed, and
17140 the file name may contain path information.
17141 If no @var{filename} is supplied, then the @var{switches} list must contain
17142 at least one
17143 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17144 Including both a @option{-files} switch and one or more
17145 @var{filename} arguments is permitted.
17146
17147 @item
17148 @samp{-cargs @var{gcc_switches}} is a list of switches for
17149 @command{gcc}. They will be passed on to all compiler invocations made by
17150 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17151 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17152 and use the @option{-gnatec} switch to set the configuration file.
17153 @end itemize
17154
17155 @menu
17156 * Switches for gnatmetric::
17157 @end menu
17158
17159 @node Switches for gnatmetric
17160 @section Switches for @command{gnatmetric}
17161
17162 @noindent
17163 The following subsections describe the various switches accepted by
17164 @command{gnatmetric}, organized by category.
17165
17166 @menu
17167 * Output Files Control::
17168 * Disable Metrics For Local Units::
17169 * Specifying a set of metrics to compute::
17170 * Other gnatmetric Switches::
17171 * Generate project-wide metrics::
17172 @end menu
17173
17174 @node Output Files Control
17175 @subsection Output File Control
17176 @cindex Output file control in @command{gnatmetric}
17177
17178 @noindent
17179 @command{gnatmetric} has two output formats. It can generate a
17180 textual (human-readable) form, and also XML. By default only textual
17181 output is generated.
17182
17183 When generating the output in textual form, @command{gnatmetric} creates
17184 for each Ada source file a corresponding text file
17185 containing the computed metrics, except for the case when the set of metrics
17186 specified by gnatmetric parameters consists only of metrics that are computed
17187 for the whole set of analyzed sources, but not for each Ada source.
17188 By default, this file is placed in the same directory as where the source
17189 file is located, and its name is obtained
17190 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17191 input file.
17192
17193 All the output information generated in XML format is placed in a single
17194 file. By default this file is placed in the current directory and has the
17195 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17196
17197 Some of the computed metrics are summed over the units passed to
17198 @command{gnatmetric}; for example, the total number of lines of code.
17199 By default this information is sent to @file{stdout}, but a file
17200 can be specified with the @option{-og} switch.
17201
17202 The following switches control the @command{gnatmetric} output:
17203
17204 @table @option
17205 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17206 @item ^-x^/XML^
17207 Generate the XML output
17208
17209 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17210 @item ^-xs^/XSD^
17211 Generate the XML output and the XML schema file that describes the structure
17212 of the XML metric report, this schema is assigned to the XML file. The schema
17213 file has the same name as the XML output file with @file{.xml} suffix replaced
17214 with @file{.xsd}
17215
17216 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17217 @item ^-nt^/NO_TEXT^
17218 Do not generate the output in text form (implies @option{^-x^/XML^})
17219
17220 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17221 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17222 Put textual files with detailed metrics into @var{output_dir}
17223
17224 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17225 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17226 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17227 in the name of the output file.
17228
17229 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17230 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17231 Put global metrics into @var{file_name}
17232
17233 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17234 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17235 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17236
17237 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17238 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17239 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17240 output includes the name(s) of the Ada source file(s) from which the metrics
17241 are computed.  By default each name includes the absolute path. The
17242 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17243 to exclude all directory information from the file names that are output.)
17244
17245 @end table
17246
17247 @node Disable Metrics For Local Units
17248 @subsection Disable Metrics For Local Units
17249 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17250
17251 @noindent
17252 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17253 one compilation
17254 unit per one source file. It computes line metrics for the whole source
17255 file, and it also computes syntax
17256 and complexity metrics for the file's outermost unit.
17257
17258 By default, @command{gnatmetric} will also compute all metrics for certain
17259 kinds of locally declared program units:
17260
17261 @itemize @bullet
17262 @item
17263 subprogram (and generic subprogram) bodies;
17264
17265 @item
17266 package (and generic package) specs and bodies;
17267
17268 @item
17269 task object and type specifications and bodies;
17270
17271 @item
17272 protected object and type specifications and bodies.
17273 @end itemize
17274
17275 @noindent
17276 These kinds of entities will be referred to as
17277 @emph{eligible local program units}, or simply @emph{eligible local units},
17278 @cindex Eligible local unit (for @command{gnatmetric})
17279 in the discussion below.
17280
17281 Note that a subprogram declaration, generic instantiation,
17282 or renaming declaration only receives metrics
17283 computation when it appear as the outermost entity
17284 in a source file.
17285
17286 Suppression of metrics computation for eligible local units can be
17287 obtained via the following switch:
17288
17289 @table @option
17290 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17291 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17292 Do not compute detailed metrics for eligible local program units
17293
17294 @end table
17295
17296 @node Specifying a set of metrics to compute
17297 @subsection Specifying a set of metrics to compute
17298
17299 @noindent
17300 By default all the metrics are computed and reported. The switches
17301 described in this subsection allow you to control, on an individual
17302 basis, whether metrics are computed and
17303 reported. If at least one positive metric
17304 switch is specified (that is, a switch that defines that a given
17305 metric or set of metrics is to be computed), then only
17306 explicitly specified metrics are reported.
17307
17308 @menu
17309 * Line Metrics Control::
17310 * Syntax Metrics Control::
17311 * Complexity Metrics Control::
17312 * Object-Oriented Metrics Control::
17313 @end menu
17314
17315 @node Line Metrics Control
17316 @subsubsection Line Metrics Control
17317 @cindex Line metrics control in @command{gnatmetric}
17318
17319 @noindent
17320 For any (legal) source file, and for each of its
17321 eligible local program units, @command{gnatmetric} computes the following
17322 metrics:
17323
17324 @itemize @bullet
17325 @item
17326 the total number of lines;
17327
17328 @item
17329 the total number of code lines (i.e., non-blank lines that are not comments)
17330
17331 @item
17332 the number of comment lines
17333
17334 @item
17335 the number of code lines containing end-of-line comments;
17336
17337 @item
17338 the comment percentage: the ratio between the number of lines that contain
17339 comments and the number of all non-blank lines, expressed as a percentage;
17340
17341 @item
17342 the number of empty lines and lines containing only space characters and/or
17343 format effectors (blank lines)
17344
17345 @item
17346 the average number of code lines in subprogram bodies, task bodies, entry
17347 bodies and statement sequences in package bodies (this metric is only computed
17348 across the whole set of the analyzed units)
17349
17350 @end itemize
17351
17352 @noindent
17353 @command{gnatmetric} sums the values of the line metrics for all the
17354 files being processed and then generates the cumulative results. The tool
17355 also computes for all the files being processed the average number of code
17356 lines in bodies.
17357
17358 You can use the following switches to select the specific line metrics
17359 to be computed and reported.
17360
17361 @table @option
17362 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17363
17364 @ifclear vms
17365 @cindex @option{--no-lines@var{x}}
17366 @end ifclear
17367
17368 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17369 Report all the line metrics
17370
17371 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17372 Do not report any of line metrics
17373
17374 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17375 Report the number of all lines
17376
17377 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17378 Do not report the number of all lines
17379
17380 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17381 Report the number of code lines
17382
17383 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17384 Do not report the number of code lines
17385
17386 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17387 Report the number of comment lines
17388
17389 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17390 Do not report the number of comment lines
17391
17392 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17393 Report the number of code lines containing
17394 end-of-line comments
17395
17396 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17397 Do not report the number of code lines containing
17398 end-of-line comments
17399
17400 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17401 Report the comment percentage in the program text
17402
17403 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17404 Do not report the comment percentage in the program text
17405
17406 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17407 Report the number of blank lines
17408
17409 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17410 Do not report the number of blank lines
17411
17412 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17413 Report the average number of code lines in subprogram bodies, task bodies,
17414 entry bodies and statement sequences in package bodies. The metric is computed
17415 and reported for the whole set of processed Ada sources only.
17416
17417 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17418 Do not report the average number of code lines in subprogram bodies,
17419 task bodies, entry bodies and statement sequences in package bodies.
17420
17421 @end table
17422
17423 @node Syntax Metrics Control
17424 @subsubsection Syntax Metrics Control
17425 @cindex Syntax metrics control in @command{gnatmetric}
17426
17427 @noindent
17428 @command{gnatmetric} computes various syntactic metrics for the
17429 outermost unit and for each eligible local unit:
17430
17431 @table @emph
17432 @item LSLOC (``Logical Source Lines Of Code'')
17433 The total number of declarations and the total number of statements
17434
17435 @item Maximal static nesting level of inner program units
17436 According to
17437 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17438 package, a task unit, a protected unit, a
17439 protected entry, a generic unit, or an explicitly declared subprogram other
17440 than an enumeration literal.''
17441
17442 @item Maximal nesting level of composite syntactic constructs
17443 This corresponds to the notion of the
17444 maximum nesting level in the GNAT built-in style checks
17445 (@pxref{Style Checking})
17446 @end table
17447
17448 @noindent
17449 For the outermost unit in the file, @command{gnatmetric} additionally computes
17450 the following metrics:
17451
17452 @table @emph
17453 @item Public subprograms
17454 This metric is computed for package specs. It is the
17455 number of subprograms and generic subprograms declared in the visible
17456 part (including the visible part of nested packages, protected objects, and
17457 protected types).
17458
17459 @item All subprograms
17460 This metric is computed for bodies and subunits. The
17461 metric is equal to a total number of subprogram bodies in the compilation
17462 unit.
17463 Neither generic instantiations nor renamings-as-a-body nor body stubs
17464 are counted. Any subprogram body is counted, independently of its nesting
17465 level and enclosing constructs. Generic bodies and bodies of protected
17466 subprograms are counted in the same way as ``usual'' subprogram bodies.
17467
17468 @item Public types
17469 This metric is computed for package specs and
17470 generic package declarations. It is the total number of types
17471 that can be referenced from outside this compilation unit, plus the
17472 number of types from all the visible parts of all the visible generic
17473 packages. Generic formal types are not counted.  Only types, not subtypes,
17474 are included.
17475
17476 @noindent
17477 Along with the total number of public types, the following
17478 types are counted and reported separately:
17479
17480 @itemize @bullet
17481 @item
17482 Abstract types
17483
17484 @item
17485 Root tagged types (abstract, non-abstract, private, non-private). Type
17486 extensions are @emph{not} counted
17487
17488 @item
17489 Private types (including private extensions)
17490
17491 @item
17492 Task types
17493
17494 @item
17495 Protected types
17496
17497 @end itemize
17498
17499 @item All types
17500 This metric is computed for any compilation unit. It is equal to the total
17501 number of the declarations of different types given in the compilation unit.
17502 The private and the corresponding full type declaration are counted as one
17503 type declaration. Incomplete type declarations and generic formal types
17504 are not counted.
17505 No distinction is made among different kinds of types (abstract,
17506 private etc.); the total number of types is computed and reported.
17507
17508 @end table
17509
17510 @noindent
17511 By default, all the syntax metrics are computed and reported. You can use the
17512 following switches to select specific syntax metrics.
17513
17514 @table @option
17515
17516 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17517
17518 @ifclear vms
17519 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17520 @end ifclear
17521
17522 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17523 Report all the syntax metrics
17524
17525 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17526 Do not report any of syntax metrics
17527
17528 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17529 Report the total number of declarations
17530
17531 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17532 Do not report the total number of declarations
17533
17534 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17535 Report the total number of statements
17536
17537 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17538 Do not report the total number of statements
17539
17540 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17541 Report the number of public subprograms in a compilation unit
17542
17543 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17544 Do not report the number of public subprograms in a compilation unit
17545
17546 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17547 Report the number of all the subprograms in a compilation unit
17548
17549 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17550 Do not report the number of all the subprograms in a compilation unit
17551
17552 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17553 Report the number of public types in a compilation unit
17554
17555 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17556 Do not report the number of public types in a compilation unit
17557
17558 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17559 Report the number of all the types in a compilation unit
17560
17561 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17562 Do not report the number of all the types in a compilation unit
17563
17564 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17565 Report the maximal program unit nesting level
17566
17567 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17568 Do not report the maximal program unit nesting level
17569
17570 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17571 Report the maximal construct nesting level
17572
17573 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17574 Do not report the maximal construct nesting level
17575
17576 @end table
17577
17578 @node Complexity Metrics Control
17579 @subsubsection Complexity Metrics Control
17580 @cindex Complexity metrics control in @command{gnatmetric}
17581
17582 @noindent
17583 For a program unit that is an executable body (a subprogram body (including
17584 generic bodies), task body, entry body or a package body containing
17585 its own statement sequence) @command{gnatmetric} computes the following
17586 complexity metrics:
17587
17588 @itemize @bullet
17589 @item
17590 McCabe cyclomatic complexity;
17591
17592 @item
17593 McCabe essential complexity;
17594
17595 @item
17596 maximal loop nesting level
17597
17598 @end itemize
17599
17600 @noindent
17601 The McCabe complexity metrics are defined
17602 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17603
17604 According to McCabe, both control statements and short-circuit control forms
17605 should be taken into account when computing cyclomatic complexity. For each
17606 body, we compute three metric values:
17607
17608 @itemize @bullet
17609 @item
17610 the complexity introduced by control
17611 statements only, without taking into account short-circuit forms,
17612
17613 @item
17614 the complexity introduced by short-circuit control forms only, and
17615
17616 @item
17617 the total
17618 cyclomatic complexity, which is the sum of these two values.
17619 @end itemize
17620
17621 @noindent
17622 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17623 the code in the exception handlers and in all the nested program units.
17624
17625 By default, all the complexity metrics are computed and reported.
17626 For more fine-grained control you can use
17627 the following switches:
17628
17629 @table @option
17630 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17631
17632 @ifclear vms
17633 @cindex @option{--no-complexity@var{x}}
17634 @end ifclear
17635
17636 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17637 Report all the complexity metrics
17638
17639 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17640 Do not report any of complexity metrics
17641
17642 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17643 Report the McCabe Cyclomatic Complexity
17644
17645 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17646 Do not report the McCabe Cyclomatic Complexity
17647
17648 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17649 Report the Essential Complexity
17650
17651 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17652 Do not report the Essential Complexity
17653
17654 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17655 Report maximal loop nesting level
17656
17657 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17658 Do not report maximal loop nesting level
17659
17660 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17661 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17662 task bodies, entry bodies and statement sequences in package bodies.
17663 The metric is computed and reported for whole set of processed Ada sources
17664 only.
17665
17666 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17667 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17668 bodies, task bodies, entry bodies and statement sequences in package bodies
17669
17670 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17671 @item ^-ne^/NO_EXITS_AS_GOTOS^
17672 Do not consider @code{exit} statements as @code{goto}s when
17673 computing Essential Complexity
17674
17675 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17676 Report the extra exit points for subprogram bodies. As an exit point, this
17677 metric counts @code{return} statements and raise statements in case when the
17678 raised exception is not handled in the same body. In case of a function this
17679 metric subtracts 1 from the number of exit points, because a function body
17680 must contain at least one @code{return} statement.
17681
17682 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17683 Do not report the extra exit points for subprogram bodies
17684 @end table
17685
17686
17687 @node Object-Oriented Metrics Control
17688 @subsubsection Object-Oriented Metrics Control
17689 @cindex Object-Oriented metrics control in @command{gnatmetric}
17690
17691 @noindent
17692 @cindex Coupling metrics (in in @command{gnatmetric})
17693 Coupling metrics are object-oriented metrics that measure the
17694 dependencies between a given class (or a group of classes) and the
17695 ``external world'' (that is, the other classes in the program). In this
17696 subsection the term ``class'' is used in its
17697 traditional object-oriented programming sense
17698 (an instantiable module that contains data and/or method members).
17699 A @emph{category} (of classes)
17700 is a group of closely related classes that are reused and/or
17701 modified together.
17702
17703 A class @code{K}'s @emph{efferent coupling} is the number of classes
17704 that @code{K} depends upon.
17705 A category's efferent coupling is the number of classes outside the
17706 category that the classes inside the category depend upon.
17707
17708 A class @code{K}'s @emph{afferent coupling} is the number of classes
17709 that depend upon @code{K}.
17710 A category's afferent coupling is the number of classes outside the
17711 category that depend on classes belonging to the category.
17712
17713 Ada's implementation of the object-oriented paradigm does not use the
17714 traditional class notion, so the definition of the coupling
17715 metrics for Ada maps the class and class category notions
17716 onto Ada constructs.
17717
17718 For the coupling metrics, several kinds of modules -- a library package,
17719 a library generic package, and a library generic package instantiation --
17720 that define a tagged type or an interface type are
17721 considered to be a class. A category consists of a library package (or
17722 a library generic package) that defines a tagged or an interface type,
17723 together with all its descendant (generic) packages that define tagged
17724 or interface types. For any package counted as a class,
17725 its body and subunits (if any) are considered
17726 together with its spec when counting the dependencies, and coupling
17727 metrics are reported for spec units only. For dependencies
17728 between classes, the Ada semantic dependencies are considered.
17729 For coupling metrics, only dependencies on units that are considered as
17730 classes, are considered.
17731
17732 When computing coupling metrics, @command{gnatmetric} counts only
17733 dependencies between units that are arguments of the gnatmetric call.
17734 Coupling metrics are program-wide (or project-wide) metrics, so to
17735 get a valid result, you should call @command{gnatmetric} for
17736 the whole set of sources that make up your program. It can be done
17737 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17738 option (see See @ref{The GNAT Driver and Project Files} for details.
17739
17740 By default, all the coupling metrics are disabled. You can use the following
17741 switches to specify the coupling metrics to be computed and reported:
17742
17743 @table @option
17744
17745 @ifclear vms
17746 @cindex @option{--package@var{x}} (@command{gnatmetric})
17747 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17748 @cindex @option{--category@var{x}} (@command{gnatmetric})
17749 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17750 @end ifclear
17751
17752 @ifset vms
17753 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17754 @end ifset
17755
17756 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17757 Report all the coupling metrics
17758
17759 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17760 Do not report any of  metrics
17761
17762 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17763 Report package efferent coupling
17764
17765 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17766 Do not report package efferent coupling
17767
17768 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17769 Report package afferent coupling
17770
17771 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17772 Do not report package afferent coupling
17773
17774 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17775 Report category efferent coupling
17776
17777 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17778 Do not report category efferent coupling
17779
17780 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17781 Report category afferent coupling
17782
17783 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17784 Do not report category afferent coupling
17785
17786 @end table
17787
17788 @node Other gnatmetric Switches
17789 @subsection Other @code{gnatmetric} Switches
17790
17791 @noindent
17792 Additional @command{gnatmetric} switches are as follows:
17793
17794 @table @option
17795 @item ^-files @var{filename}^/FILES=@var{filename}^
17796 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17797 Take the argument source files from the specified file. This file should be an
17798 ordinary text file containing file names separated by spaces or
17799 line breaks. You can use this switch more then once in the same call to
17800 @command{gnatmetric}. You also can combine this switch with
17801 an explicit list of files.
17802
17803 @item ^-v^/VERBOSE^
17804 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17805 Verbose mode;
17806 @command{gnatmetric} generates version information and then
17807 a trace of sources being processed.
17808
17809 @item ^-dv^/DEBUG_OUTPUT^
17810 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17811 Debug mode;
17812 @command{gnatmetric} generates various messages useful to understand what
17813 happens during the metrics computation
17814
17815 @item ^-q^/QUIET^
17816 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17817 Quiet mode.
17818 @end table
17819
17820 @node Generate project-wide metrics
17821 @subsection Generate project-wide metrics
17822
17823 In order to compute metrics on all units of a given project, you can use
17824 the @command{gnat} driver along with the @option{-P} option:
17825 @smallexample
17826    gnat metric -Pproj
17827 @end smallexample
17828
17829 @noindent
17830 If the project @code{proj} depends upon other projects, you can compute
17831 the metrics on the project closure using the @option{-U} option:
17832 @smallexample
17833    gnat metric -Pproj -U
17834 @end smallexample
17835
17836 @noindent
17837 Finally, if not all the units are relevant to a particular main
17838 program in the project closure, you can generate metrics for the set
17839 of units needed to create a given main program (unit closure) using
17840 the @option{-U} option followed by the name of the main unit:
17841 @smallexample
17842    gnat metric -Pproj -U main
17843 @end smallexample
17844
17845
17846 @c ***********************************
17847 @node File Name Krunching Using gnatkr
17848 @chapter File Name Krunching Using @code{gnatkr}
17849 @findex gnatkr
17850
17851 @noindent
17852 This chapter discusses the method used by the compiler to shorten
17853 the default file names chosen for Ada units so that they do not
17854 exceed the maximum length permitted. It also describes the
17855 @code{gnatkr} utility that can be used to determine the result of
17856 applying this shortening.
17857 @menu
17858 * About gnatkr::
17859 * Using gnatkr::
17860 * Krunching Method::
17861 * Examples of gnatkr Usage::
17862 @end menu
17863
17864 @node About gnatkr
17865 @section About @code{gnatkr}
17866
17867 @noindent
17868 The default file naming rule in GNAT
17869 is that the file name must be derived from
17870 the unit name. The exact default rule is as follows:
17871 @itemize @bullet
17872 @item
17873 Take the unit name and replace all dots by hyphens.
17874 @item
17875 If such a replacement occurs in the
17876 second character position of a name, and the first character is
17877 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17878 then replace the dot by the character
17879 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17880 instead of a minus.
17881 @end itemize
17882 The reason for this exception is to avoid clashes
17883 with the standard names for children of System, Ada, Interfaces,
17884 and GNAT, which use the prefixes
17885 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17886 respectively.
17887
17888 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17889 switch of the compiler activates a ``krunching''
17890 circuit that limits file names to nn characters (where nn is a decimal
17891 integer). For example, using OpenVMS,
17892 where the maximum file name length is
17893 39, the value of nn is usually set to 39, but if you want to generate
17894 a set of files that would be usable if ported to a system with some
17895 different maximum file length, then a different value can be specified.
17896 The default value of 39 for OpenVMS need not be specified.
17897
17898 The @code{gnatkr} utility can be used to determine the krunched name for
17899 a given file, when krunched to a specified maximum length.
17900
17901 @node Using gnatkr
17902 @section Using @code{gnatkr}
17903
17904 @noindent
17905 The @code{gnatkr} command has the form
17906
17907 @ifclear vms
17908 @smallexample
17909 $ gnatkr @var{name} @ovar{length}
17910 @end smallexample
17911 @end ifclear
17912
17913 @ifset vms
17914 @smallexample
17915 $ gnatkr @var{name} /COUNT=nn
17916 @end smallexample
17917 @end ifset
17918
17919 @noindent
17920 @var{name} is the uncrunched file name, derived from the name of the unit
17921 in the standard manner described in the previous section (i.e., in particular
17922 all dots are replaced by hyphens). The file name may or may not have an
17923 extension (defined as a suffix of the form period followed by arbitrary
17924 characters other than period). If an extension is present then it will
17925 be preserved in the output. For example, when krunching @file{hellofile.ads}
17926 to eight characters, the result will be hellofil.ads.
17927
17928 Note: for compatibility with previous versions of @code{gnatkr} dots may
17929 appear in the name instead of hyphens, but the last dot will always be
17930 taken as the start of an extension. So if @code{gnatkr} is given an argument
17931 such as @file{Hello.World.adb} it will be treated exactly as if the first
17932 period had been a hyphen, and for example krunching to eight characters
17933 gives the result @file{hellworl.adb}.
17934
17935 Note that the result is always all lower case (except on OpenVMS where it is
17936 all upper case). Characters of the other case are folded as required.
17937
17938 @var{length} represents the length of the krunched name. The default
17939 when no argument is given is ^8^39^ characters. A length of zero stands for
17940 unlimited, in other words do not chop except for system files where the
17941 implied crunching length is always eight characters.
17942
17943 @noindent
17944 The output is the krunched name. The output has an extension only if the
17945 original argument was a file name with an extension.
17946
17947 @node Krunching Method
17948 @section Krunching Method
17949
17950 @noindent
17951 The initial file name is determined by the name of the unit that the file
17952 contains. The name is formed by taking the full expanded name of the
17953 unit and replacing the separating dots with hyphens and
17954 using ^lowercase^uppercase^
17955 for all letters, except that a hyphen in the second character position is
17956 replaced by a ^tilde^dollar sign^ if the first character is
17957 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17958 The extension is @code{.ads} for a
17959 spec and @code{.adb} for a body.
17960 Krunching does not affect the extension, but the file name is shortened to
17961 the specified length by following these rules:
17962
17963 @itemize @bullet
17964 @item
17965 The name is divided into segments separated by hyphens, tildes or
17966 underscores and all hyphens, tildes, and underscores are
17967 eliminated. If this leaves the name short enough, we are done.
17968
17969 @item
17970 If the name is too long, the longest segment is located (left-most
17971 if there are two of equal length), and shortened by dropping
17972 its last character. This is repeated until the name is short enough.
17973
17974 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17975 to fit the name into 8 characters as required by some operating systems.
17976
17977 @smallexample
17978 our-strings-wide_fixed 22
17979 our strings wide fixed 19
17980 our string  wide fixed 18
17981 our strin   wide fixed 17
17982 our stri    wide fixed 16
17983 our stri    wide fixe  15
17984 our str     wide fixe  14
17985 our str     wid  fixe  13
17986 our str     wid  fix   12
17987 ou  str     wid  fix   11
17988 ou  st      wid  fix   10
17989 ou  st      wi   fix   9
17990 ou  st      wi   fi    8
17991 Final file name: oustwifi.adb
17992 @end smallexample
17993
17994 @item
17995 The file names for all predefined units are always krunched to eight
17996 characters. The krunching of these predefined units uses the following
17997 special prefix replacements:
17998
17999 @table @file
18000 @item ada-
18001 replaced by @file{^a^A^-}
18002
18003 @item gnat-
18004 replaced by @file{^g^G^-}
18005
18006 @item interfaces-
18007 replaced by @file{^i^I^-}
18008
18009 @item system-
18010 replaced by @file{^s^S^-}
18011 @end table
18012
18013 These system files have a hyphen in the second character position. That
18014 is why normal user files replace such a character with a
18015 ^tilde^dollar sign^, to
18016 avoid confusion with system file names.
18017
18018 As an example of this special rule, consider
18019 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18020
18021 @smallexample
18022 ada-strings-wide_fixed 22
18023 a-  strings wide fixed 18
18024 a-  string  wide fixed 17
18025 a-  strin   wide fixed 16
18026 a-  stri    wide fixed 15
18027 a-  stri    wide fixe  14
18028 a-  str     wide fixe  13
18029 a-  str     wid  fixe  12
18030 a-  str     wid  fix   11
18031 a-  st      wid  fix   10
18032 a-  st      wi   fix   9
18033 a-  st      wi   fi    8
18034 Final file name: a-stwifi.adb
18035 @end smallexample
18036 @end itemize
18037
18038 Of course no file shortening algorithm can guarantee uniqueness over all
18039 possible unit names, and if file name krunching is used then it is your
18040 responsibility to ensure that no name clashes occur. The utility
18041 program @code{gnatkr} is supplied for conveniently determining the
18042 krunched name of a file.
18043
18044 @node Examples of gnatkr Usage
18045 @section Examples of @code{gnatkr} Usage
18046
18047 @smallexample
18048 @iftex
18049 @leftskip=0cm
18050 @end iftex
18051 @ifclear vms
18052 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18053 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18054 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18055 $ gnatkr grandparent-parent-child     --> grparchi
18056 @end ifclear
18057 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18058 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18059 @end smallexample
18060
18061 @node Preprocessing Using gnatprep
18062 @chapter Preprocessing Using @code{gnatprep}
18063 @findex gnatprep
18064
18065 @noindent
18066 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18067 preprocessing.
18068 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18069 special GNAT features.
18070 For further discussion of conditional compilation in general, see
18071 @ref{Conditional Compilation}.
18072
18073 @menu
18074 * Preprocessing Symbols::
18075 * Using gnatprep::
18076 * Switches for gnatprep::
18077 * Form of Definitions File::
18078 * Form of Input Text for gnatprep::
18079 @end menu
18080
18081 @node Preprocessing Symbols
18082 @section Preprocessing Symbols
18083
18084 @noindent
18085 Preprocessing symbols are defined in definition files and referred to in
18086 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18087 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18088 all characters need to be in the ASCII set (no accented letters).
18089
18090 @node Using gnatprep
18091 @section Using @code{gnatprep}
18092
18093 @noindent
18094 To call @code{gnatprep} use
18095
18096 @smallexample
18097 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18098 @end smallexample
18099
18100 @noindent
18101 where
18102 @table @var
18103 @item switches
18104 is an optional sequence of switches as described in the next section.
18105
18106 @item infile
18107 is the full name of the input file, which is an Ada source
18108 file containing preprocessor directives.
18109
18110 @item outfile
18111 is the full name of the output file, which is an Ada source
18112 in standard Ada form. When used with GNAT, this file name will
18113 normally have an ads or adb suffix.
18114
18115 @item deffile
18116 is the full name of a text file containing definitions of
18117 preprocessing symbols to be referenced by the preprocessor. This argument is
18118 optional, and can be replaced by the use of the @option{-D} switch.
18119
18120 @end table
18121
18122 @node Switches for gnatprep
18123 @section Switches for @code{gnatprep}
18124
18125 @table @option
18126 @c !sort!
18127
18128 @item ^-b^/BLANK_LINES^
18129 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18130 Causes both preprocessor lines and the lines deleted by
18131 preprocessing to be replaced by blank lines in the output source file,
18132 preserving line numbers in the output file.
18133
18134 @item ^-c^/COMMENTS^
18135 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18136 Causes both preprocessor lines and the lines deleted
18137 by preprocessing to be retained in the output source as comments marked
18138 with the special string @code{"--! "}. This option will result in line numbers
18139 being preserved in the output file.
18140
18141 @item ^-C^/REPLACE_IN_COMMENTS^
18142 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18143 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18144 If this option is specified, then comments are scanned and any $symbol
18145 substitutions performed as in program text. This is particularly useful
18146 when structured comments are used (e.g., when writing programs in the
18147 SPARK dialect of Ada). Note that this switch is not available when
18148 doing integrated preprocessing (it would be useless in this context
18149 since comments are ignored by the compiler in any case).
18150
18151 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18152 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18153 Defines a new preprocessing symbol, associated with value. If no value is given
18154 on the command line, then symbol is considered to be @code{True}. This switch
18155 can be used in place of a definition file.
18156
18157 @ifset vms
18158 @item /REMOVE
18159 @cindex @option{/REMOVE} (@command{gnatprep})
18160 This is the default setting which causes lines deleted by preprocessing
18161 to be entirely removed from the output file.
18162 @end ifset
18163
18164 @item ^-r^/REFERENCE^
18165 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18166 Causes a @code{Source_Reference} pragma to be generated that
18167 references the original input file, so that error messages will use
18168 the file name of this original file. The use of this switch implies
18169 that preprocessor lines are not to be removed from the file, so its
18170 use will force @option{^-b^/BLANK_LINES^} mode if
18171 @option{^-c^/COMMENTS^}
18172 has not been specified explicitly.
18173
18174 Note that if the file to be preprocessed contains multiple units, then
18175 it will be necessary to @code{gnatchop} the output file from
18176 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18177 in the preprocessed file, it will be respected by
18178 @code{gnatchop ^-r^/REFERENCE^}
18179 so that the final chopped files will correctly refer to the original
18180 input source file for @code{gnatprep}.
18181
18182 @item ^-s^/SYMBOLS^
18183 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18184 Causes a sorted list of symbol names and values to be
18185 listed on the standard output file.
18186
18187 @item ^-u^/UNDEFINED^
18188 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18189 Causes undefined symbols to be treated as having the value FALSE in the context
18190 of a preprocessor test. In the absence of this option, an undefined symbol in
18191 a @code{#if} or @code{#elsif} test will be treated as an error.
18192
18193 @end table
18194
18195 @ifclear vms
18196 @noindent
18197 Note: if neither @option{-b} nor @option{-c} is present,
18198 then preprocessor lines and
18199 deleted lines are completely removed from the output, unless -r is
18200 specified, in which case -b is assumed.
18201 @end ifclear
18202
18203 @node Form of Definitions File
18204 @section Form of Definitions File
18205
18206 @noindent
18207 The definitions file contains lines of the form
18208
18209 @smallexample
18210 symbol := value
18211 @end smallexample
18212
18213 @noindent
18214 where symbol is a preprocessing symbol, and value is one of the following:
18215
18216 @itemize @bullet
18217 @item
18218 Empty, corresponding to a null substitution
18219 @item
18220 A string literal using normal Ada syntax
18221 @item
18222 Any sequence of characters from the set
18223 (letters, digits, period, underline).
18224 @end itemize
18225
18226 @noindent
18227 Comment lines may also appear in the definitions file, starting with
18228 the usual @code{--},
18229 and comments may be added to the definitions lines.
18230
18231 @node Form of Input Text for gnatprep
18232 @section Form of Input Text for @code{gnatprep}
18233
18234 @noindent
18235 The input text may contain preprocessor conditional inclusion lines,
18236 as well as general symbol substitution sequences.
18237
18238 The preprocessor conditional inclusion commands have the form
18239
18240 @smallexample
18241 @group
18242 @cartouche
18243 #if @i{expression} @r{[}then@r{]}
18244    lines
18245 #elsif @i{expression} @r{[}then@r{]}
18246    lines
18247 #elsif @i{expression} @r{[}then@r{]}
18248    lines
18249 @dots{}
18250 #else
18251    lines
18252 #end if;
18253 @end cartouche
18254 @end group
18255 @end smallexample
18256
18257 @noindent
18258 In this example, @i{expression} is defined by the following grammar:
18259 @smallexample
18260 @i{expression} ::=  <symbol>
18261 @i{expression} ::=  <symbol> = "<value>"
18262 @i{expression} ::=  <symbol> = <symbol>
18263 @i{expression} ::=  <symbol> 'Defined
18264 @i{expression} ::=  not @i{expression}
18265 @i{expression} ::=  @i{expression} and @i{expression}
18266 @i{expression} ::=  @i{expression} or @i{expression}
18267 @i{expression} ::=  @i{expression} and then @i{expression}
18268 @i{expression} ::=  @i{expression} or else @i{expression}
18269 @i{expression} ::=  ( @i{expression} )
18270 @end smallexample
18271
18272 The following restriction exists: it is not allowed to have "and" or "or"
18273 following "not" in the same expression without parentheses. For example, this
18274 is not allowed:
18275
18276 @smallexample
18277    not X or Y
18278 @end smallexample
18279
18280 This should be one of the following:
18281
18282 @smallexample
18283    (not X) or Y
18284    not (X or Y)
18285 @end smallexample
18286
18287 @noindent
18288 For the first test (@i{expression} ::= <symbol>) the symbol must have
18289 either the value true or false, that is to say the right-hand of the
18290 symbol definition must be one of the (case-insensitive) literals
18291 @code{True} or @code{False}. If the value is true, then the
18292 corresponding lines are included, and if the value is false, they are
18293 excluded.
18294
18295 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18296 the symbol has been defined in the definition file or by a @option{-D}
18297 switch on the command line. Otherwise, the test is false.
18298
18299 The equality tests are case insensitive, as are all the preprocessor lines.
18300
18301 If the symbol referenced is not defined in the symbol definitions file,
18302 then the effect depends on whether or not switch @option{-u}
18303 is specified. If so, then the symbol is treated as if it had the value
18304 false and the test fails. If this switch is not specified, then
18305 it is an error to reference an undefined symbol. It is also an error to
18306 reference a symbol that is defined with a value other than @code{True}
18307 or @code{False}.
18308
18309 The use of the @code{not} operator inverts the sense of this logical test.
18310 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18311 operators, without parentheses. For example, "if not X or Y then" is not
18312 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18313
18314 The @code{then} keyword is optional as shown
18315
18316 The @code{#} must be the first non-blank character on a line, but
18317 otherwise the format is free form. Spaces or tabs may appear between
18318 the @code{#} and the keyword. The keywords and the symbols are case
18319 insensitive as in normal Ada code. Comments may be used on a
18320 preprocessor line, but other than that, no other tokens may appear on a
18321 preprocessor line. Any number of @code{elsif} clauses can be present,
18322 including none at all. The @code{else} is optional, as in Ada.
18323
18324 The @code{#} marking the start of a preprocessor line must be the first
18325 non-blank character on the line, i.e., it must be preceded only by
18326 spaces or horizontal tabs.
18327
18328 Symbol substitution outside of preprocessor lines is obtained by using
18329 the sequence
18330
18331 @smallexample
18332 $symbol
18333 @end smallexample
18334
18335 @noindent
18336 anywhere within a source line, except in a comment or within a
18337 string literal. The identifier
18338 following the @code{$} must match one of the symbols defined in the symbol
18339 definition file, and the result is to substitute the value of the
18340 symbol in place of @code{$symbol} in the output file.
18341
18342 Note that although the substitution of strings within a string literal
18343 is not possible, it is possible to have a symbol whose defined value is
18344 a string literal. So instead of setting XYZ to @code{hello} and writing:
18345
18346 @smallexample
18347 Header : String := "$XYZ";
18348 @end smallexample
18349
18350 @noindent
18351 you should set XYZ to @code{"hello"} and write:
18352
18353 @smallexample
18354 Header : String := $XYZ;
18355 @end smallexample
18356
18357 @noindent
18358 and then the substitution will occur as desired.
18359
18360 @ifset vms
18361 @node The GNAT Run-Time Library Builder gnatlbr
18362 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18363 @findex gnatlbr
18364 @cindex Library builder
18365
18366 @noindent
18367 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18368 supplied configuration pragmas.
18369
18370 @menu
18371 * Running gnatlbr::
18372 * Switches for gnatlbr::
18373 * Examples of gnatlbr Usage::
18374 @end menu
18375
18376 @node Running gnatlbr
18377 @section Running @code{gnatlbr}
18378
18379 @noindent
18380 The @code{gnatlbr} command has the form
18381
18382 @smallexample
18383 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18384 @end smallexample
18385
18386 @node Switches for gnatlbr
18387 @section Switches for @code{gnatlbr}
18388
18389 @noindent
18390 @code{gnatlbr} recognizes the following switches:
18391
18392 @table @option
18393 @c !sort!
18394 @item /CREATE=directory
18395 @cindex @code{/CREATE} (@code{gnatlbr})
18396 Create the new run-time library in the specified directory.
18397
18398 @item /SET=directory
18399 @cindex @code{/SET} (@code{gnatlbr})
18400 Make the library in the specified directory the current run-time library.
18401
18402 @item /DELETE=directory
18403 @cindex @code{/DELETE} (@code{gnatlbr})
18404 Delete the run-time library in the specified directory.
18405
18406 @item /CONFIG=file
18407 @cindex @code{/CONFIG} (@code{gnatlbr})
18408 With /CREATE: Use the configuration pragmas in the specified file when
18409 building the library.
18410
18411 With /SET: Use the configuration pragmas in the specified file when
18412 compiling.
18413
18414 @end table
18415
18416 @node Examples of gnatlbr Usage
18417 @section Example of @code{gnatlbr} Usage
18418
18419 @smallexample
18420 Contents of VAXFLOAT.ADC:
18421 pragma Float_Representation (VAX_Float);
18422
18423 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18424
18425 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18426
18427 @end smallexample
18428 @end ifset
18429
18430 @node The GNAT Library Browser gnatls
18431 @chapter The GNAT Library Browser @code{gnatls}
18432 @findex gnatls
18433 @cindex Library browser
18434
18435 @noindent
18436 @code{gnatls} is a tool that outputs information about compiled
18437 units. It gives the relationship between objects, unit names and source
18438 files. It can also be used to check the source dependencies of a unit
18439 as well as various characteristics.
18440
18441 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18442 driver (see @ref{The GNAT Driver and Project Files}).
18443
18444 @menu
18445 * Running gnatls::
18446 * Switches for gnatls::
18447 * Examples of gnatls Usage::
18448 @end menu
18449
18450 @node Running gnatls
18451 @section Running @code{gnatls}
18452
18453 @noindent
18454 The @code{gnatls} command has the form
18455
18456 @smallexample
18457 $ gnatls switches @var{object_or_ali_file}
18458 @end smallexample
18459
18460 @noindent
18461 The main argument is the list of object or @file{ali} files
18462 (@pxref{The Ada Library Information Files})
18463 for which information is requested.
18464
18465 In normal mode, without additional option, @code{gnatls} produces a
18466 four-column listing. Each line represents information for a specific
18467 object. The first column gives the full path of the object, the second
18468 column gives the name of the principal unit in this object, the third
18469 column gives the status of the source and the fourth column gives the
18470 full path of the source representing this unit.
18471 Here is a simple example of use:
18472
18473 @smallexample
18474 $ gnatls *.o
18475 ^./^[]^demo1.o            demo1            DIF demo1.adb
18476 ^./^[]^demo2.o            demo2             OK demo2.adb
18477 ^./^[]^hello.o            h1                OK hello.adb
18478 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18479 ^./^[]^instr.o            instr             OK instr.adb
18480 ^./^[]^tef.o              tef              DIF tef.adb
18481 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18482 ^./^[]^tgef.o             tgef             DIF tgef.adb
18483 @end smallexample
18484
18485 @noindent
18486 The first line can be interpreted as follows: the main unit which is
18487 contained in
18488 object file @file{demo1.o} is demo1, whose main source is in
18489 @file{demo1.adb}. Furthermore, the version of the source used for the
18490 compilation of demo1 has been modified (DIF). Each source file has a status
18491 qualifier which can be:
18492
18493 @table @code
18494 @item OK (unchanged)
18495 The version of the source file used for the compilation of the
18496 specified unit corresponds exactly to the actual source file.
18497
18498 @item MOK (slightly modified)
18499 The version of the source file used for the compilation of the
18500 specified unit differs from the actual source file but not enough to
18501 require recompilation. If you use gnatmake with the qualifier
18502 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18503 MOK will not be recompiled.
18504
18505 @item DIF (modified)
18506 No version of the source found on the path corresponds to the source
18507 used to build this object.
18508
18509 @item ??? (file not found)
18510 No source file was found for this unit.
18511
18512 @item HID (hidden,  unchanged version not first on PATH)
18513 The version of the source that corresponds exactly to the source used
18514 for compilation has been found on the path but it is hidden by another
18515 version of the same source that has been modified.
18516
18517 @end table
18518
18519 @node Switches for gnatls
18520 @section Switches for @code{gnatls}
18521
18522 @noindent
18523 @code{gnatls} recognizes the following switches:
18524
18525 @table @option
18526 @c !sort!
18527 @cindex @option{--version} @command{gnatls}
18528 Display Copyright and version, then exit disregarding all other options.
18529
18530 @item --help
18531 @cindex @option{--help} @command{gnatls}
18532 If @option{--version} was not used, display usage, then exit disregarding
18533 all other options.
18534
18535 @item ^-a^/ALL_UNITS^
18536 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18537 Consider all units, including those of the predefined Ada library.
18538 Especially useful with @option{^-d^/DEPENDENCIES^}.
18539
18540 @item ^-d^/DEPENDENCIES^
18541 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18542 List sources from which specified units depend on.
18543
18544 @item ^-h^/OUTPUT=OPTIONS^
18545 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18546 Output the list of options.
18547
18548 @item ^-o^/OUTPUT=OBJECTS^
18549 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18550 Only output information about object files.
18551
18552 @item ^-s^/OUTPUT=SOURCES^
18553 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18554 Only output information about source files.
18555
18556 @item ^-u^/OUTPUT=UNITS^
18557 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18558 Only output information about compilation units.
18559
18560 @item ^-files^/FILES^=@var{file}
18561 @cindex @option{^-files^/FILES^} (@code{gnatls})
18562 Take as arguments the files listed in text file @var{file}.
18563 Text file @var{file} may contain empty lines that are ignored.
18564 Each nonempty line should contain the name of an existing file.
18565 Several such switches may be specified simultaneously.
18566
18567 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18568 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18569 @itemx ^-I^/SEARCH=^@var{dir}
18570 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18571 @itemx -nostdinc
18572 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18573 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18574 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18575 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18576 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18577 flags (@pxref{Switches for gnatmake}).
18578
18579 @item --RTS=@var{rts-path}
18580 @cindex @option{--RTS} (@code{gnatls})
18581 Specifies the default location of the runtime library. Same meaning as the
18582 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18583
18584 @item ^-v^/OUTPUT=VERBOSE^
18585 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18586 Verbose mode. Output the complete source, object and project paths. Do not use
18587 the default column layout but instead use long format giving as much as
18588 information possible on each requested units, including special
18589 characteristics such as:
18590
18591 @table @code
18592 @item  Preelaborable
18593 The unit is preelaborable in the Ada sense.
18594
18595 @item No_Elab_Code
18596 No elaboration code has been produced by the compiler for this unit.
18597
18598 @item Pure
18599 The unit is pure in the Ada sense.
18600
18601 @item Elaborate_Body
18602 The unit contains a pragma Elaborate_Body.
18603
18604 @item Remote_Types
18605 The unit contains a pragma Remote_Types.
18606
18607 @item Shared_Passive
18608 The unit contains a pragma Shared_Passive.
18609
18610 @item Predefined
18611 This unit is part of the predefined environment and cannot be modified
18612 by the user.
18613
18614 @item Remote_Call_Interface
18615 The unit contains a pragma Remote_Call_Interface.
18616
18617 @end table
18618
18619 @end table
18620
18621 @node Examples of gnatls Usage
18622 @section Example of @code{gnatls} Usage
18623 @ifclear vms
18624
18625 @noindent
18626 Example of using the verbose switch. Note how the source and
18627 object paths are affected by the -I switch.
18628
18629 @smallexample
18630 $ gnatls -v -I.. demo1.o
18631
18632 GNATLS 5.03w (20041123-34)
18633 Copyright 1997-2004 Free Software Foundation, Inc.
18634
18635 Source Search Path:
18636    <Current_Directory>
18637    ../
18638    /home/comar/local/adainclude/
18639
18640 Object Search Path:
18641    <Current_Directory>
18642    ../
18643    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18644
18645 Project Search Path:
18646    <Current_Directory>
18647    /home/comar/local/lib/gnat/
18648
18649 ./demo1.o
18650    Unit =>
18651      Name   => demo1
18652      Kind   => subprogram body
18653      Flags  => No_Elab_Code
18654      Source => demo1.adb    modified
18655 @end smallexample
18656
18657 @noindent
18658 The following is an example of use of the dependency list.
18659 Note the use of the -s switch
18660 which gives a straight list of source files. This can be useful for
18661 building specialized scripts.
18662
18663 @smallexample
18664 $ gnatls -d demo2.o
18665 ./demo2.o   demo2        OK demo2.adb
18666                          OK gen_list.ads
18667                          OK gen_list.adb
18668                          OK instr.ads
18669                          OK instr-child.ads
18670
18671 $ gnatls -d -s -a demo1.o
18672 demo1.adb
18673 /home/comar/local/adainclude/ada.ads
18674 /home/comar/local/adainclude/a-finali.ads
18675 /home/comar/local/adainclude/a-filico.ads
18676 /home/comar/local/adainclude/a-stream.ads
18677 /home/comar/local/adainclude/a-tags.ads
18678 gen_list.ads
18679 gen_list.adb
18680 /home/comar/local/adainclude/gnat.ads
18681 /home/comar/local/adainclude/g-io.ads
18682 instr.ads
18683 /home/comar/local/adainclude/system.ads
18684 /home/comar/local/adainclude/s-exctab.ads
18685 /home/comar/local/adainclude/s-finimp.ads
18686 /home/comar/local/adainclude/s-finroo.ads
18687 /home/comar/local/adainclude/s-secsta.ads
18688 /home/comar/local/adainclude/s-stalib.ads
18689 /home/comar/local/adainclude/s-stoele.ads
18690 /home/comar/local/adainclude/s-stratt.ads
18691 /home/comar/local/adainclude/s-tasoli.ads
18692 /home/comar/local/adainclude/s-unstyp.ads
18693 /home/comar/local/adainclude/unchconv.ads
18694 @end smallexample
18695 @end ifclear
18696
18697 @ifset vms
18698 @smallexample
18699 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18700
18701 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18702 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18703 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18704 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18705 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18706 demo1.adb
18707 gen_list.ads
18708 gen_list.adb
18709 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18710 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18711 instr.ads
18712 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18713 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18714 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18715 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18716 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18717 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18718 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18719 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18720 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18721 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18722 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18723 @end smallexample
18724 @end ifset
18725
18726 @node Cleaning Up Using gnatclean
18727 @chapter Cleaning Up Using @code{gnatclean}
18728 @findex gnatclean
18729 @cindex Cleaning tool
18730
18731 @noindent
18732 @code{gnatclean} is a tool that allows the deletion of files produced by the
18733 compiler, binder and linker, including ALI files, object files, tree files,
18734 expanded source files, library files, interface copy source files, binder
18735 generated files and executable files.
18736
18737 @menu
18738 * Running gnatclean::
18739 * Switches for gnatclean::
18740 @c * Examples of gnatclean Usage::
18741 @end menu
18742
18743 @node Running gnatclean
18744 @section Running @code{gnatclean}
18745
18746 @noindent
18747 The @code{gnatclean} command has the form:
18748
18749 @smallexample
18750 $ gnatclean switches @var{names}
18751 @end smallexample
18752
18753 @noindent
18754 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18755 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18756 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18757
18758 @noindent
18759 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18760 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18761 the linker. In informative-only mode, specified by switch
18762 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18763 normal mode is listed, but no file is actually deleted.
18764
18765 @node Switches for gnatclean
18766 @section Switches for @code{gnatclean}
18767
18768 @noindent
18769 @code{gnatclean} recognizes the following switches:
18770
18771 @table @option
18772 @c !sort!
18773 @cindex @option{--version} @command{gnatclean}
18774 Display Copyright and version, then exit disregarding all other options.
18775
18776 @item --help
18777 @cindex @option{--help} @command{gnatclean}
18778 If @option{--version} was not used, display usage, then exit disregarding
18779 all other options.
18780
18781 @item ^-c^/COMPILER_FILES_ONLY^
18782 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18783 Only attempt to delete the files produced by the compiler, not those produced
18784 by the binder or the linker. The files that are not to be deleted are library
18785 files, interface copy files, binder generated files and executable files.
18786
18787 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18788 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18789 Indicate that ALI and object files should normally be found in directory
18790 @var{dir}.
18791
18792 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18793 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18794 When using project files, if some errors or warnings are detected during
18795 parsing and verbose mode is not in effect (no use of switch
18796 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18797 file, rather than its simple file name.
18798
18799 @item ^-h^/HELP^
18800 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18801 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18802
18803 @item ^-n^/NODELETE^
18804 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18805 Informative-only mode. Do not delete any files. Output the list of the files
18806 that would have been deleted if this switch was not specified.
18807
18808 @item ^-P^/PROJECT_FILE=^@var{project}
18809 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18810 Use project file @var{project}. Only one such switch can be used.
18811 When cleaning a project file, the files produced by the compilation of the
18812 immediate sources or inherited sources of the project files are to be
18813 deleted. This is not depending on the presence or not of executable names
18814 on the command line.
18815
18816 @item ^-q^/QUIET^
18817 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18818 Quiet output. If there are no errors, do not output anything, except in
18819 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18820 (switch ^-n^/NODELETE^).
18821
18822 @item ^-r^/RECURSIVE^
18823 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18824 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18825 clean all imported and extended project files, recursively. If this switch
18826 is not specified, only the files related to the main project file are to be
18827 deleted. This switch has no effect if no project file is specified.
18828
18829 @item ^-v^/VERBOSE^
18830 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18831 Verbose mode.
18832
18833 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18834 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18835 Indicates the verbosity of the parsing of GNAT project files.
18836 @xref{Switches Related to Project Files}.
18837
18838 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18839 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18840 Indicates that external variable @var{name} has the value @var{value}.
18841 The Project Manager will use this value for occurrences of
18842 @code{external(name)} when parsing the project file.
18843 @xref{Switches Related to Project Files}.
18844
18845 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18846 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18847 When searching for ALI and object files, look in directory
18848 @var{dir}.
18849
18850 @item ^-I^/SEARCH=^@var{dir}
18851 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18852 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18853
18854 @item ^-I-^/NOCURRENT_DIRECTORY^
18855 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18856 @cindex Source files, suppressing search
18857 Do not look for ALI or object files in the directory
18858 where @code{gnatclean} was invoked.
18859
18860 @end table
18861
18862 @c @node Examples of gnatclean Usage
18863 @c @section Examples of @code{gnatclean} Usage
18864
18865 @ifclear vms
18866 @node GNAT and Libraries
18867 @chapter GNAT and Libraries
18868 @cindex Library, building, installing, using
18869
18870 @noindent
18871 This chapter describes how to build and use libraries with GNAT, and also shows
18872 how to recompile the GNAT run-time library. You should be familiar with the
18873 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18874 chapter.
18875
18876 @menu
18877 * Introduction to Libraries in GNAT::
18878 * General Ada Libraries::
18879 * Stand-alone Ada Libraries::
18880 * Rebuilding the GNAT Run-Time Library::
18881 @end menu
18882
18883 @node Introduction to Libraries in GNAT
18884 @section Introduction to Libraries in GNAT
18885
18886 @noindent
18887 A library is, conceptually, a collection of objects which does not have its
18888 own main thread of execution, but rather provides certain services to the
18889 applications that use it. A library can be either statically linked with the
18890 application, in which case its code is directly included in the application,
18891 or, on platforms that support it, be dynamically linked, in which case
18892 its code is shared by all applications making use of this library.
18893
18894 GNAT supports both types of libraries.
18895 In the static case, the compiled code can be provided in different ways. The
18896 simplest approach is to provide directly the set of objects resulting from
18897 compilation of the library source files. Alternatively, you can group the
18898 objects into an archive using whatever commands are provided by the operating
18899 system. For the latter case, the objects are grouped into a shared library.
18900
18901 In the GNAT environment, a library has three types of components:
18902 @itemize @bullet
18903 @item
18904 Source files.
18905 @item
18906 @file{ALI} files.
18907 @xref{The Ada Library Information Files}.
18908 @item
18909 Object files, an archive or a shared library.
18910 @end itemize
18911
18912 @noindent
18913 A GNAT library may expose all its source files, which is useful for
18914 documentation purposes. Alternatively, it may expose only the units needed by
18915 an external user to make use of the library. That is to say, the specs
18916 reflecting the library services along with all the units needed to compile
18917 those specs, which can include generic bodies or any body implementing an
18918 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18919 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18920
18921 All compilation units comprising an application, including those in a library,
18922 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18923 computes the elaboration order from the @file{ALI} files and this is why they
18924 constitute a mandatory part of GNAT libraries.
18925 @emph{Stand-alone libraries} are the exception to this rule because a specific
18926 library elaboration routine is produced independently of the application(s)
18927 using the library.
18928
18929 @node General Ada Libraries
18930 @section General Ada Libraries
18931
18932 @menu
18933 * Building a library::
18934 * Installing a library::
18935 * Using a library::
18936 @end menu
18937
18938 @node Building a library
18939 @subsection Building a library
18940
18941 @noindent
18942 The easiest way to build a library is to use the Project Manager,
18943 which supports a special type of project called a @emph{Library Project}
18944 (@pxref{Library Projects}).
18945
18946 A project is considered a library project, when two project-level attributes
18947 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18948 control different aspects of library configuration, additional optional
18949 project-level attributes can be specified:
18950 @table @code
18951 @item Library_Kind
18952 This attribute controls whether the library is to be static or dynamic
18953
18954 @item Library_Version
18955 This attribute specifies the library version; this value is used
18956 during dynamic linking of shared libraries to determine if the currently
18957 installed versions of the binaries are compatible.
18958
18959 @item Library_Options
18960 @item Library_GCC
18961 These attributes specify additional low-level options to be used during
18962 library generation, and redefine the actual application used to generate
18963 library.
18964 @end table
18965
18966 @noindent
18967 The GNAT Project Manager takes full care of the library maintenance task,
18968 including recompilation of the source files for which objects do not exist
18969 or are not up to date, assembly of the library archive, and installation of
18970 the library (i.e., copying associated source, object and @file{ALI} files
18971 to the specified location).
18972
18973 Here is a simple library project file:
18974 @smallexample @c ada
18975 project My_Lib is
18976    for Source_Dirs use ("src1", "src2");
18977    for Object_Dir use "obj";
18978    for Library_Name use "mylib";
18979    for Library_Dir use "lib";
18980    for Library_Kind use "dynamic";
18981 end My_lib;
18982 @end smallexample
18983
18984 @noindent
18985 and the compilation command to build and install the library:
18986
18987 @smallexample @c ada
18988   $ gnatmake -Pmy_lib
18989 @end smallexample
18990
18991 @noindent
18992 It is not entirely trivial to perform manually all the steps required to
18993 produce a library. We recommend that you use the GNAT Project Manager
18994 for this task. In special cases where this is not desired, the necessary
18995 steps are discussed below.
18996
18997 There are various possibilities for compiling the units that make up the
18998 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18999 with a conventional script. For simple libraries, it is also possible to create
19000 a dummy main program which depends upon all the packages that comprise the
19001 interface of the library. This dummy main program can then be given to
19002 @command{gnatmake}, which will ensure that all necessary objects are built.
19003
19004 After this task is accomplished, you should follow the standard procedure
19005 of the underlying operating system to produce the static or shared library.
19006
19007 Here is an example of such a dummy program:
19008 @smallexample @c ada
19009 @group
19010 with My_Lib.Service1;
19011 with My_Lib.Service2;
19012 with My_Lib.Service3;
19013 procedure My_Lib_Dummy is
19014 begin
19015    null;
19016 end;
19017 @end group
19018 @end smallexample
19019
19020 @noindent
19021 Here are the generic commands that will build an archive or a shared library.
19022
19023 @smallexample
19024 # compiling the library
19025 $ gnatmake -c my_lib_dummy.adb
19026
19027 # we don't need the dummy object itself
19028 $ rm my_lib_dummy.o my_lib_dummy.ali
19029
19030 # create an archive with the remaining objects
19031 $ ar rc libmy_lib.a *.o
19032 # some systems may require "ranlib" to be run as well
19033
19034 # or create a shared library
19035 $ gcc -shared -o libmy_lib.so *.o
19036 # some systems may require the code to have been compiled with -fPIC
19037
19038 # remove the object files that are now in the library
19039 $ rm *.o
19040
19041 # Make the ALI files read-only so that gnatmake will not try to
19042 # regenerate the objects that are in the library
19043 $ chmod -w *.ali
19044 @end smallexample
19045
19046 @noindent
19047 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19048 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19049 be accessed by the directive @option{-l@var{xxx}} at link time.
19050
19051 @node Installing a library
19052 @subsection Installing a library
19053 @cindex @code{ADA_PROJECT_PATH}
19054
19055 @noindent
19056 If you use project files, library installation is part of the library build
19057 process. Thus no further action is needed in order to make use of the
19058 libraries that are built as part of the general application build. A usable
19059 version of the library is installed in the directory specified by the
19060 @code{Library_Dir} attribute of the library project file.
19061
19062 You may want to install a library in a context different from where the library
19063 is built. This situation arises with third party suppliers, who may want
19064 to distribute a library in binary form where the user is not expected to be
19065 able to recompile the library. The simplest option in this case is to provide
19066 a project file slightly different from the one used to build the library, by
19067 using the @code{externally_built} attribute. For instance, the project
19068 file used to build the library in the previous section can be changed into the
19069 following one when the library is installed:
19070
19071 @smallexample @c projectfile
19072 project My_Lib is
19073    for Source_Dirs use ("src1", "src2");
19074    for Library_Name use "mylib";
19075    for Library_Dir use "lib";
19076    for Library_Kind use "dynamic";
19077    for Externally_Built use "true";
19078 end My_lib;
19079 @end smallexample
19080
19081 @noindent
19082 This project file assumes that the directories @file{src1},
19083 @file{src2}, and @file{lib} exist in
19084 the directory containing the project file. The @code{externally_built}
19085 attribute makes it clear to the GNAT builder that it should not attempt to
19086 recompile any of the units from this library. It allows the library provider to
19087 restrict the source set to the minimum necessary for clients to make use of the
19088 library as described in the first section of this chapter. It is the
19089 responsibility of the library provider to install the necessary sources, ALI
19090 files and libraries in the directories mentioned in the project file. For
19091 convenience, the user's library project file should be installed in a location
19092 that will be searched automatically by the GNAT
19093 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
19094 environment variable (@pxref{Importing Projects}), and also the default GNAT
19095 library location that can be queried with @command{gnatls -v} and is usually of
19096 the form $gnat_install_root/lib/gnat.
19097
19098 When project files are not an option, it is also possible, but not recommended,
19099 to install the library so that the sources needed to use the library are on the
19100 Ada source path and the ALI files & libraries be on the Ada Object path (see
19101 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19102 administrator can place general-purpose libraries in the default compiler
19103 paths, by specifying the libraries' location in the configuration files
19104 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19105 must be located in the GNAT installation tree at the same place as the gcc spec
19106 file. The location of the gcc spec file can be determined as follows:
19107 @smallexample
19108 $ gcc -v
19109 @end smallexample
19110
19111 @noindent
19112 The configuration files mentioned above have a simple format: each line
19113 must contain one unique directory name.
19114 Those names are added to the corresponding path
19115 in their order of appearance in the file. The names can be either absolute
19116 or relative; in the latter case, they are relative to where theses files
19117 are located.
19118
19119 The files @file{ada_source_path} and @file{ada_object_path} might not be
19120 present in a
19121 GNAT installation, in which case, GNAT will look for its run-time library in
19122 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19123 objects and @file{ALI} files). When the files exist, the compiler does not
19124 look in @file{adainclude} and @file{adalib}, and thus the
19125 @file{ada_source_path} file
19126 must contain the location for the GNAT run-time sources (which can simply
19127 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19128 contain the location for the GNAT run-time objects (which can simply
19129 be @file{adalib}).
19130
19131 You can also specify a new default path to the run-time library at compilation
19132 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19133 the run-time library you want your program to be compiled with. This switch is
19134 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19135 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19136
19137 It is possible to install a library before or after the standard GNAT
19138 library, by reordering the lines in the configuration files. In general, a
19139 library must be installed before the GNAT library if it redefines
19140 any part of it.
19141
19142 @node Using a library
19143 @subsection Using a library
19144
19145 @noindent Once again, the project facility greatly simplifies the use of
19146 libraries. In this context, using a library is just a matter of adding a
19147 @code{with} clause in the user project. For instance, to make use of the
19148 library @code{My_Lib} shown in examples in earlier sections, you can
19149 write:
19150
19151 @smallexample @c projectfile
19152 with "my_lib";
19153 project My_Proj is
19154   @dots{}
19155 end My_Proj;
19156 @end smallexample
19157
19158 Even if you have a third-party, non-Ada library, you can still use GNAT's
19159 Project Manager facility to provide a wrapper for it. For example, the
19160 following project, when @code{with}ed by your main project, will link with the
19161 third-party library @file{liba.a}:
19162
19163 @smallexample @c projectfile
19164 @group
19165 project Liba is
19166    for Externally_Built use "true";
19167    for Source_Files use ();
19168    for Library_Dir use "lib";
19169    for Library_Name use "a";
19170    for Library_Kind use "static";
19171 end Liba;
19172 @end group
19173 @end smallexample
19174 This is an alternative to the use of @code{pragma Linker_Options}. It is
19175 especially interesting in the context of systems with several interdependent
19176 static libraries where finding a proper linker order is not easy and best be
19177 left to the tools having visibility over project dependence information.
19178
19179 @noindent
19180 In order to use an Ada library manually, you need to make sure that this
19181 library is on both your source and object path
19182 (see @ref{Search Paths and the Run-Time Library (RTL)}
19183 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19184 in an archive or a shared library, you need to specify the desired
19185 library at link time.
19186
19187 For example, you can use the library @file{mylib} installed in
19188 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19189
19190 @smallexample
19191 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19192   -largs -lmy_lib
19193 @end smallexample
19194
19195 @noindent
19196 This can be expressed more simply:
19197 @smallexample
19198 $ gnatmake my_appl
19199 @end smallexample
19200 @noindent
19201 when the following conditions are met:
19202 @itemize @bullet
19203 @item
19204 @file{/dir/my_lib_src} has been added by the user to the environment
19205 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19206 @file{ada_source_path}
19207 @item
19208 @file{/dir/my_lib_obj} has been added by the user to the environment
19209 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19210 @file{ada_object_path}
19211 @item
19212 a pragma @code{Linker_Options} has been added to one of the sources.
19213 For example:
19214
19215 @smallexample @c ada
19216 pragma Linker_Options ("-lmy_lib");
19217 @end smallexample
19218 @end itemize
19219
19220 @node Stand-alone Ada Libraries
19221 @section Stand-alone Ada Libraries
19222 @cindex Stand-alone library, building, using
19223
19224 @menu
19225 * Introduction to Stand-alone Libraries::
19226 * Building a Stand-alone Library::
19227 * Creating a Stand-alone Library to be used in a non-Ada context::
19228 * Restrictions in Stand-alone Libraries::
19229 @end menu
19230
19231 @node Introduction to Stand-alone Libraries
19232 @subsection Introduction to Stand-alone Libraries
19233
19234 @noindent
19235 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19236 necessary code to
19237 elaborate the Ada units that are included in the library. In contrast with
19238 an ordinary library, which consists of all sources, objects and @file{ALI}
19239 files of the
19240 library, a SAL may specify a restricted subset of compilation units
19241 to serve as a library interface. In this case, the fully
19242 self-sufficient set of files will normally consist of an objects
19243 archive, the sources of interface units' specs, and the @file{ALI}
19244 files of interface units.
19245 If an interface spec contains a generic unit or an inlined subprogram,
19246 the body's
19247 source must also be provided; if the units that must be provided in the source
19248 form depend on other units, the source and @file{ALI} files of those must
19249 also be provided.
19250
19251 The main purpose of a SAL is to minimize the recompilation overhead of client
19252 applications when a new version of the library is installed. Specifically,
19253 if the interface sources have not changed, client applications do not need to
19254 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19255 version, controlled by @code{Library_Version} attribute, is not changed,
19256 then the clients do not need to be relinked.
19257
19258 SALs also allow the library providers to minimize the amount of library source
19259 text exposed to the clients.  Such ``information hiding'' might be useful or
19260 necessary for various reasons.
19261
19262 Stand-alone libraries are also well suited to be used in an executable whose
19263 main routine is not written in Ada.
19264
19265 @node Building a Stand-alone Library
19266 @subsection Building a Stand-alone Library
19267
19268 @noindent
19269 GNAT's Project facility provides a simple way of building and installing
19270 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19271 To be a Stand-alone Library Project, in addition to the two attributes
19272 that make a project a Library Project (@code{Library_Name} and
19273 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19274 @code{Library_Interface} must be defined.  For example:
19275
19276 @smallexample @c projectfile
19277 @group
19278    for Library_Dir use "lib_dir";
19279    for Library_Name use "dummy";
19280    for Library_Interface use ("int1", "int1.child");
19281 @end group
19282 @end smallexample
19283
19284 @noindent
19285 Attribute @code{Library_Interface} has a non-empty string list value,
19286 each string in the list designating a unit contained in an immediate source
19287 of the project file.
19288
19289 When a Stand-alone Library is built, first the binder is invoked to build
19290 a package whose name depends on the library name
19291 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19292 This binder-generated package includes initialization and
19293 finalization procedures whose
19294 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19295 in the example
19296 above). The object corresponding to this package is included in the library.
19297
19298 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19299 calling of these procedures if a static SAL is built, or if a shared SAL
19300 is built
19301 with the project-level attribute @code{Library_Auto_Init} set to
19302 @code{"false"}.
19303
19304 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19305 (those that are listed in attribute @code{Library_Interface}) are copied to
19306 the Library Directory. As a consequence, only the Interface Units may be
19307 imported from Ada units outside of the library. If other units are imported,
19308 the binding phase will fail.
19309
19310 The attribute @code{Library_Src_Dir} may be specified for a
19311 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19312 single string value. Its value must be the path (absolute or relative to the
19313 project directory) of an existing directory. This directory cannot be the
19314 object directory or one of the source directories, but it can be the same as
19315 the library directory. The sources of the Interface
19316 Units of the library that are needed by an Ada client of the library will be
19317 copied to the designated directory, called the Interface Copy directory.
19318 These sources include the specs of the Interface Units, but they may also
19319 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19320 are used, or when there is a generic unit in the spec. Before the sources
19321 are copied to the Interface Copy directory, an attempt is made to delete all
19322 files in the Interface Copy directory.
19323
19324 Building stand-alone libraries by hand is somewhat tedious, but for those
19325 occasions when it is necessary here are the steps that you need to perform:
19326 @itemize @bullet
19327 @item
19328 Compile all library sources.
19329
19330 @item
19331 Invoke the binder with the switch @option{-n} (No Ada main program),
19332 with all the @file{ALI} files of the interfaces, and
19333 with the switch @option{-L} to give specific names to the @code{init}
19334 and @code{final} procedures.  For example:
19335 @smallexample
19336   gnatbind -n int1.ali int2.ali -Lsal1
19337 @end smallexample
19338
19339 @item
19340 Compile the binder generated file:
19341 @smallexample
19342   gcc -c b~int2.adb
19343 @end smallexample
19344
19345 @item
19346 Link the dynamic library with all the necessary object files,
19347 indicating to the linker the names of the @code{init} (and possibly
19348 @code{final}) procedures for automatic initialization (and finalization).
19349 The built library should be placed in a directory different from
19350 the object directory.
19351
19352 @item
19353 Copy the @code{ALI} files of the interface to the library directory,
19354 add in this copy an indication that it is an interface to a SAL
19355 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19356 with letter ``P'') and make the modified copy of the @file{ALI} file
19357 read-only.
19358 @end itemize
19359
19360 @noindent
19361 Using SALs is not different from using other libraries
19362 (see @ref{Using a library}).
19363
19364 @node Creating a Stand-alone Library to be used in a non-Ada context
19365 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19366
19367 @noindent
19368 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19369 a non-Ada context.
19370
19371 The only extra step required is to ensure that library interface subprograms
19372 are compatible with the main program, by means of @code{pragma Export}
19373 or @code{pragma Convention}.
19374
19375 Here is an example of simple library interface for use with C main program:
19376
19377 @smallexample @c ada
19378 package Interface is
19379
19380    procedure Do_Something;
19381    pragma Export (C, Do_Something, "do_something");
19382
19383    procedure Do_Something_Else;
19384    pragma Export (C, Do_Something_Else, "do_something_else");
19385
19386 end Interface;
19387 @end smallexample
19388
19389 @noindent
19390 On the foreign language side, you must provide a ``foreign'' view of the
19391 library interface; remember that it should contain elaboration routines in
19392 addition to interface subprograms.
19393
19394 The example below shows the content of @code{mylib_interface.h} (note
19395 that there is no rule for the naming of this file, any name can be used)
19396 @smallexample
19397 /* the library elaboration procedure */
19398 extern void mylibinit (void);
19399
19400 /* the library finalization procedure */
19401 extern void mylibfinal (void);
19402
19403 /* the interface exported by the library */
19404 extern void do_something (void);
19405 extern void do_something_else (void);
19406 @end smallexample
19407
19408 @noindent
19409 Libraries built as explained above can be used from any program, provided
19410 that the elaboration procedures (named @code{mylibinit} in the previous
19411 example) are called before the library services are used. Any number of
19412 libraries can be used simultaneously, as long as the elaboration
19413 procedure of each library is called.
19414
19415 Below is an example of a C program that uses the @code{mylib} library.
19416
19417 @smallexample
19418 #include "mylib_interface.h"
19419
19420 int
19421 main (void)
19422 @{
19423    /* First, elaborate the library before using it */
19424    mylibinit ();
19425
19426    /* Main program, using the library exported entities */
19427    do_something ();
19428    do_something_else ();
19429
19430    /* Library finalization at the end of the program */
19431    mylibfinal ();
19432    return 0;
19433 @}
19434 @end smallexample
19435
19436 @noindent
19437 Note that invoking any library finalization procedure generated by
19438 @code{gnatbind} shuts down the Ada run-time environment.
19439 Consequently, the
19440 finalization of all Ada libraries must be performed at the end of the program.
19441 No call to these libraries or to the Ada run-time library should be made
19442 after the finalization phase.
19443
19444 @node Restrictions in Stand-alone Libraries
19445 @subsection Restrictions in Stand-alone Libraries
19446
19447 @noindent
19448 The pragmas listed below should be used with caution inside libraries,
19449 as they can create incompatibilities with other Ada libraries:
19450 @itemize @bullet
19451 @item pragma @code{Locking_Policy}
19452 @item pragma @code{Queuing_Policy}
19453 @item pragma @code{Task_Dispatching_Policy}
19454 @item pragma @code{Unreserve_All_Interrupts}
19455 @end itemize
19456
19457 @noindent
19458 When using a library that contains such pragmas, the user must make sure
19459 that all libraries use the same pragmas with the same values. Otherwise,
19460 @code{Program_Error} will
19461 be raised during the elaboration of the conflicting
19462 libraries. The usage of these pragmas and its consequences for the user
19463 should therefore be well documented.
19464
19465 Similarly, the traceback in the exception occurrence mechanism should be
19466 enabled or disabled in a consistent manner across all libraries.
19467 Otherwise, Program_Error will be raised during the elaboration of the
19468 conflicting libraries.
19469
19470 If the @code{Version} or @code{Body_Version}
19471 attributes are used inside a library, then you need to
19472 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19473 libraries, so that version identifiers can be properly computed.
19474 In practice these attributes are rarely used, so this is unlikely
19475 to be a consideration.
19476
19477 @node  Rebuilding the GNAT Run-Time Library
19478 @section Rebuilding the GNAT Run-Time Library
19479 @cindex GNAT Run-Time Library, rebuilding
19480 @cindex Building the GNAT Run-Time Library
19481 @cindex Rebuilding the GNAT Run-Time Library
19482 @cindex Run-Time Library, rebuilding
19483
19484 @noindent
19485 It may be useful to recompile the GNAT library in various contexts, the
19486 most important one being the use of partition-wide configuration pragmas
19487 such as @code{Normalize_Scalars}. A special Makefile called
19488 @code{Makefile.adalib} is provided to that effect and can be found in
19489 the directory containing the GNAT library. The location of this
19490 directory depends on the way the GNAT environment has been installed and can
19491 be determined by means of the command:
19492
19493 @smallexample
19494 $ gnatls -v
19495 @end smallexample
19496
19497 @noindent
19498 The last entry in the object search path usually contains the
19499 gnat library. This Makefile contains its own documentation and in
19500 particular the set of instructions needed to rebuild a new library and
19501 to use it.
19502
19503 @node Using the GNU make Utility
19504 @chapter Using the GNU @code{make} Utility
19505 @findex make
19506
19507 @noindent
19508 This chapter offers some examples of makefiles that solve specific
19509 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19510 make, make, GNU @code{make}}), nor does it try to replace the
19511 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19512
19513 All the examples in this section are specific to the GNU version of
19514 make. Although @command{make} is a standard utility, and the basic language
19515 is the same, these examples use some advanced features found only in
19516 @code{GNU make}.
19517
19518 @menu
19519 * Using gnatmake in a Makefile::
19520 * Automatically Creating a List of Directories::
19521 * Generating the Command Line Switches::
19522 * Overcoming Command Line Length Limits::
19523 @end menu
19524
19525 @node Using gnatmake in a Makefile
19526 @section Using gnatmake in a Makefile
19527 @findex makefile
19528 @cindex GNU make
19529
19530 @noindent
19531 Complex project organizations can be handled in a very powerful way by
19532 using GNU make combined with gnatmake. For instance, here is a Makefile
19533 which allows you to build each subsystem of a big project into a separate
19534 shared library. Such a makefile allows you to significantly reduce the link
19535 time of very big applications while maintaining full coherence at
19536 each step of the build process.
19537
19538 The list of dependencies are handled automatically by
19539 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19540 the appropriate directories.
19541
19542 Note that you should also read the example on how to automatically
19543 create the list of directories
19544 (@pxref{Automatically Creating a List of Directories})
19545 which might help you in case your project has a lot of subdirectories.
19546
19547 @smallexample
19548 @iftex
19549 @leftskip=0cm
19550 @font@heightrm=cmr8
19551 @heightrm
19552 @end iftex
19553 ## This Makefile is intended to be used with the following directory
19554 ## configuration:
19555 ##  - The sources are split into a series of csc (computer software components)
19556 ##    Each of these csc is put in its own directory.
19557 ##    Their name are referenced by the directory names.
19558 ##    They will be compiled into shared library (although this would also work
19559 ##    with static libraries
19560 ##  - The main program (and possibly other packages that do not belong to any
19561 ##    csc is put in the top level directory (where the Makefile is).
19562 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19563 ##                    \_ second_csc (sources) __ lib (will contain the library)
19564 ##                    \_ @dots{}
19565 ## Although this Makefile is build for shared library, it is easy to modify
19566 ## to build partial link objects instead (modify the lines with -shared and
19567 ## gnatlink below)
19568 ##
19569 ## With this makefile, you can change any file in the system or add any new
19570 ## file, and everything will be recompiled correctly (only the relevant shared
19571 ## objects will be recompiled, and the main program will be re-linked).
19572
19573 # The list of computer software component for your project. This might be
19574 # generated automatically.
19575 CSC_LIST=aa bb cc
19576
19577 # Name of the main program (no extension)
19578 MAIN=main
19579
19580 # If we need to build objects with -fPIC, uncomment the following line
19581 #NEED_FPIC=-fPIC
19582
19583 # The following variable should give the directory containing libgnat.so
19584 # You can get this directory through 'gnatls -v'. This is usually the last
19585 # directory in the Object_Path.
19586 GLIB=@dots{}
19587
19588 # The directories for the libraries
19589 # (This macro expands the list of CSC to the list of shared libraries, you
19590 # could simply use the expanded form:
19591 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19592 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19593
19594 $@{MAIN@}: objects $@{LIB_DIR@}
19595     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19596     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19597
19598 objects::
19599     # recompile the sources
19600     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19601
19602 # Note: In a future version of GNAT, the following commands will be simplified
19603 # by a new tool, gnatmlib
19604 $@{LIB_DIR@}:
19605     mkdir -p $@{dir $@@ @}
19606     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19607     cd $@{dir $@@ @} && cp -f ../*.ali .
19608
19609 # The dependencies for the modules
19610 # Note that we have to force the expansion of *.o, since in some cases
19611 # make won't be able to do it itself.
19612 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19613 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19614 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19615
19616 # Make sure all of the shared libraries are in the path before starting the
19617 # program
19618 run::
19619     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19620
19621 clean::
19622     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19623     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19624     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19625     $@{RM@} *.o *.ali $@{MAIN@}
19626 @end smallexample
19627
19628 @node Automatically Creating a List of Directories
19629 @section Automatically Creating a List of Directories
19630
19631 @noindent
19632 In most makefiles, you will have to specify a list of directories, and
19633 store it in a variable. For small projects, it is often easier to
19634 specify each of them by hand, since you then have full control over what
19635 is the proper order for these directories, which ones should be
19636 included.
19637
19638 However, in larger projects, which might involve hundreds of
19639 subdirectories, it might be more convenient to generate this list
19640 automatically.
19641
19642 The example below presents two methods. The first one, although less
19643 general, gives you more control over the list. It involves wildcard
19644 characters, that are automatically expanded by @command{make}. Its
19645 shortcoming is that you need to explicitly specify some of the
19646 organization of your project, such as for instance the directory tree
19647 depth, whether some directories are found in a separate tree, @enddots{}
19648
19649 The second method is the most general one. It requires an external
19650 program, called @command{find}, which is standard on all Unix systems. All
19651 the directories found under a given root directory will be added to the
19652 list.
19653
19654 @smallexample
19655 @iftex
19656 @leftskip=0cm
19657 @font@heightrm=cmr8
19658 @heightrm
19659 @end iftex
19660 # The examples below are based on the following directory hierarchy:
19661 # All the directories can contain any number of files
19662 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19663 #                       ->  ab
19664 #                       ->  ac
19665 #                ->  b  ->  ba  ->  baa
19666 #                       ->  bb
19667 #                       ->  bc
19668 # This Makefile creates a variable called DIRS, that can be reused any time
19669 # you need this list (see the other examples in this section)
19670
19671 # The root of your project's directory hierarchy
19672 ROOT_DIRECTORY=.
19673
19674 ####
19675 # First method: specify explicitly the list of directories
19676 # This allows you to specify any subset of all the directories you need.
19677 ####
19678
19679 DIRS := a/aa/ a/ab/ b/ba/
19680
19681 ####
19682 # Second method: use wildcards
19683 # Note that the argument(s) to wildcard below should end with a '/'.
19684 # Since wildcards also return file names, we have to filter them out
19685 # to avoid duplicate directory names.
19686 # We thus use make's @code{dir} and @code{sort} functions.
19687 # It sets DIRs to the following value (note that the directories aaa and baa
19688 # are not given, unless you change the arguments to wildcard).
19689 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19690 ####
19691
19692 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19693                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19694
19695 ####
19696 # Third method: use an external program
19697 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19698 # This is the most complete command: it sets DIRs to the following value:
19699 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19700 ####
19701
19702 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19703
19704 @end smallexample
19705
19706 @node Generating the Command Line Switches
19707 @section Generating the Command Line Switches
19708
19709 @noindent
19710 Once you have created the list of directories as explained in the
19711 previous section (@pxref{Automatically Creating a List of Directories}),
19712 you can easily generate the command line arguments to pass to gnatmake.
19713
19714 For the sake of completeness, this example assumes that the source path
19715 is not the same as the object path, and that you have two separate lists
19716 of directories.
19717
19718 @smallexample
19719 # see "Automatically creating a list of directories" to create
19720 # these variables
19721 SOURCE_DIRS=
19722 OBJECT_DIRS=
19723
19724 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19725 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19726
19727 all:
19728         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19729 @end smallexample
19730
19731 @node Overcoming Command Line Length Limits
19732 @section Overcoming Command Line Length Limits
19733
19734 @noindent
19735 One problem that might be encountered on big projects is that many
19736 operating systems limit the length of the command line. It is thus hard to give
19737 gnatmake the list of source and object directories.
19738
19739 This example shows how you can set up environment variables, which will
19740 make @command{gnatmake} behave exactly as if the directories had been
19741 specified on the command line, but have a much higher length limit (or
19742 even none on most systems).
19743
19744 It assumes that you have created a list of directories in your Makefile,
19745 using one of the methods presented in
19746 @ref{Automatically Creating a List of Directories}.
19747 For the sake of completeness, we assume that the object
19748 path (where the ALI files are found) is different from the sources patch.
19749
19750 Note a small trick in the Makefile below: for efficiency reasons, we
19751 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19752 expanded immediately by @code{make}. This way we overcome the standard
19753 make behavior which is to expand the variables only when they are
19754 actually used.
19755
19756 On Windows, if you are using the standard Windows command shell, you must
19757 replace colons with semicolons in the assignments to these variables.
19758
19759 @smallexample
19760 @iftex
19761 @leftskip=0cm
19762 @font@heightrm=cmr8
19763 @heightrm
19764 @end iftex
19765 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19766 # This is the same thing as putting the -I arguments on the command line.
19767 # (the equivalent of using -aI on the command line would be to define
19768 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19769 # You can of course have different values for these variables.
19770 #
19771 # Note also that we need to keep the previous values of these variables, since
19772 # they might have been set before running 'make' to specify where the GNAT
19773 # library is installed.
19774
19775 # see "Automatically creating a list of directories" to create these
19776 # variables
19777 SOURCE_DIRS=
19778 OBJECT_DIRS=
19779
19780 empty:=
19781 space:=$@{empty@} $@{empty@}
19782 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19783 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19784 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19785 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19786 export ADA_INCLUDE_PATH
19787 export ADA_OBJECT_PATH
19788
19789 all:
19790         gnatmake main_unit
19791 @end smallexample
19792 @end ifclear
19793
19794 @node Memory Management Issues
19795 @chapter Memory Management Issues
19796
19797 @noindent
19798 This chapter describes some useful memory pools provided in the GNAT library
19799 and in particular the GNAT Debug Pool facility, which can be used to detect
19800 incorrect uses of access values (including ``dangling references'').
19801 @ifclear vms
19802 It also describes the @command{gnatmem} tool, which can be used to track down
19803 ``memory leaks''.
19804 @end ifclear
19805
19806 @menu
19807 * Some Useful Memory Pools::
19808 * The GNAT Debug Pool Facility::
19809 @ifclear vms
19810 * The gnatmem Tool::
19811 @end ifclear
19812 @end menu
19813
19814 @node Some Useful Memory Pools
19815 @section Some Useful Memory Pools
19816 @findex Memory Pool
19817 @cindex storage, pool
19818
19819 @noindent
19820 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19821 storage pool. Allocations use the standard system call @code{malloc} while
19822 deallocations use the standard system call @code{free}. No reclamation is
19823 performed when the pool goes out of scope. For performance reasons, the
19824 standard default Ada allocators/deallocators do not use any explicit storage
19825 pools but if they did, they could use this storage pool without any change in
19826 behavior. That is why this storage pool is used  when the user
19827 manages to make the default implicit allocator explicit as in this example:
19828 @smallexample @c ada
19829    type T1 is access Something;
19830     -- no Storage pool is defined for T2
19831    type T2 is access Something_Else;
19832    for T2'Storage_Pool use T1'Storage_Pool;
19833    -- the above is equivalent to
19834    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19835 @end smallexample
19836
19837 @noindent
19838 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19839 pool. The allocation strategy is similar to @code{Pool_Local}'s
19840 except that the all
19841 storage allocated with this pool is reclaimed when the pool object goes out of
19842 scope. This pool provides a explicit mechanism similar to the implicit one
19843 provided by several Ada 83 compilers for allocations performed through a local
19844 access type and whose purpose was to reclaim memory when exiting the
19845 scope of a given local access. As an example, the following program does not
19846 leak memory even though it does not perform explicit deallocation:
19847
19848 @smallexample @c ada
19849 with System.Pool_Local;
19850 procedure Pooloc1 is
19851    procedure Internal is
19852       type A is access Integer;
19853       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19854       for A'Storage_Pool use X;
19855       v : A;
19856    begin
19857       for I in  1 .. 50 loop
19858          v := new Integer;
19859       end loop;
19860    end Internal;
19861 begin
19862    for I in  1 .. 100 loop
19863       Internal;
19864    end loop;
19865 end Pooloc1;
19866 @end smallexample
19867
19868 @noindent
19869 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19870 @code{Storage_Size} is specified for an access type.
19871 The whole storage for the pool is
19872 allocated at once, usually on the stack at the point where the access type is
19873 elaborated. It is automatically reclaimed when exiting the scope where the
19874 access type is defined. This package is not intended to be used directly by the
19875 user and it is implicitly used for each such declaration:
19876
19877 @smallexample @c ada
19878    type T1 is access Something;
19879    for T1'Storage_Size use 10_000;
19880 @end smallexample
19881
19882 @node The GNAT Debug Pool Facility
19883 @section The GNAT Debug Pool Facility
19884 @findex Debug Pool
19885 @cindex storage, pool, memory corruption
19886
19887 @noindent
19888 The use of unchecked deallocation and unchecked conversion can easily
19889 lead to incorrect memory references. The problems generated by such
19890 references are usually difficult to tackle because the symptoms can be
19891 very remote from the origin of the problem. In such cases, it is
19892 very helpful to detect the problem as early as possible. This is the
19893 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19894
19895 In order to use the GNAT specific debugging pool, the user must
19896 associate a debug pool object with each of the access types that may be
19897 related to suspected memory problems. See Ada Reference Manual 13.11.
19898 @smallexample @c ada
19899 type Ptr is access Some_Type;
19900 Pool : GNAT.Debug_Pools.Debug_Pool;
19901 for Ptr'Storage_Pool use Pool;
19902 @end smallexample
19903
19904 @noindent
19905 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19906 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19907 allow the user to redefine allocation and deallocation strategies. They
19908 also provide a checkpoint for each dereference, through the use of
19909 the primitive operation @code{Dereference} which is implicitly called at
19910 each dereference of an access value.
19911
19912 Once an access type has been associated with a debug pool, operations on
19913 values of the type may raise four distinct exceptions,
19914 which correspond to four potential kinds of memory corruption:
19915 @itemize @bullet
19916 @item
19917 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19918 @item
19919 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19920 @item
19921 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19922 @item
19923 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19924 @end itemize
19925
19926 @noindent
19927 For types associated with a Debug_Pool, dynamic allocation is performed using
19928 the standard GNAT allocation routine. References to all allocated chunks of
19929 memory are kept in an internal dictionary. Several deallocation strategies are
19930 provided, whereupon the user can choose to release the memory to the system,
19931 keep it allocated for further invalid access checks, or fill it with an easily
19932 recognizable pattern for debug sessions. The memory pattern is the old IBM
19933 hexadecimal convention: @code{16#DEADBEEF#}.
19934
19935 See the documentation in the file g-debpoo.ads for more information on the
19936 various strategies.
19937
19938 Upon each dereference, a check is made that the access value denotes a
19939 properly allocated memory location. Here is a complete example of use of
19940 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19941 @smallexample @c ada
19942 @iftex
19943 @leftskip=0cm
19944 @end iftex
19945 with Gnat.Io; use Gnat.Io;
19946 with Unchecked_Deallocation;
19947 with Unchecked_Conversion;
19948 with GNAT.Debug_Pools;
19949 with System.Storage_Elements;
19950 with Ada.Exceptions; use Ada.Exceptions;
19951 procedure Debug_Pool_Test is
19952
19953    type T is access Integer;
19954    type U is access all T;
19955
19956    P : GNAT.Debug_Pools.Debug_Pool;
19957    for T'Storage_Pool use P;
19958
19959    procedure Free is new Unchecked_Deallocation (Integer, T);
19960    function UC is new Unchecked_Conversion (U, T);
19961    A, B : aliased T;
19962
19963    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19964
19965 begin
19966    Info (P);
19967    A := new Integer;
19968    B := new Integer;
19969    B := A;
19970    Info (P);
19971    Free (A);
19972    begin
19973       Put_Line (Integer'Image(B.all));
19974    exception
19975       when E : others => Put_Line ("raised: " & Exception_Name (E));
19976    end;
19977    begin
19978       Free (B);
19979    exception
19980       when E : others => Put_Line ("raised: " & Exception_Name (E));
19981    end;
19982    B := UC(A'Access);
19983    begin
19984       Put_Line (Integer'Image(B.all));
19985    exception
19986       when E : others => Put_Line ("raised: " & Exception_Name (E));
19987    end;
19988    begin
19989       Free (B);
19990    exception
19991       when E : others => Put_Line ("raised: " & Exception_Name (E));
19992    end;
19993    Info (P);
19994 end Debug_Pool_Test;
19995 @end smallexample
19996
19997 @noindent
19998 The debug pool mechanism provides the following precise diagnostics on the
19999 execution of this erroneous program:
20000 @smallexample
20001 Debug Pool info:
20002   Total allocated bytes :  0
20003   Total deallocated bytes :  0
20004   Current Water Mark:  0
20005   High Water Mark:  0
20006
20007 Debug Pool info:
20008   Total allocated bytes :  8
20009   Total deallocated bytes :  0
20010   Current Water Mark:  8
20011   High Water Mark:  8
20012
20013 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20014 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20015 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20016 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20017 Debug Pool info:
20018   Total allocated bytes :  8
20019   Total deallocated bytes :  4
20020   Current Water Mark:  4
20021   High Water Mark:  8
20022 @end smallexample
20023
20024 @ifclear vms
20025 @node The gnatmem Tool
20026 @section The @command{gnatmem} Tool
20027 @findex gnatmem
20028
20029 @noindent
20030 The @code{gnatmem} utility monitors dynamic allocation and
20031 deallocation activity in a program, and displays information about
20032 incorrect deallocations and possible sources of memory leaks.
20033 It is designed to work in association with a static runtime library
20034 only and in this context provides three types of information:
20035 @itemize @bullet
20036 @item
20037 General information concerning memory management, such as the total
20038 number of allocations and deallocations, the amount of allocated
20039 memory and the high water mark, i.e.@: the largest amount of allocated
20040 memory in the course of program execution.
20041
20042 @item
20043 Backtraces for all incorrect deallocations, that is to say deallocations
20044 which do not correspond to a valid allocation.
20045
20046 @item
20047 Information on each allocation that is potentially the origin of a memory
20048 leak.
20049 @end itemize
20050
20051 @menu
20052 * Running gnatmem::
20053 * Switches for gnatmem::
20054 * Example of gnatmem Usage::
20055 @end menu
20056
20057 @node Running gnatmem
20058 @subsection Running @code{gnatmem}
20059
20060 @noindent
20061 @code{gnatmem} makes use of the output created by the special version of
20062 allocation and deallocation routines that record call information. This
20063 allows to obtain accurate dynamic memory usage history at a minimal cost to
20064 the execution speed. Note however, that @code{gnatmem} is not supported on
20065 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20066 Solaris and Windows NT/2000/XP (x86).
20067
20068 @noindent
20069 The @code{gnatmem} command has the form
20070
20071 @smallexample
20072    $ gnatmem @ovar{switches} user_program
20073 @end smallexample
20074
20075 @noindent
20076 The program must have been linked with the instrumented version of the
20077 allocation and deallocation routines. This is done by linking with the
20078 @file{libgmem.a} library. For correct symbolic backtrace information,
20079 the user program should be compiled with debugging options
20080 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20081
20082 @smallexample
20083 $ gnatmake -g my_program -largs -lgmem
20084 @end smallexample
20085
20086 @noindent
20087 As library @file{libgmem.a} contains an alternate body for package
20088 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20089 when an executable is linked with library @file{libgmem.a}. It is then not
20090 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20091
20092 @noindent
20093 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20094 This file contains information about all allocations and deallocations
20095 performed by the program. It is produced by the instrumented allocations and
20096 deallocations routines and will be used by @code{gnatmem}.
20097
20098 In order to produce symbolic backtrace information for allocations and
20099 deallocations performed by the GNAT run-time library, you need to use a
20100 version of that library that has been compiled with the @option{-g} switch
20101 (see @ref{Rebuilding the GNAT Run-Time Library}).
20102
20103 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20104 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20105 @option{-i} switch, gnatmem will assume that this file can be found in the
20106 current directory. For example, after you have executed @file{my_program},
20107 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20108
20109 @smallexample
20110 $ gnatmem my_program
20111 @end smallexample
20112
20113 @noindent
20114 This will produce the output with the following format:
20115
20116 *************** debut cc
20117 @smallexample
20118 $ gnatmem my_program
20119
20120 Global information
20121 ------------------
20122    Total number of allocations        :  45
20123    Total number of deallocations      :   6
20124    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20125    High Water Mark                    :  11.40 Kilobytes
20126
20127 .
20128 .
20129 .
20130 Allocation Root # 2
20131 -------------------
20132  Number of non freed allocations    :  11
20133  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20134  High Water Mark                    :   1.27 Kilobytes
20135  Backtrace                          :
20136    my_program.adb:23 my_program.alloc
20137 .
20138 .
20139 .
20140 @end smallexample
20141
20142 The first block of output gives general information. In this case, the
20143 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20144 Unchecked_Deallocation routine occurred.
20145
20146 @noindent
20147 Subsequent paragraphs display  information on all allocation roots.
20148 An allocation root is a specific point in the execution of the program
20149 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20150 construct. This root is represented by an execution backtrace (or subprogram
20151 call stack). By default the backtrace depth for allocations roots is 1, so
20152 that a root corresponds exactly to a source location. The backtrace can
20153 be made deeper, to make the root more specific.
20154
20155 @node Switches for gnatmem
20156 @subsection Switches for @code{gnatmem}
20157
20158 @noindent
20159 @code{gnatmem} recognizes the following switches:
20160
20161 @table @option
20162
20163 @item -q
20164 @cindex @option{-q} (@code{gnatmem})
20165 Quiet. Gives the minimum output needed to identify the origin of the
20166 memory leaks. Omits statistical information.
20167
20168 @item @var{N}
20169 @cindex @var{N} (@code{gnatmem})
20170 N is an integer literal (usually between 1 and 10) which controls the
20171 depth of the backtraces defining allocation root. The default value for
20172 N is 1. The deeper the backtrace, the more precise the localization of
20173 the root. Note that the total number of roots can depend on this
20174 parameter. This parameter must be specified @emph{before} the name of the
20175 executable to be analyzed, to avoid ambiguity.
20176
20177 @item -b n
20178 @cindex @option{-b} (@code{gnatmem})
20179 This switch has the same effect as just depth parameter.
20180
20181 @item -i @var{file}
20182 @cindex @option{-i} (@code{gnatmem})
20183 Do the @code{gnatmem} processing starting from @file{file}, rather than
20184 @file{gmem.out} in the current directory.
20185
20186 @item -m n
20187 @cindex @option{-m} (@code{gnatmem})
20188 This switch causes @code{gnatmem} to mask the allocation roots that have less
20189 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20190 examine even the roots that didn't result in leaks.
20191
20192 @item -s order
20193 @cindex @option{-s} (@code{gnatmem})
20194 This switch causes @code{gnatmem} to sort the allocation roots according to the
20195 specified order of sort criteria, each identified by a single letter. The
20196 currently supported criteria are @code{n, h, w} standing respectively for
20197 number of unfreed allocations, high watermark, and final watermark
20198 corresponding to a specific root. The default order is @code{nwh}.
20199
20200 @end table
20201
20202 @node Example of gnatmem Usage
20203 @subsection Example of @code{gnatmem} Usage
20204
20205 @noindent
20206 The following example shows the use of @code{gnatmem}
20207 on a simple memory-leaking program.
20208 Suppose that we have the following Ada program:
20209
20210 @smallexample @c ada
20211 @group
20212 @cartouche
20213 with Unchecked_Deallocation;
20214 procedure Test_Gm is
20215
20216    type T is array (1..1000) of Integer;
20217    type Ptr is access T;
20218    procedure Free is new Unchecked_Deallocation (T, Ptr);
20219    A : Ptr;
20220
20221    procedure My_Alloc is
20222    begin
20223       A := new T;
20224    end My_Alloc;
20225
20226    procedure My_DeAlloc is
20227       B : Ptr := A;
20228    begin
20229       Free (B);
20230    end My_DeAlloc;
20231
20232 begin
20233    My_Alloc;
20234    for I in 1 .. 5 loop
20235       for J in I .. 5 loop
20236          My_Alloc;
20237       end loop;
20238       My_Dealloc;
20239    end loop;
20240 end;
20241 @end cartouche
20242 @end group
20243 @end smallexample
20244
20245 @noindent
20246 The program needs to be compiled with debugging option and linked with
20247 @code{gmem} library:
20248
20249 @smallexample
20250 $ gnatmake -g test_gm -largs -lgmem
20251 @end smallexample
20252
20253 @noindent
20254 Then we execute the program as usual:
20255
20256 @smallexample
20257 $ test_gm
20258 @end smallexample
20259
20260 @noindent
20261 Then @code{gnatmem} is invoked simply with
20262 @smallexample
20263 $ gnatmem test_gm
20264 @end smallexample
20265
20266 @noindent
20267 which produces the following output (result may vary on different platforms):
20268
20269 @smallexample
20270 Global information
20271 ------------------
20272    Total number of allocations        :  18
20273    Total number of deallocations      :   5
20274    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20275    High Water Mark                    :  56.90 Kilobytes
20276
20277 Allocation Root # 1
20278 -------------------
20279  Number of non freed allocations    :  11
20280  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20281  High Water Mark                    :  46.88 Kilobytes
20282  Backtrace                          :
20283    test_gm.adb:11 test_gm.my_alloc
20284
20285 Allocation Root # 2
20286 -------------------
20287  Number of non freed allocations    :   1
20288  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20289  High Water Mark                    :  10.02 Kilobytes
20290  Backtrace                          :
20291    s-secsta.adb:81 system.secondary_stack.ss_init
20292
20293 Allocation Root # 3
20294 -------------------
20295  Number of non freed allocations    :   1
20296  Final Water Mark (non freed mem)   :  12 Bytes
20297  High Water Mark                    :  12 Bytes
20298  Backtrace                          :
20299    s-secsta.adb:181 system.secondary_stack.ss_init
20300 @end smallexample
20301
20302 @noindent
20303 Note that the GNAT run time contains itself a certain number of
20304 allocations that have no  corresponding deallocation,
20305 as shown here for root #2 and root
20306 #3. This is a normal behavior when the number of non-freed allocations
20307 is one, it allocates dynamic data structures that the run time needs for
20308 the complete lifetime of the program. Note also that there is only one
20309 allocation root in the user program with a single line back trace:
20310 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20311 program shows that 'My_Alloc' is called at 2 different points in the
20312 source (line 21 and line 24). If those two allocation roots need to be
20313 distinguished, the backtrace depth parameter can be used:
20314
20315 @smallexample
20316 $ gnatmem 3 test_gm
20317 @end smallexample
20318
20319 @noindent
20320 which will give the following output:
20321
20322 @smallexample
20323 Global information
20324 ------------------
20325    Total number of allocations        :  18
20326    Total number of deallocations      :   5
20327    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20328    High Water Mark                    :  56.90 Kilobytes
20329
20330 Allocation Root # 1
20331 -------------------
20332  Number of non freed allocations    :  10
20333  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20334  High Water Mark                    :  42.97 Kilobytes
20335  Backtrace                          :
20336    test_gm.adb:11 test_gm.my_alloc
20337    test_gm.adb:24 test_gm
20338    b_test_gm.c:52 main
20339
20340 Allocation Root # 2
20341 -------------------
20342  Number of non freed allocations    :   1
20343  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20344  High Water Mark                    :  10.02 Kilobytes
20345  Backtrace                          :
20346    s-secsta.adb:81  system.secondary_stack.ss_init
20347    s-secsta.adb:283 <system__secondary_stack___elabb>
20348    b_test_gm.c:33   adainit
20349
20350 Allocation Root # 3
20351 -------------------
20352  Number of non freed allocations    :   1
20353  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20354  High Water Mark                    :   3.91 Kilobytes
20355  Backtrace                          :
20356    test_gm.adb:11 test_gm.my_alloc
20357    test_gm.adb:21 test_gm
20358    b_test_gm.c:52 main
20359
20360 Allocation Root # 4
20361 -------------------
20362  Number of non freed allocations    :   1
20363  Final Water Mark (non freed mem)   :  12 Bytes
20364  High Water Mark                    :  12 Bytes
20365  Backtrace                          :
20366    s-secsta.adb:181 system.secondary_stack.ss_init
20367    s-secsta.adb:283 <system__secondary_stack___elabb>
20368    b_test_gm.c:33   adainit
20369 @end smallexample
20370
20371 @noindent
20372 The allocation root #1 of the first example has been split in 2 roots #1
20373 and #3 thanks to the more precise associated backtrace.
20374
20375 @end ifclear
20376
20377 @node Stack Related Facilities
20378 @chapter Stack Related Facilities
20379
20380 @noindent
20381 This chapter describes some useful tools associated with stack
20382 checking and analysis. In
20383 particular, it deals with dynamic and static stack usage measurements.
20384
20385 @menu
20386 * Stack Overflow Checking::
20387 * Static Stack Usage Analysis::
20388 * Dynamic Stack Usage Analysis::
20389 @end menu
20390
20391 @node Stack Overflow Checking
20392 @section Stack Overflow Checking
20393 @cindex Stack Overflow Checking
20394 @cindex -fstack-check
20395
20396 @noindent
20397 For most operating systems, @command{gcc} does not perform stack overflow
20398 checking by default. This means that if the main environment task or
20399 some other task exceeds the available stack space, then unpredictable
20400 behavior will occur. Most native systems offer some level of protection by
20401 adding a guard page at the end of each task stack. This mechanism is usually
20402 not enough for dealing properly with stack overflow situations because
20403 a large local variable could ``jump'' above the guard page.
20404 Furthermore, when the
20405 guard page is hit, there may not be any space left on the stack for executing
20406 the exception propagation code. Enabling stack checking avoids
20407 such situations.
20408
20409 To activate stack checking, compile all units with the gcc option
20410 @option{-fstack-check}. For example:
20411
20412 @smallexample
20413 gcc -c -fstack-check package1.adb
20414 @end smallexample
20415
20416 @noindent
20417 Units compiled with this option will generate extra instructions to check
20418 that any use of the stack (for procedure calls or for declaring local
20419 variables in declare blocks) does not exceed the available stack space.
20420 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20421
20422 For declared tasks, the stack size is controlled by the size
20423 given in an applicable @code{Storage_Size} pragma or by the value specified
20424 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20425 the default size as defined in the GNAT runtime otherwise.
20426
20427 For the environment task, the stack size depends on
20428 system defaults and is unknown to the compiler. Stack checking
20429 may still work correctly if a fixed
20430 size stack is allocated, but this cannot be guaranteed.
20431 @ifclear vms
20432 To ensure that a clean exception is signalled for stack
20433 overflow, set the environment variable
20434 @env{GNAT_STACK_LIMIT} to indicate the maximum
20435 stack area that can be used, as in:
20436 @cindex GNAT_STACK_LIMIT
20437
20438 @smallexample
20439 SET GNAT_STACK_LIMIT 1600
20440 @end smallexample
20441
20442 @noindent
20443 The limit is given in kilobytes, so the above declaration would
20444 set the stack limit of the environment task to 1.6 megabytes.
20445 Note that the only purpose of this usage is to limit the amount
20446 of stack used by the environment task. If it is necessary to
20447 increase the amount of stack for the environment task, then this
20448 is an operating systems issue, and must be addressed with the
20449 appropriate operating systems commands.
20450 @end ifclear
20451 @ifset vms
20452 To have a fixed size stack in the environment task, the stack must be put
20453 in the P0 address space and its size specified.  Use these switches to
20454 create a p0 image:
20455
20456 @smallexample
20457 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20458 @end smallexample
20459
20460 @noindent
20461 The quotes are required to keep case.  The number after @samp{STACK=} is the
20462 size of the environmental task stack in pagelets (512 bytes).  In this example
20463 the stack size is about 2 megabytes.
20464
20465 @noindent
20466 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20467 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20468 more details about the @option{/p0image} qualifier and the @option{stack}
20469 option.
20470 @end ifset
20471
20472 @node Static Stack Usage Analysis
20473 @section Static Stack Usage Analysis
20474 @cindex Static Stack Usage Analysis
20475 @cindex -fstack-usage
20476
20477 @noindent
20478 A unit compiled with @option{-fstack-usage} will generate an extra file
20479 that specifies
20480 the maximum amount of stack used, on a per-function basis.
20481 The file has the same
20482 basename as the target object file with a @file{.su} extension.
20483 Each line of this file is made up of three fields:
20484
20485 @itemize
20486 @item
20487 The name of the function.
20488 @item
20489 A number of bytes.
20490 @item
20491 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20492 @end itemize
20493
20494 The second field corresponds to the size of the known part of the function
20495 frame.
20496
20497 The qualifier @code{static} means that the function frame size
20498 is purely static.
20499 It usually means that all local variables have a static size.
20500 In this case, the second field is a reliable measure of the function stack
20501 utilization.
20502
20503 The qualifier @code{dynamic} means that the function frame size is not static.
20504 It happens mainly when some local variables have a dynamic size. When this
20505 qualifier appears alone, the second field is not a reliable measure
20506 of the function stack analysis. When it is qualified with  @code{bounded}, it
20507 means that the second field is a reliable maximum of the function stack
20508 utilization.
20509
20510 @node Dynamic Stack Usage Analysis
20511 @section Dynamic Stack Usage Analysis
20512
20513 @noindent
20514 It is possible to measure the maximum amount of stack used by a task, by
20515 adding a switch to @command{gnatbind}, as:
20516
20517 @smallexample
20518 $ gnatbind -u0 file
20519 @end smallexample
20520
20521 @noindent
20522 With this option, at each task termination, its stack usage is  output on
20523 @file{stderr}.
20524 It is not always convenient to output the stack usage when the program
20525 is still running. Hence, it is possible to delay this output until program
20526 termination. for a given number of tasks specified as the argument of the
20527 @option{-u} option. For instance:
20528
20529 @smallexample
20530 $ gnatbind -u100 file
20531 @end smallexample
20532
20533 @noindent
20534 will buffer the stack usage information of the first 100 tasks to terminate and
20535 output this info at program termination. Results are displayed in four
20536 columns:
20537
20538 @noindent
20539 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20540
20541 @noindent
20542 where:
20543
20544 @table @emph
20545 @item Index
20546 is a number associated with each task.
20547
20548 @item Task Name
20549 is the name of the task analyzed.
20550
20551 @item Stack Size
20552 is the maximum size for the stack.
20553
20554 @item Stack Usage
20555 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20556 is not entirely analyzed, and it's not possible to know exactly how
20557 much has actually been used. The report thus contains the theoretical stack usage
20558 (Value) and the possible variation (Variation) around this value.
20559
20560 @end table
20561
20562 @noindent
20563 The environment task stack, e.g., the stack that contains the main unit, is
20564 only processed when the environment variable GNAT_STACK_LIMIT is set.
20565
20566
20567 @c *********************************
20568 @c *            GNATCHECK          *
20569 @c *********************************
20570 @node Verifying Properties Using gnatcheck
20571 @chapter Verifying Properties Using @command{gnatcheck}
20572 @findex gnatcheck
20573 @cindex @command{gnatcheck}
20574
20575 @noindent
20576 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20577 of Ada source files according to a given set of semantic rules.
20578 @cindex ASIS
20579
20580 In order to check compliance with a given rule, @command{gnatcheck} has to
20581 semantically analyze the Ada sources.
20582 Therefore, checks can only be performed on
20583 legal Ada units. Moreover, when a unit depends semantically upon units located
20584 outside the current directory, the source search path has to be provided when
20585 calling @command{gnatcheck}, either through a specified project file or
20586 through @command{gnatcheck} switches as described below.
20587
20588 A number of rules are predefined in @command{gnatcheck} and are described
20589 later in this chapter.
20590 You can also add new rules, by modifying the @command{gnatcheck} code and
20591 rebuilding the tool. In order to add a simple rule making some local checks,
20592 a small amount of straightforward ASIS-based programming is usually needed.
20593
20594 Project support for @command{gnatcheck} is provided by the GNAT
20595 driver (see @ref{The GNAT Driver and Project Files}).
20596
20597 Invoking @command{gnatcheck} on the command line has the form:
20598
20599 @smallexample
20600 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20601       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20602       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20603 @end smallexample
20604
20605 @noindent
20606 where
20607 @itemize @bullet
20608 @item
20609 @var{switches} specify the general tool options
20610
20611 @item
20612 Each @var{filename} is the name (including the extension) of a source
20613 file to process. ``Wildcards'' are allowed, and
20614 the file name may contain path information.
20615
20616 @item
20617 Each @var{arg_list_filename} is the name (including the extension) of a text
20618 file containing the names of the source files to process, separated by spaces
20619 or line breaks.
20620
20621 @item
20622 @var{gcc_switches} is a list of switches for
20623 @command{gcc}. They will be passed on to all compiler invocations made by
20624 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20625 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20626 and use the @option{-gnatec} switch to set the configuration file.
20627
20628 @item
20629 @var{rule_options} is a list of options for controlling a set of
20630 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20631 @end itemize
20632
20633 @noindent
20634 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20635
20636 @menu
20637 * Format of the Report File::
20638 * General gnatcheck Switches::
20639 * gnatcheck Rule Options::
20640 * Adding the Results of Compiler Checks to gnatcheck Output::
20641 * Project-Wide Checks::
20642 * Predefined Rules::
20643 @end menu
20644
20645 @node Format of the Report File
20646 @section Format of the Report File
20647 @cindex Report file (for @code{gnatcheck})
20648
20649 @noindent
20650 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20651 rule violations.
20652 It also creates a text file  that
20653 contains the complete report of the last gnatcheck run. By default this file is
20654 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20655 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20656 location of the report file. This report contains:
20657 @itemize @bullet
20658 @item a list of the Ada source files being checked,
20659 @item a list of enabled and disabled rules,
20660 @item a list of the diagnostic messages, ordered in three different ways
20661 and collected in three separate
20662 sections. Section 1 contains the raw list of diagnostic messages. It
20663 corresponds to the output going to @file{stdout}. Section 2 contains
20664 messages ordered by rules.
20665 Section 3 contains messages ordered by source files.
20666 @end itemize
20667
20668 @node General gnatcheck Switches
20669 @section General @command{gnatcheck} Switches
20670
20671 @noindent
20672 The following switches control the general @command{gnatcheck} behavior
20673
20674 @table @option
20675 @c !sort!
20676 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20677 @item ^-a^/ALL^
20678 Process all units including those with read-only ALI files such as
20679 those from GNAT Run-Time library.
20680
20681 @ifclear vms
20682 @ignore
20683 @cindex @option{-d} (@command{gnatcheck})
20684 @item -d
20685 Debug mode
20686 @end ignore
20687
20688 @cindex @option{-dd} (@command{gnatcheck})
20689 @item -dd
20690 Progress indicator mode (for use in GPS)
20691 @end ifclear
20692
20693 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20694 @item ^-h^/HELP^
20695 List the predefined and user-defined rules. For more details see
20696 @ref{Predefined Rules}.
20697
20698 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20699 @item ^-l^/LOCS^
20700 Use full source locations references in the report file. For a construct from
20701 a generic instantiation a full source location is a chain from the location
20702 of this construct in the generic unit to the place where this unit is
20703 instantiated.
20704
20705 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20706 @item ^-log^/LOG^
20707 Duplicate all the output sent to Stderr into a log file. The log file is
20708 named @var{gnatcheck.log} and is located in the current directory.
20709
20710 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20711 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20712 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20713 the default value is 500. Zero means that there is no limitation on
20714 the number of diagnostic messages to be printed into Stdout.
20715
20716 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20717 @item ^-q^/QUIET^
20718 Quiet mode. All the diagnoses about rule violations are placed in the
20719 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20720
20721 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20722 @item ^-s^/SHORT^
20723 Short format of the report file (no version information, no list of applied
20724 rules, no list of checked sources is included)
20725
20726 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20727 @item ^-s1^/COMPILER_STYLE^
20728 Include the compiler-style section in the report file
20729
20730 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20731 @item ^-s2^/BY_RULES^
20732 Include the section containing diagnoses ordered by rules in the report file
20733
20734 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20735 @item ^-s3^/BY_FILES_BY_RULES^
20736 Include the section containing diagnoses ordered by files and then by rules
20737 in the report file
20738
20739 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20740 @item ^-t^/TIME^
20741 Print out execution time.
20742
20743 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20744 @item ^-v^/VERBOSE^
20745 Verbose mode; @command{gnatcheck} generates version information and then
20746 a trace of sources being processed.
20747
20748 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20749 @item ^-o ^/OUTPUT=^@var{report_file}
20750 Set name of report file file to @var{report_file} .
20751
20752 @end table
20753
20754 @noindent
20755 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20756 @option{^-s2^/BY_RULES^} or
20757 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20758 then the  @command{gnatcheck} report file will only contain sections
20759 explicitly denoted by these options.
20760
20761 @node gnatcheck Rule Options
20762 @section @command{gnatcheck} Rule Options
20763
20764 @noindent
20765 The following options control the processing performed by
20766 @command{gnatcheck}.
20767
20768 @table @option
20769 @cindex @option{+ALL} (@command{gnatcheck})
20770 @item +ALL
20771 Turn all the rule checks ON.
20772
20773 @cindex @option{-ALL} (@command{gnatcheck})
20774 @item -ALL
20775 Turn all the rule checks OFF.
20776
20777 @cindex @option{+R} (@command{gnatcheck})
20778 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20779 Turn on the check for a specified rule with the specified parameter, if any.
20780 @var{rule_id} must be the identifier of one of the currently implemented rules
20781 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20782 are not case-sensitive. The @var{param} item must
20783 be a string representing a valid parameter(s) for the specified rule.
20784 If it contains any space characters then this string must be enclosed in
20785 quotation marks.
20786
20787 @cindex @option{-R} (@command{gnatcheck})
20788 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20789 Turn off the check for a specified rule with the specified parameter, if any.
20790
20791 @cindex @option{-from} (@command{gnatcheck})
20792 @item -from=@var{rule_option_filename}
20793 Read the rule options from the text file @var{rule_option_filename}, referred as
20794 ``rule file'' below.
20795
20796 @end table
20797
20798 @noindent
20799 The default behavior is that all the rule checks are disabled.
20800
20801 A rule file is a text file containing a set of rule options.
20802 @cindex Rule file (for @code{gnatcheck})
20803 The file may contain empty lines and Ada-style comments (comment
20804 lines and end-of-line comments). The rule file has free format; that is,
20805 you do not have to start a new rule option on a new line.
20806
20807 A rule file may contain other @option{-from=@var{rule_option_filename}}
20808 options, each such option being replaced with the content of the
20809 corresponding rule file during the rule files processing. In case a
20810 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20811 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20812 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20813 the processing of rule files is interrupted and a part of their content
20814 is ignored.
20815
20816
20817 @node Adding the Results of Compiler Checks to gnatcheck Output
20818 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20819
20820 @noindent
20821 The @command{gnatcheck} tool can include in the generated diagnostic messages
20822 and in
20823 the report file the results of the checks performed by the compiler. Though
20824 disabled by default, this effect may be obtained by using @option{+R} with
20825 the following rule identifiers and parameters:
20826
20827 @table @option
20828 @item Restrictions
20829 To record restrictions violations (that are performed by the compiler if the
20830 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20831 use the rule named
20832 @code{Restrictions} with the same parameters as pragma
20833 @code{Restrictions} or @code{Restriction_Warnings}.
20834
20835 @item Style_Checks
20836 To record compiler style checks(@pxref{Style Checking}), use the rule named
20837 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20838 which enables all the standard style checks that corresponds to @option{-gnatyy}
20839 GNAT style check option, or a string that has exactly the same
20840 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20841 @code{Style_Checks} (for further information about this pragma,
20842 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}). For example,
20843 @code{+RStyle_Checks:O} rule option activates and adds to @command{gnatcheck}
20844 output the compiler style check that corresponds to
20845 @code{-gnatyO} style check option.
20846
20847 @item Warnings
20848 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20849 named @code{Warnings} with a parameter that is a valid
20850 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20851 (for further information about this pragma, @pxref{Pragma Warnings,,,
20852 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20853 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20854 all the specific warnings, but not suppresses the warning mode,
20855 and 'e' parameter, corresponding to @option{-gnatwe} that means
20856 "treat warnings as errors", does not have any effect.
20857
20858 @end table
20859
20860 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20861 option with the corresponding restriction name as a parameter. @code{-R} is
20862 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20863 warnings and style checks, use the corresponding warning and style options.
20864
20865 @node Project-Wide Checks
20866 @section Project-Wide Checks
20867 @cindex Project-wide checks (for @command{gnatcheck})
20868
20869 @noindent
20870 In order to perform checks on all units of a given project, you can use
20871 the GNAT driver along with the @option{-P} option:
20872 @smallexample
20873    gnat check -Pproj -rules -from=my_rules
20874 @end smallexample
20875
20876 @noindent
20877 If the project @code{proj} depends upon other projects, you can perform
20878 checks on the project closure using the @option{-U} option:
20879 @smallexample
20880    gnat check -Pproj -U -rules -from=my_rules
20881 @end smallexample
20882
20883 @noindent
20884 Finally, if not all the units are relevant to a particular main
20885 program in the project closure, you can perform checks for the set
20886 of units needed to create a given main program (unit closure) using
20887 the @option{-U} option followed by the name of the main unit:
20888 @smallexample
20889    gnat check -Pproj -U main -rules -from=my_rules
20890 @end smallexample
20891
20892
20893 @node Predefined Rules
20894 @section Predefined Rules
20895 @cindex Predefined rules (for @command{gnatcheck})
20896
20897 @ignore
20898 @c (Jan 2007) Since the global rules are still under development and are not
20899 @c documented, there is no point in explaining the difference between
20900 @c global and local rules
20901 @noindent
20902 A rule in @command{gnatcheck} is either local or global.
20903 A @emph{local rule} is a rule that applies to a well-defined section
20904 of a program and that can be checked by analyzing only this section.
20905 A @emph{global rule} requires analysis of some global properties of the
20906 whole program (mostly related to the program call graph).
20907 As of @value{NOW}, the implementation of global rules should be
20908 considered to be at a preliminary stage. You can use the
20909 @option{+GLOBAL} option to enable all the global rules, and the
20910 @option{-GLOBAL} rule option to disable all the global rules.
20911
20912 All the global rules in the list below are
20913 so indicated by marking them ``GLOBAL''.
20914 This +GLOBAL and -GLOBAL options are not
20915 included in the list of gnatcheck options above, because at the moment they
20916 are considered as a temporary debug options.
20917
20918 @command{gnatcheck} performs rule checks for generic
20919 instances only for global rules.  This limitation may be relaxed in a later
20920 release.
20921 @end ignore
20922
20923 @noindent
20924 The following subsections document the rules implemented in
20925 @command{gnatcheck}.
20926 The subsection title is the same as the rule identifier, which may be
20927 used as a parameter of the @option{+R} or @option{-R} options.
20928
20929
20930 @menu
20931 * Abstract_Type_Declarations::
20932 * Anonymous_Arrays::
20933 * Anonymous_Subtypes::
20934 * Blocks::
20935 * Boolean_Relational_Operators::
20936 @ignore
20937 * Ceiling_Violations::
20938 @end ignore
20939 * Controlled_Type_Declarations::
20940 * Declarations_In_Blocks::
20941 * Default_Parameters::
20942 * Discriminated_Records::
20943 * Enumeration_Ranges_In_CASE_Statements::
20944 * Exceptions_As_Control_Flow::
20945 * Exits_From_Conditional_Loops::
20946 * EXIT_Statements_With_No_Loop_Name::
20947 * Expanded_Loop_Exit_Names::
20948 * Explicit_Full_Discrete_Ranges::
20949 * Float_Equality_Checks::
20950 * Forbidden_Pragmas::
20951 * Function_Style_Procedures::
20952 * Generics_In_Subprograms::
20953 * GOTO_Statements::
20954 * Implicit_IN_Mode_Parameters::
20955 * Implicit_SMALL_For_Fixed_Point_Types::
20956 * Improperly_Located_Instantiations::
20957 * Improper_Returns::
20958 * Library_Level_Subprograms::
20959 * Local_Packages::
20960 @ignore
20961 * Improperly_Called_Protected_Entries::
20962 @end ignore
20963 * Metrics::
20964 * Misnamed_Identifiers::
20965 * Multiple_Entries_In_Protected_Definitions::
20966 * Name_Clashes::
20967 * Non_Qualified_Aggregates::
20968 * Non_Short_Circuit_Operators::
20969 * Non_SPARK_Attributes::
20970 * Non_Tagged_Derived_Types::
20971 * Non_Visible_Exceptions::
20972 * Numeric_Literals::
20973 * OTHERS_In_Aggregates::
20974 * OTHERS_In_CASE_Statements::
20975 * OTHERS_In_Exception_Handlers::
20976 * Outer_Loop_Exits::
20977 * Overloaded_Operators::
20978 * Overly_Nested_Control_Structures::
20979 * Parameters_Out_Of_Order::
20980 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20981 * Positional_Actuals_For_Defaulted_Parameters::
20982 * Positional_Components::
20983 * Positional_Generic_Parameters::
20984 * Positional_Parameters::
20985 * Predefined_Numeric_Types::
20986 * Raising_External_Exceptions::
20987 * Raising_Predefined_Exceptions::
20988 * Separate_Numeric_Error_Handlers::
20989 @ignore
20990 * Recursion::
20991 * Side_Effect_Functions::
20992 @end ignore
20993 * Slices::
20994 * Unassigned_OUT_Parameters::
20995 * Uncommented_BEGIN_In_Package_Bodies::
20996 * Unconditional_Exits::
20997 * Unconstrained_Array_Returns::
20998 * Universal_Ranges::
20999 * Unnamed_Blocks_And_Loops::
21000 @ignore
21001 * Unused_Subprograms::
21002 @end ignore
21003 * USE_PACKAGE_Clauses::
21004 * Volatile_Objects_Without_Address_Clauses::
21005 @end menu
21006
21007
21008 @node Abstract_Type_Declarations
21009 @subsection @code{Abstract_Type_Declarations}
21010 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21011
21012 @noindent
21013 Flag all declarations of abstract types. For an abstract private
21014 type, both the private and full type declarations are flagged.
21015
21016 This rule has no parameters.
21017
21018
21019 @node Anonymous_Arrays
21020 @subsection @code{Anonymous_Arrays}
21021 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21022
21023 @noindent
21024 Flag all anonymous array type definitions (by Ada semantics these can only
21025 occur in object declarations).
21026
21027 This rule has no parameters.
21028
21029 @node Anonymous_Subtypes
21030 @subsection @code{Anonymous_Subtypes}
21031 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21032
21033 @noindent
21034 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
21035 any instance of a subtype indication with a constraint, other than one
21036 that occurs immediately within a subtype declaration. Any use of a range
21037 other than as a constraint used immediately within a subtype declaration
21038 is considered as an anonymous subtype.
21039
21040 An effect of this rule is that @code{for} loops such as the following are
21041 flagged (since @code{1..N} is formally a ``range''):
21042
21043 @smallexample @c ada
21044 for I in 1 .. N loop
21045    @dots{}
21046 end loop;
21047 @end smallexample
21048
21049 @noindent
21050 Declaring an explicit subtype solves the problem:
21051
21052 @smallexample @c ada
21053 subtype S is Integer range 1..N;
21054 @dots{}
21055 for I in S loop
21056    @dots{}
21057 end loop;
21058 @end smallexample
21059
21060 @noindent
21061 This rule has no parameters.
21062
21063 @node Blocks
21064 @subsection @code{Blocks}
21065 @cindex @code{Blocks} rule (for @command{gnatcheck})
21066
21067 @noindent
21068 Flag each block statement.
21069
21070 This rule has no parameters.
21071
21072 @node Boolean_Relational_Operators
21073 @subsection @code{Boolean_Relational_Operators}
21074 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21075
21076 @noindent
21077 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21078 ``>='', ``='' and ``/='') for the predefined Boolean type.
21079 (This rule is useful in enforcing the SPARK language restrictions.)
21080
21081 Calls to predefined relational operators of any type derived from
21082 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21083 with these designators, and uses of operators that are renamings
21084 of the predefined relational operators for @code{Standard.Boolean},
21085 are likewise not detected.
21086
21087 This rule has no parameters.
21088
21089 @ignore
21090 @node Ceiling_Violations
21091 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
21092 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21093
21094 @noindent
21095 Flag invocations of a protected operation by a task whose priority exceeds
21096 the protected object's ceiling.
21097
21098 As of @value{NOW}, this rule has the following limitations:
21099
21100 @itemize @bullet
21101
21102 @item
21103  We consider only pragmas Priority and Interrupt_Priority as means to define
21104   a task/protected operation priority. We do not consider the effect of using
21105   Ada.Dynamic_Priorities.Set_Priority procedure;
21106
21107 @item
21108  We consider only base task priorities, and no priority inheritance. That is,
21109   we do not make a difference between calls issued during task activation and
21110   execution of the sequence of statements from task body;
21111
21112 @item
21113  Any situation when the priority of protected operation caller is set by a
21114   dynamic expression (that is, the corresponding Priority or
21115   Interrupt_Priority pragma has a non-static expression as an argument) we
21116   treat as a priority inconsistency (and, therefore, detect this situation).
21117 @end itemize
21118
21119 @noindent
21120 At the moment the notion of the main subprogram is not implemented in
21121 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21122 if this subprogram can be a main subprogram of a partition) changes the
21123 priority of an environment task. So if we have more then one such pragma in
21124 the set of processed sources, the pragma that is processed last, defines the
21125 priority of an environment task.
21126
21127 This rule has no parameters.
21128 @end ignore
21129
21130 @node Controlled_Type_Declarations
21131 @subsection @code{Controlled_Type_Declarations}
21132 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21133
21134 @noindent
21135 Flag all declarations of controlled types. A declaration of a private type
21136 is flagged if its full declaration declares a controlled type. A declaration
21137 of a derived type is flagged if its ancestor type is controlled. Subtype
21138 declarations are not checked. A declaration of a type that itself is not a
21139 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21140 component is not checked.
21141
21142 This rule has no parameters.
21143
21144
21145
21146 @node Declarations_In_Blocks
21147 @subsection @code{Declarations_In_Blocks}
21148 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21149
21150 @noindent
21151 Flag all block statements containing local declarations. A @code{declare}
21152 block with an empty @i{declarative_part} or with a @i{declarative part}
21153 containing only pragmas and/or @code{use} clauses is not flagged.
21154
21155 This rule has no parameters.
21156
21157
21158 @node Default_Parameters
21159 @subsection @code{Default_Parameters}
21160 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21161
21162 @noindent
21163 Flag all default expressions for subprogram parameters. Parameter
21164 declarations of formal and generic subprograms are also checked.
21165
21166 This rule has no parameters.
21167
21168
21169 @node Discriminated_Records
21170 @subsection @code{Discriminated_Records}
21171 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21172
21173 @noindent
21174 Flag all declarations of record types with discriminants. Only the
21175 declarations of record and record extension types are checked. Incomplete,
21176 formal, private, derived and private extension type declarations are not
21177 checked. Task and protected type declarations also are not checked.
21178
21179 This rule has no parameters.
21180
21181
21182 @node Enumeration_Ranges_In_CASE_Statements
21183 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21184 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21185
21186 @noindent
21187 Flag each use of a range of enumeration literals as a choice in a
21188 @code{case} statement.
21189 All forms for specifying a range (explicit ranges
21190 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21191 An enumeration range is
21192 flagged even if contains exactly one enumeration value or no values at all. A
21193 type derived from an enumeration type is considered as an enumeration type.
21194
21195 This rule helps prevent maintenance problems arising from adding an
21196 enumeration value to a type and having it implicitly handled by an existing
21197 @code{case} statement with an enumeration range that includes the new literal.
21198
21199 This rule has no parameters.
21200
21201
21202 @node Exceptions_As_Control_Flow
21203 @subsection @code{Exceptions_As_Control_Flow}
21204 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21205
21206 @noindent
21207 Flag each place where an exception is explicitly raised and handled in the
21208 same subprogram body. A @code{raise} statement in an exception handler,
21209 package body, task body or entry body is not flagged.
21210
21211 The rule has no parameters.
21212
21213 @node Exits_From_Conditional_Loops
21214 @subsection @code{Exits_From_Conditional_Loops}
21215 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21216
21217 @noindent
21218 Flag any exit statement if it transfers the control out of a @code{for} loop
21219 or a @code{while} loop. This includes cases when the @code{exit} statement
21220 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21221 in some @code{for} or @code{while} loop, but transfers the control from some
21222 outer (inconditional) @code{loop} statement.
21223
21224 The rule has no parameters.
21225
21226
21227 @node EXIT_Statements_With_No_Loop_Name
21228 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21229 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21230
21231 @noindent
21232 Flag each @code{exit} statement that does not specify the name of the loop
21233 being exited.
21234
21235 The rule has no parameters.
21236
21237
21238 @node Expanded_Loop_Exit_Names
21239 @subsection @code{Expanded_Loop_Exit_Names}
21240 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21241
21242 @noindent
21243 Flag all expanded loop names in @code{exit} statements.
21244
21245 This rule has no parameters.
21246
21247 @node Explicit_Full_Discrete_Ranges
21248 @subsection @code{Explicit_Full_Discrete_Ranges}
21249 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21250
21251 @noindent
21252 Flag each discrete range that has the form @code{A'First .. A'Last}.
21253
21254 This rule has no parameters.
21255
21256 @node Float_Equality_Checks
21257 @subsection @code{Float_Equality_Checks}
21258 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21259
21260 @noindent
21261 Flag all calls to the predefined equality operations for floating-point types.
21262 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21263 User-defined equality operations are not flagged, nor are ``@code{=}''
21264 and ``@code{/=}'' operations for fixed-point types.
21265
21266 This rule has no parameters.
21267
21268
21269 @node Forbidden_Pragmas
21270 @subsection @code{Forbidden_Pragmas}
21271 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21272
21273 @noindent
21274 Flag each use of the specified pragmas.  The pragmas to be detected
21275 are named in the rule's  parameters.
21276
21277 This rule has the following parameters:
21278
21279 @itemize @bullet
21280 @item For the @option{+R} option
21281
21282 @table @asis
21283 @item @emph{Pragma_Name}
21284 Adds the specified pragma to the set of pragmas to be
21285 checked and sets the checks for all the specified pragmas
21286 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21287 does not correspond to any pragma name defined in the Ada
21288 standard or to the name of a GNAT-specific pragma defined
21289 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21290 Manual}, it is treated as the name of unknown pragma.
21291
21292 @item @code{GNAT}
21293 All the GNAT-specific pragmas are detected; this sets
21294 the checks for all the specified pragmas ON.
21295
21296 @item @code{ALL}
21297 All pragmas are detected; this sets the rule ON.
21298 @end table
21299
21300 @item For the @option{-R} option
21301 @table @asis
21302 @item @emph{Pragma_Name}
21303 Removes the specified pragma from the set of pragmas to be
21304 checked without affecting checks for
21305 other pragmas. @emph{Pragma_Name} is treated as a name
21306 of a pragma. If it does not correspond to any pragma
21307 defined in the Ada standard or to any name defined in
21308 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21309 this option is treated as turning OFF detection of all unknown pragmas.
21310
21311 @item GNAT
21312 Turn OFF detection of all GNAT-specific pragmas
21313
21314 @item ALL
21315 Clear the list of the pragmas to be detected and
21316 turn the rule OFF.
21317 @end table
21318 @end itemize
21319
21320 @noindent
21321 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21322 the syntax of an Ada identifier and therefore can not be considered
21323 as a pragma name, a diagnostic message is generated and the corresponding
21324 parameter is ignored.
21325
21326 When more then one parameter is given in the same rule option, the parameters
21327 must be separated by a comma.
21328
21329 If more then one option for this rule is specified for the @command{gnatcheck}
21330 call, a new option overrides the previous one(s).
21331
21332 The @option{+R} option with no parameters turns the rule ON with the set of
21333 pragmas to be detected defined by the previous rule options.
21334 (By default this set is empty, so if the only option specified for the rule is
21335 @option{+RForbidden_Pragmas} (with
21336 no parameter), then the rule is enabled, but it does not detect anything).
21337 The @option{-R} option with no parameter turns the rule OFF, but it does not
21338 affect the set of pragmas to be detected.
21339
21340
21341
21342
21343 @node Function_Style_Procedures
21344 @subsection @code{Function_Style_Procedures}
21345 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21346
21347 @noindent
21348 Flag each procedure that can be rewritten as a function. A procedure can be
21349 converted into a function if it has exactly one parameter of mode @code{out}
21350 and no parameters of mode @code{in out}. Procedure declarations,
21351 formal procedure declarations, and generic procedure declarations are always
21352 checked. Procedure
21353 bodies and body stubs are flagged only if they do not have corresponding
21354 separate declarations. Procedure renamings and procedure instantiations are
21355 not flagged.
21356
21357 If a procedure can be rewritten as a function, but its @code{out} parameter is
21358 of a limited type, it is not flagged.
21359
21360 Protected procedures are not flagged. Null procedures also are not flagged.
21361
21362 This rule has no parameters.
21363
21364
21365 @node Generics_In_Subprograms
21366 @subsection @code{Generics_In_Subprograms}
21367 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21368
21369 @noindent
21370 Flag each declaration of a generic unit in a subprogram. Generic
21371 declarations in the bodies of generic subprograms are also flagged.
21372 A generic unit nested in another generic unit is not flagged.
21373 If a generic unit is
21374 declared in a local package that is declared in a subprogram body, the
21375 generic unit is flagged.
21376
21377 This rule has no parameters.
21378
21379
21380 @node GOTO_Statements
21381 @subsection @code{GOTO_Statements}
21382 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21383
21384 @noindent
21385 Flag each occurrence of a @code{goto} statement.
21386
21387 This rule has no parameters.
21388
21389
21390 @node Implicit_IN_Mode_Parameters
21391 @subsection @code{Implicit_IN_Mode_Parameters}
21392 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21393
21394 @noindent
21395 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21396 Note that @code{access} parameters, although they technically behave
21397 like @code{in} parameters, are not flagged.
21398
21399 This rule has no parameters.
21400
21401
21402 @node Implicit_SMALL_For_Fixed_Point_Types
21403 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21404 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21405
21406 @noindent
21407 Flag each fixed point type declaration that lacks an explicit
21408 representation  clause to define its @code{'Small} value.
21409 Since @code{'Small} can be  defined only for ordinary fixed point types,
21410 decimal fixed point type declarations are not checked.
21411
21412 This rule has no parameters.
21413
21414
21415 @node Improperly_Located_Instantiations
21416 @subsection @code{Improperly_Located_Instantiations}
21417 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21418
21419 @noindent
21420 Flag all generic instantiations in library-level package specs
21421 (including library generic packages) and in all subprogram bodies.
21422
21423 Instantiations in task and entry bodies are not flagged. Instantiations in the
21424 bodies of protected subprograms are flagged.
21425
21426 This rule has no parameters.
21427
21428
21429
21430 @node Improper_Returns
21431 @subsection @code{Improper_Returns}
21432 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21433
21434 @noindent
21435 Flag each explicit @code{return} statement in procedures, and
21436 multiple @code{return} statements in functions.
21437 Diagnostic messages are generated for all @code{return} statements
21438 in a procedure (thus each procedure must be written so that it
21439 returns implicitly at the end of its statement part),
21440 and for all @code{return} statements in a function after the first one.
21441 This rule supports the stylistic convention that each subprogram
21442 should have no more than one point of normal return.
21443
21444 This rule has no parameters.
21445
21446
21447 @node Library_Level_Subprograms
21448 @subsection @code{Library_Level_Subprograms}
21449 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21450
21451 @noindent
21452 Flag all library-level subprograms (including generic subprogram instantiations).
21453
21454 This rule has no parameters.
21455
21456
21457 @node Local_Packages
21458 @subsection @code{Local_Packages}
21459 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21460
21461 @noindent
21462 Flag all local packages declared in package and generic package
21463 specs.
21464 Local packages in bodies are not flagged.
21465
21466 This rule has no parameters.
21467
21468 @ignore
21469 @node Improperly_Called_Protected_Entries
21470 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21471 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21472
21473 @noindent
21474 Flag each protected entry that can be called from more than one task.
21475
21476 This rule has no parameters.
21477 @end ignore
21478
21479 @node Metrics
21480 @subsection @code{Metrics}
21481 @cindex @code{Metrics} rule (for @command{gnatcheck})
21482
21483 @noindent
21484 There is a set of checks based on computing a metric value and comparing the
21485 result with the specified upper (or lower, depending on a specific metric)
21486 value specified for a given metric. A construct is flagged if a given metric
21487 is applicable (can be computed) for it and the computed value is greater
21488 then (lover then) the specified upper (lower) bound.
21489
21490 The name of any metric-based rule consists of the prefix @code{Metrics_}
21491 followed by the name of the corresponding metric (see the table below).
21492 For @option{+R} option, each metric-based rule has a numeric parameter
21493 specifying the bound (integer or real, depending on a metric), @option{-R}
21494 option for metric rules does not have a parameter.
21495
21496 The following table shows the metric names for that the corresponding
21497 metrics-based checks are supported by gnatcheck, including the
21498 constraint that must be satisfied by the bound that is specified for the check
21499 and what bound - upper (U) or lower (L) - should be specified.
21500
21501 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21502 @ifnothtml
21503 @headitem Check Name @tab Description @tab Bounds Value
21504 @end ifnothtml
21505 @ifhtml
21506 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21507 @end ifhtml
21508 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21509 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21510 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21511 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21512 @end multitable
21513
21514 @noindent
21515 The meaning and the computed values for all these metrics are exactly
21516 the same as for the corresponding metrics in @command{gnatmetric}.
21517
21518 @emph{Example:} the rule
21519 @smallexample
21520 +RMetrics_Cyclomatic_Complexity : 7
21521 @end smallexample
21522 @noindent
21523 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21524
21525 To turn OFF the check for cyclomatic complexity metric, use the following option:
21526 @smallexample
21527 -RMetrics_Cyclomatic_Complexity
21528 @end smallexample
21529
21530 @node Misnamed_Identifiers
21531 @subsection @code{Misnamed_Identifiers}
21532 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21533
21534 @noindent
21535 Flag the declaration of each identifier that does not have a suffix
21536 corresponding to the kind of entity being declared.
21537 The following declarations are checked:
21538
21539 @itemize @bullet
21540 @item
21541 type declarations
21542
21543 @item
21544 subtype declarations
21545
21546 @item
21547 constant declarations (but not number declarations)
21548
21549 @item
21550 package renaming declarations (but not generic package renaming
21551 declarations)
21552 @end itemize
21553
21554 @noindent
21555 This rule may have parameters. When used without parameters, the rule enforces
21556 the following checks:
21557
21558 @itemize @bullet
21559 @item
21560 type-defining names end with @code{_T}, unless the type is an access type,
21561 in which case the suffix must be @code{_A}
21562 @item
21563 constant names end with @code{_C}
21564 @item
21565 names defining package renamings end with @code{_R}
21566 @end itemize
21567
21568 @noindent
21569 For a private or incomplete type declaration the following checks are
21570 made for the defining name suffix:
21571
21572 @itemize @bullet
21573 @item
21574 For an incomplete type declaration: if the corresponding full type
21575 declaration is available, the defining identifier from the full type
21576 declaration is checked, but the defining identifier from the incomplete type
21577 declaration is not; otherwise the defining identifier from the incomplete
21578 type declaration is checked against the suffix specified for type
21579 declarations.
21580
21581 @item
21582 For a private type declaration (including private extensions),  the defining
21583 identifier from the private type declaration is checked against the type
21584 suffix (even if the corresponding full declaration is an access type
21585 declaration), and the defining identifier from the corresponding full type
21586 declaration is not checked.
21587 @end itemize
21588
21589 @noindent
21590 For a deferred constant, the defining name in the corresponding full constant
21591 declaration is not checked.
21592
21593 Defining names of formal types are not checked.
21594
21595 The rule may have the following parameters:
21596
21597 @itemize @bullet
21598 @item
21599 For the @option{+R} option:
21600 @table @code
21601 @item Default
21602 Sets the default listed above for all the names to be checked.
21603
21604 @item Type_Suffix=@emph{string}
21605 Specifies the suffix for a type name.
21606
21607 @item Access_Suffix=@emph{string}
21608 Specifies the suffix for an access type name. If
21609 this parameter is set, it overrides for access
21610 types the suffix set by the @code{Type_Suffix} parameter.
21611 For access types, @emph{string} may have the following format:
21612 @emph{suffix1(suffix2)}. That means that an access type name
21613 should have the @emph{suffix1} suffix except for the case when
21614 the designated type is also an access type, in this case the
21615 type name should have the @emph{suffix1 & suffix2} suffix.
21616
21617 @item Class_Access_Suffix=@emph{string}
21618 Specifies the suffix for the name of an access type that points to some class-wide
21619 type. If this parameter is set, it overrides for such access
21620 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
21621 parameter.
21622
21623 @item Class_Subtype_Suffix=@emph{string}
21624 Specifies the suffix for the name of a subtype that denotes a class-wide type.
21625
21626 @item Constant_Suffix=@emph{string}
21627 Specifies the suffix for a constant name.
21628
21629 @item Renaming_Suffix=@emph{string}
21630 Specifies the suffix for a package renaming name.
21631 @end table
21632
21633 @item
21634 For the @option{-R} option:
21635 @table @code
21636 @item All_Suffixes
21637 Remove all the suffixes specified for the
21638 identifier suffix checks, whether by default or
21639 as specified by other rule parameters. All the
21640 checks for this rule are disabled as a result.
21641
21642 @item Type_Suffix
21643 Removes the suffix specified for types. This
21644 disables checks for types but does not disable
21645 any other checks for this rule (including the
21646 check for access type names if @code{Access_Suffix} is
21647 set).
21648
21649 @item Access_Suffix
21650 Removes the suffix specified for access types.
21651 This disables checks for access type names but
21652 does not disable any other checks for this rule.
21653 If @code{Type_Suffix} is set, access type names are
21654 checked as ordinary type names.
21655
21656 @item Class_Access_Suffix
21657 Removes the suffix specified for access types pointing to class-wide
21658 type. This disables specific checks for names of access types pointing to
21659 class-wide types but does not disable any other checks for this rule.
21660 If @code{Type_Suffix} is set, access type names are
21661 checked as ordinary type names. If @code{Access_Suffix} is set, these
21662 access types are checked as any other access type name.
21663
21664 @item Class_Subtype_Suffix=@emph{string}
21665 Removes the suffix specified for subtype names.
21666 This disables checks for subtype names but
21667 does not disable any other checks for this rule.
21668
21669 @item Constant_Suffix
21670 Removes the suffix specified for constants. This
21671 disables checks for constant names but does not
21672 disable any other checks for this rule.
21673
21674 @item Renaming_Suffix
21675 Removes the suffix specified for package
21676 renamings. This disables checks for package
21677 renamings but does not disable any other checks
21678 for this rule.
21679 @end table
21680 @end itemize
21681
21682 @noindent
21683 If more than one parameter is used, parameters must be separated by commas.
21684
21685 If more than one  option is specified for the @command{gnatcheck} invocation,
21686 a new option overrides the previous one(s).
21687
21688 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21689 checks for all the
21690 name suffixes specified by previous options used for this rule.
21691
21692 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21693 all the checks but keeps
21694 all the suffixes specified by previous options used for this rule.
21695
21696 The @emph{string} value must be a valid suffix for an Ada identifier (after
21697 trimming all the leading and trailing space characters, if any).
21698 Parameters are not case sensitive, except the @emph{string} part.
21699
21700 If any error is detected in a rule parameter, the parameter is ignored.
21701 In such a case the options that are set for the rule are not
21702 specified.
21703
21704
21705
21706 @node Multiple_Entries_In_Protected_Definitions
21707 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21708 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21709
21710 @noindent
21711 Flag each protected definition (i.e., each protected object/type declaration)
21712 that defines more than one entry.
21713 Diagnostic messages are generated for all the entry declarations
21714 except the first one. An entry family is counted as one entry. Entries from
21715 the private part of the protected definition are also checked.
21716
21717 This rule has no parameters.
21718
21719 @node Name_Clashes
21720 @subsection @code{Name_Clashes}
21721 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21722
21723 @noindent
21724 Check that certain names are not used as defining identifiers. To activate
21725 this rule, you need to supply a reference to the dictionary file(s) as a rule
21726 parameter(s) (more then one dictionary file can be specified). If no
21727 dictionary file is set, this rule will not cause anything to be flagged.
21728 Only defining occurrences, not references, are checked.
21729 The check is not case-sensitive.
21730
21731 This rule is enabled by default, but without setting any corresponding
21732 dictionary file(s); thus the default effect is to do no checks.
21733
21734 A dictionary file is a plain text file. The maximum line length for this file
21735 is 1024 characters.  If the line is longer then this limit, extra characters
21736 are ignored.
21737
21738 Each line can be either an empty line, a comment line, or a line containing
21739 a list of identifiers separated by space or HT characters.
21740 A comment is an Ada-style comment (from @code{--} to end-of-line).
21741 Identifiers must follow the Ada syntax for identifiers.
21742 A line containing one or more identifiers may end with a comment.
21743
21744 @node Non_Qualified_Aggregates
21745 @subsection @code{Non_Qualified_Aggregates}
21746 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21747
21748 @noindent
21749 Flag each non-qualified aggregate.
21750 A non-qualified aggregate is an
21751 aggregate that is not the expression of a qualified expression. A
21752 string literal is not considered an aggregate, but an array
21753 aggregate of a string type is considered as a normal aggregate.
21754 Aggregates of anonymous array types are not flagged.
21755
21756 This rule has no parameters.
21757
21758
21759 @node Non_Short_Circuit_Operators
21760 @subsection @code{Non_Short_Circuit_Operators}
21761 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21762
21763 @noindent
21764 Flag all calls to predefined @code{and} and @code{or} operators for
21765 any boolean type. Calls to
21766 user-defined @code{and} and @code{or} and to operators defined by renaming
21767 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21768 operators for modular types or boolean array types are not flagged.
21769
21770 This rule has no parameters.
21771
21772
21773
21774 @node Non_SPARK_Attributes
21775 @subsection @code{Non_SPARK_Attributes}
21776 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21777
21778 @noindent
21779 The SPARK language defines the following subset of Ada 95 attribute
21780 designators as those that can be used in SPARK programs. The use of
21781 any other attribute is flagged.
21782
21783 @itemize @bullet
21784 @item @code{'Adjacent}
21785 @item @code{'Aft}
21786 @item @code{'Base}
21787 @item @code{'Ceiling}
21788 @item @code{'Component_Size}
21789 @item @code{'Compose}
21790 @item @code{'Copy_Sign}
21791 @item @code{'Delta}
21792 @item @code{'Denorm}
21793 @item @code{'Digits}
21794 @item @code{'Exponent}
21795 @item @code{'First}
21796 @item @code{'Floor}
21797 @item @code{'Fore}
21798 @item @code{'Fraction}
21799 @item @code{'Last}
21800 @item @code{'Leading_Part}
21801 @item @code{'Length}
21802 @item @code{'Machine}
21803 @item @code{'Machine_Emax}
21804 @item @code{'Machine_Emin}
21805 @item @code{'Machine_Mantissa}
21806 @item @code{'Machine_Overflows}
21807 @item @code{'Machine_Radix}
21808 @item @code{'Machine_Rounds}
21809 @item @code{'Max}
21810 @item @code{'Min}
21811 @item @code{'Model}
21812 @item @code{'Model_Emin}
21813 @item @code{'Model_Epsilon}
21814 @item @code{'Model_Mantissa}
21815 @item @code{'Model_Small}
21816 @item @code{'Modulus}
21817 @item @code{'Pos}
21818 @item @code{'Pred}
21819 @item @code{'Range}
21820 @item @code{'Remainder}
21821 @item @code{'Rounding}
21822 @item @code{'Safe_First}
21823 @item @code{'Safe_Last}
21824 @item @code{'Scaling}
21825 @item @code{'Signed_Zeros}
21826 @item @code{'Size}
21827 @item @code{'Small}
21828 @item @code{'Succ}
21829 @item @code{'Truncation}
21830 @item @code{'Unbiased_Rounding}
21831 @item @code{'Val}
21832 @item @code{'Valid}
21833 @end itemize
21834
21835 @noindent
21836 This rule has no parameters.
21837
21838
21839 @node Non_Tagged_Derived_Types
21840 @subsection @code{Non_Tagged_Derived_Types}
21841 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21842
21843 @noindent
21844 Flag all derived type declarations that do not have a record extension part.
21845
21846 This rule has no parameters.
21847
21848
21849
21850 @node Non_Visible_Exceptions
21851 @subsection @code{Non_Visible_Exceptions}
21852 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21853
21854 @noindent
21855 Flag constructs leading to the possibility of propagating an exception
21856 out of the scope in which the exception is declared.
21857 Two cases are detected:
21858
21859 @itemize @bullet
21860 @item
21861 An exception declaration in a subprogram body, task body or block
21862 statement is flagged if the body or statement does not contain a handler for
21863 that exception or a handler with an @code{others} choice.
21864
21865 @item
21866 A @code{raise} statement in an exception handler of a subprogram body,
21867 task body or block statement is flagged if it (re)raises a locally
21868 declared exception.  This may occur under the following circumstances:
21869 @itemize @minus
21870 @item
21871 it explicitly raises a locally declared exception, or
21872 @item
21873 it does not specify an exception name (i.e., it is simply @code{raise;})
21874 and the enclosing handler contains a locally declared exception in its
21875 exception choices.
21876 @end itemize
21877 @end itemize
21878
21879 @noindent
21880 Renamings of local exceptions are not flagged.
21881
21882 This rule has no parameters.
21883
21884
21885 @node Numeric_Literals
21886 @subsection @code{Numeric_Literals}
21887 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21888
21889 @noindent
21890 Flag each use of a numeric literal in an index expression, and in any
21891 circumstance except for the following:
21892
21893 @itemize @bullet
21894 @item
21895 a literal occurring in the initialization expression for a constant
21896 declaration or a named number declaration, or
21897
21898 @item
21899 an integer literal that is less than or equal to a value
21900 specified by the @option{N} rule parameter.
21901 @end itemize
21902
21903 @noindent
21904 This rule may have the following parameters for the @option{+R} option:
21905
21906 @table @asis
21907 @item @emph{N}
21908 @emph{N} is an integer literal used as the maximal value that is not flagged
21909 (i.e., integer literals not exceeding this value are allowed)
21910
21911 @item @code{ALL}
21912 All integer literals are flagged
21913 @end table
21914
21915 @noindent
21916 If no parameters are set, the maximum unflagged value is 1.
21917
21918 The last specified check limit (or the fact that there is no limit at
21919 all) is used when multiple @option{+R} options appear.
21920
21921 The @option{-R} option for this rule has no parameters.
21922 It disables the rule but retains the last specified maximum unflagged value.
21923 If the @option{+R} option subsequently appears, this value is used as the
21924 threshold for the check.
21925
21926
21927 @node OTHERS_In_Aggregates
21928 @subsection @code{OTHERS_In_Aggregates}
21929 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21930
21931 @noindent
21932 Flag each use of an @code{others} choice in extension aggregates.
21933 In record and array aggregates, an @code{others} choice is flagged unless
21934 it is used to refer to all components, or to all but one component.
21935
21936 If, in case of a named array aggregate, there are two associations, one
21937 with an @code{others} choice and another with a discrete range, the
21938 @code{others} choice is flagged even if the discrete range specifies
21939 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21940
21941 This rule has no parameters.
21942
21943 @node OTHERS_In_CASE_Statements
21944 @subsection @code{OTHERS_In_CASE_Statements}
21945 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21946
21947 @noindent
21948 Flag any use of an @code{others} choice in a @code{case} statement.
21949
21950 This rule has no parameters.
21951
21952 @node OTHERS_In_Exception_Handlers
21953 @subsection @code{OTHERS_In_Exception_Handlers}
21954 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21955
21956 @noindent
21957 Flag any use of an @code{others} choice in an exception handler.
21958
21959 This rule has no parameters.
21960
21961
21962 @node Outer_Loop_Exits
21963 @subsection @code{Outer_Loop_Exits}
21964 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21965
21966 @noindent
21967 Flag each @code{exit} statement containing a loop name that is not the name
21968 of the immediately enclosing @code{loop} statement.
21969
21970 This rule has no parameters.
21971
21972
21973 @node Overloaded_Operators
21974 @subsection @code{Overloaded_Operators}
21975 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21976
21977 @noindent
21978 Flag each function declaration that overloads an operator symbol.
21979 A function body is checked only if the body does not have a
21980 separate spec. Formal functions are also checked. For a
21981 renaming declaration, only renaming-as-declaration is checked
21982
21983 This rule has no parameters.
21984
21985
21986 @node Overly_Nested_Control_Structures
21987 @subsection @code{Overly_Nested_Control_Structures}
21988 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21989
21990 @noindent
21991 Flag each control structure whose nesting level exceeds the value provided
21992 in the rule parameter.
21993
21994 The control structures checked are the following:
21995
21996 @itemize @bullet
21997 @item    @code{if} statement
21998 @item    @code{case} statement
21999 @item    @code{loop} statement
22000 @item    Selective accept statement
22001 @item    Timed entry call statement
22002 @item    Conditional entry call
22003 @item    Asynchronous select statement
22004 @end itemize
22005
22006 @noindent
22007 The rule has the following parameter for the @option{+R} option:
22008
22009 @table @emph
22010 @item N
22011 Positive integer specifying the maximal control structure nesting
22012 level that is not flagged
22013 @end table
22014
22015 @noindent
22016 If the parameter for the @option{+R} option is not specified or
22017 if it is not a positive integer, @option{+R} option is ignored.
22018
22019 If more then one  option is specified for the gnatcheck call, the later option and
22020 new parameter override the previous one(s).
22021
22022
22023 @node Parameters_Out_Of_Order
22024 @subsection @code{Parameters_Out_Of_Order}
22025 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22026
22027 @noindent
22028 Flag each subprogram and entry declaration whose formal parameters are not
22029 ordered according to the following scheme:
22030
22031 @itemize @bullet
22032
22033 @item @code{in} and @code{access} parameters first,
22034 then @code{in out} parameters,
22035 and then @code{out} parameters;
22036
22037 @item for @code{in} mode, parameters with default initialization expressions
22038 occur last
22039 @end itemize
22040
22041 @noindent
22042 Only the first violation of the described order is flagged.
22043
22044 The following constructs are checked:
22045
22046 @itemize @bullet
22047 @item   subprogram declarations (including null procedures);
22048 @item   generic subprogram declarations;
22049 @item   formal subprogram declarations;
22050 @item   entry declarations;
22051 @item   subprogram bodies and subprogram body stubs that do not
22052 have separate specifications
22053 @end itemize
22054
22055 @noindent
22056 Subprogram renamings are not checked.
22057
22058 This rule has no parameters.
22059
22060
22061 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22062 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22063 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22064
22065 @noindent
22066 Flag each generic actual parameter corresponding to a generic formal
22067 parameter with a default initialization, if positional notation is used.
22068
22069 This rule has no parameters.
22070
22071 @node Positional_Actuals_For_Defaulted_Parameters
22072 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22073 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22074
22075 @noindent
22076 Flag each actual parameter to a subprogram or entry call where the
22077 corresponding formal parameter has a default expression, if positional
22078 notation is used.
22079
22080 This rule has no parameters.
22081
22082 @node Positional_Components
22083 @subsection @code{Positional_Components}
22084 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22085
22086 @noindent
22087 Flag each array, record and extension aggregate that includes positional
22088 notation.
22089
22090 This rule has no parameters.
22091
22092
22093 @node Positional_Generic_Parameters
22094 @subsection @code{Positional_Generic_Parameters}
22095 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22096
22097 @noindent
22098 Flag each instantiation using positional parameter notation.
22099
22100 This rule has no parameters.
22101
22102
22103 @node Positional_Parameters
22104 @subsection @code{Positional_Parameters}
22105 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22106
22107 @noindent
22108 Flag each subprogram or entry call using positional parameter notation,
22109 except for the following:
22110
22111 @itemize @bullet
22112 @item
22113 Invocations of prefix or infix operators are not flagged
22114 @item
22115 If the called subprogram or entry has only one formal parameter,
22116 the call is not flagged;
22117 @item
22118 If a subprogram call uses the @emph{Object.Operation} notation, then
22119 @itemize @minus
22120 @item
22121 the first parameter (that is, @emph{Object}) is not flagged;
22122 @item
22123 if the called subprogram has only two parameters, the second parameter
22124 of the call is not flagged;
22125 @end itemize
22126 @end itemize
22127
22128 @noindent
22129 This rule has no parameters.
22130
22131
22132
22133
22134 @node Predefined_Numeric_Types
22135 @subsection @code{Predefined_Numeric_Types}
22136 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22137
22138 @noindent
22139 Flag each explicit use of the name of any numeric type or subtype defined
22140 in package @code{Standard}.
22141
22142 The rationale for this rule is to detect when the
22143 program may depend on platform-specific characteristics of the implementation
22144 of the predefined numeric types. Note that this rule is over-pessimistic;
22145 for example, a program that uses @code{String} indexing
22146 likely needs a variable of type @code{Integer}.
22147 Another example is the flagging of predefined numeric types with explicit
22148 constraints:
22149
22150 @smallexample @c ada
22151     subtype My_Integer is Integer range Left .. Right;
22152     Vy_Var : My_Integer;
22153 @end smallexample
22154
22155 @noindent
22156 This rule detects only numeric types and subtypes defined in
22157 @code{Standard}. The use of numeric types and subtypes defined in other
22158 predefined packages (such as @code{System.Any_Priority} or
22159 @code{Ada.Text_IO.Count}) is not flagged
22160
22161 This rule has no parameters.
22162
22163
22164
22165 @node Raising_External_Exceptions
22166 @subsection @code{Raising_External_Exceptions}
22167 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22168
22169 @noindent
22170 Flag any @code{raise} statement, in a program unit declared in a library
22171 package or in a generic library package, for an exception that is
22172 neither a predefined exception nor an exception that is also declared (or
22173 renamed) in the visible part of the package.
22174
22175 This rule has no parameters.
22176
22177
22178
22179 @node Raising_Predefined_Exceptions
22180 @subsection @code{Raising_Predefined_Exceptions}
22181 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22182
22183 @noindent
22184 Flag each @code{raise} statement that raises a predefined exception
22185 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22186 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22187
22188 This rule has no parameters.
22189
22190 @node Separate_Numeric_Error_Handlers
22191 @subsection @code{Separate_Numeric_Error_Handlers}
22192 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22193
22194 @noindent
22195 Flags each exception handler that contains a choice for
22196 the predefined @code{Constraint_Error} exception, but does not contain
22197 the choice for the predefined @code{Numeric_Error} exception, or
22198 that contains the choice for @code{Numeric_Error}, but does not contain the
22199 choice for @code{Constraint_Error}.
22200
22201 This rule has no parameters.
22202
22203 @ignore
22204 @node Recursion
22205 @subsection @code{Recursion} (under construction, GLOBAL)
22206 @cindex @code{Recursion} rule (for @command{gnatcheck})
22207
22208 @noindent
22209 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22210 calls, of recursive subprograms are detected.
22211
22212 This rule has no parameters.
22213 @end ignore
22214
22215 @ignore
22216 @node Side_Effect_Functions
22217 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22218 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22219
22220 @noindent
22221 Flag functions with side effects.
22222
22223 We define a side effect as changing any data object that is not local for the
22224 body of this function.
22225
22226 At the moment, we do NOT consider a side effect any input-output operations
22227 (changing a state or a content of any file).
22228
22229 We do not consider protected functions for this rule (???)
22230
22231 There are the following sources of side effect:
22232
22233 @enumerate
22234 @item Explicit (or direct) side-effect:
22235
22236 @itemize @bullet
22237 @item
22238 direct assignment to a non-local variable;
22239
22240 @item
22241 direct call to an entity that is known to change some data object that is
22242      not local for the body of this function (Note, that if F1 calls F2 and F2
22243      does have a side effect, this does not automatically mean that F1 also
22244      have a side effect, because it may be the case that F2 is declared in
22245      F1's body and it changes some data object that is global for F2, but
22246      local for F1);
22247 @end itemize
22248
22249 @item Indirect side-effect:
22250 @itemize @bullet
22251 @item
22252 Subprogram calls implicitly issued by:
22253 @itemize @bullet
22254 @item
22255 computing initialization expressions from type declarations as a part
22256          of object elaboration or allocator evaluation;
22257 @item
22258 computing implicit parameters of subprogram or entry calls or generic
22259          instantiations;
22260 @end itemize
22261
22262 @item
22263 activation of a task that change some non-local data object (directly or
22264      indirectly);
22265
22266 @item
22267 elaboration code of a package that is a result of a package instantiation;
22268
22269 @item
22270 controlled objects;
22271 @end itemize
22272
22273 @item Situations when we can suspect a side-effect, but the full static check
22274 is either impossible or too hard:
22275 @itemize @bullet
22276 @item
22277 assignment to access variables or to the objects pointed by access
22278      variables;
22279
22280 @item
22281 call to a subprogram pointed by access-to-subprogram value
22282
22283 @item
22284 dispatching calls;
22285 @end itemize
22286 @end enumerate
22287
22288 @noindent
22289 This rule has no parameters.
22290 @end ignore
22291
22292 @node Slices
22293 @subsection @code{Slices}
22294 @cindex @code{Slices} rule (for @command{gnatcheck})
22295
22296 @noindent
22297 Flag all uses of array slicing
22298
22299 This rule has no parameters.
22300
22301
22302 @node Unassigned_OUT_Parameters
22303 @subsection @code{Unassigned_OUT_Parameters}
22304 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22305
22306 @noindent
22307 Flags procedures' @code{out} parameters that are not assigned, and
22308 identifies the contexts in which the assignments are missing.
22309
22310 An @code{out} parameter is flagged in the statements in the procedure
22311 body's handled sequence of statements (before the procedure body's
22312 @code{exception} part, if any) if this sequence of statements contains
22313 no assignments to the parameter.
22314
22315 An @code{out} parameter is flagged in an exception handler in the exception
22316 part of the procedure body's handled sequence of statements if the handler
22317 contains no assignment to the parameter.
22318
22319 Bodies of generic procedures are also considered.
22320
22321 The following are treated as assignments to an @code{out} parameter:
22322
22323 @itemize @bullet
22324 @item
22325 an assignment statement, with the parameter or some component as the target;
22326
22327 @item
22328 passing the parameter (or one of its components) as an @code{out} or
22329 @code{in out} parameter.
22330 @end itemize
22331
22332 @noindent
22333 This rule does not have any parameters.
22334
22335
22336
22337 @node Uncommented_BEGIN_In_Package_Bodies
22338 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22339 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22340
22341 @noindent
22342 Flags each package body with declarations and a statement part that does not
22343 include a trailing comment on the line containing the @code{begin} keyword;
22344 this trailing comment needs to specify the package name and nothing else.
22345 The @code{begin} is not flagged if the package body does not
22346 contain any declarations.
22347
22348 If the @code{begin} keyword is placed on the
22349 same line as the last declaration or the first statement, it is flagged
22350 independently of whether the line contains a trailing comment. The
22351 diagnostic message is attached to the line containing the first statement.
22352
22353 This rule has no parameters.
22354
22355 @node Unconditional_Exits
22356 @subsection @code{Unconditional_Exits}
22357 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22358
22359 @noindent
22360 Flag unconditional @code{exit} statements.
22361
22362 This rule has no parameters.
22363
22364 @node Unconstrained_Array_Returns
22365 @subsection @code{Unconstrained_Array_Returns}
22366 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22367
22368 @noindent
22369 Flag each function returning an unconstrained array. Function declarations,
22370 function bodies (and body stubs) having no separate specifications,
22371 and generic function instantiations are checked.
22372 Generic function declarations, function calls and function renamings are
22373 not checked.
22374
22375 This rule has no parameters.
22376
22377 @node Universal_Ranges
22378 @subsection @code{Universal_Ranges}
22379 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22380
22381 @noindent
22382 Flag discrete ranges that are a part of an index constraint, constrained
22383 array definition, or @code{for}-loop parameter specification, and whose bounds
22384 are both of type @i{universal_integer}. Ranges that have at least one
22385 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22386 or an expression of non-universal type) are not flagged.
22387
22388 This rule has no parameters.
22389
22390
22391 @node Unnamed_Blocks_And_Loops
22392 @subsection @code{Unnamed_Blocks_And_Loops}
22393 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22394
22395 @noindent
22396 Flag each unnamed block statement and loop statement.
22397
22398 The rule has no parameters.
22399
22400
22401
22402 @ignore
22403 @node Unused_Subprograms
22404 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22405 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22406
22407 @noindent
22408 Flag all unused subprograms.
22409
22410 This rule has no parameters.
22411 @end ignore
22412
22413
22414
22415
22416 @node USE_PACKAGE_Clauses
22417 @subsection @code{USE_PACKAGE_Clauses}
22418 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22419
22420 @noindent
22421 Flag all @code{use} clauses for packages; @code{use type} clauses are
22422 not flagged.
22423
22424 This rule has no parameters.
22425
22426
22427
22428 @node Volatile_Objects_Without_Address_Clauses
22429 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22430 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22431
22432 @noindent
22433 Flag each volatile object that does not have an address clause.
22434
22435 The following check is made: if the pragma @code{Volatile} is applied to a
22436 data object or to its type, then an address clause must
22437 be supplied for this object.
22438
22439 This rule does not check the components of data objects,
22440 array components that are volatile as a result of the pragma
22441 @code{Volatile_Components}, or objects that are volatile because
22442 they are atomic as a result of pragmas @code{Atomic} or
22443 @code{Atomic_Components}.
22444
22445 Only variable declarations, and not constant declarations, are checked.
22446
22447 This rule has no parameters.
22448
22449
22450 @c *********************************
22451 @node Creating Sample Bodies Using gnatstub
22452 @chapter Creating Sample Bodies Using @command{gnatstub}
22453 @findex gnatstub
22454
22455 @noindent
22456 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22457 for library unit declarations.
22458
22459 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22460 driver (see @ref{The GNAT Driver and Project Files}).
22461
22462 To create a body stub, @command{gnatstub} has to compile the library
22463 unit declaration. Therefore, bodies can be created only for legal
22464 library units. Moreover, if a library unit depends semantically upon
22465 units located outside the current directory, you have to provide
22466 the source search path when calling @command{gnatstub}, see the description
22467 of @command{gnatstub} switches below.
22468
22469 By default, all the program unit body stubs generated by @code{gnatstub}
22470 raise the predefined @code{Program_Error} exception, which will catch
22471 accidental calls of generated stubs. This behavior can be changed with
22472 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22473
22474 @menu
22475 * Running gnatstub::
22476 * Switches for gnatstub::
22477 @end menu
22478
22479 @node Running gnatstub
22480 @section Running @command{gnatstub}
22481
22482 @noindent
22483 @command{gnatstub} has the command-line interface of the form
22484
22485 @smallexample
22486 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22487 @end smallexample
22488
22489 @noindent
22490 where
22491 @table @var
22492 @item filename
22493 is the name of the source file that contains a library unit declaration
22494 for which a body must be created. The file name may contain the path
22495 information.
22496 The file name does not have to follow the GNAT file name conventions. If the
22497 name
22498 does not follow GNAT file naming conventions, the name of the body file must
22499 be provided
22500 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22501 If the file name follows the GNAT file naming
22502 conventions and the name of the body file is not provided,
22503 @command{gnatstub}
22504 creates the name
22505 of the body file from the argument file name by replacing the @file{.ads}
22506 suffix
22507 with the @file{.adb} suffix.
22508
22509 @item directory
22510 indicates the directory in which the body stub is to be placed (the default
22511 is the
22512 current directory)
22513
22514 @item switches
22515 is an optional sequence of switches as described in the next section
22516 @end table
22517
22518 @node Switches for gnatstub
22519 @section Switches for @command{gnatstub}
22520
22521 @table @option
22522 @c !sort!
22523
22524 @item ^-f^/FULL^
22525 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22526 If the destination directory already contains a file with the name of the
22527 body file
22528 for the argument spec file, replace it with the generated body stub.
22529
22530 @item ^-hs^/HEADER=SPEC^
22531 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22532 Put the comment header (i.e., all the comments preceding the
22533 compilation unit) from the source of the library unit declaration
22534 into the body stub.
22535
22536 @item ^-hg^/HEADER=GENERAL^
22537 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22538 Put a sample comment header into the body stub.
22539
22540 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22541 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22542 Use the content of the file as the comment header for a generated body stub.
22543
22544 @ifclear vms
22545 @item -IDIR
22546 @cindex @option{-IDIR} (@command{gnatstub})
22547 @itemx -I-
22548 @cindex @option{-I-} (@command{gnatstub})
22549 @end ifclear
22550 @ifset vms
22551 @item /NOCURRENT_DIRECTORY
22552 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22553 @end ifset
22554 ^These switches have ^This switch has^ the same meaning as in calls to
22555 @command{gcc}.
22556 ^They define ^It defines ^ the source search path in the call to
22557 @command{gcc} issued
22558 by @command{gnatstub} to compile an argument source file.
22559
22560 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22561 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22562 This switch has the same meaning as in calls to @command{gcc}.
22563 It defines the additional configuration file to be passed to the call to
22564 @command{gcc} issued
22565 by @command{gnatstub} to compile an argument source file.
22566
22567 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22568 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22569 (@var{n} is a non-negative integer). Set the maximum line length in the
22570 body stub to @var{n}; the default is 79. The maximum value that can be
22571 specified is 32767. Note that in the special case of configuration
22572 pragma files, the maximum is always 32767 regardless of whether or
22573 not this switch appears.
22574
22575 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22576 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22577 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22578 the generated body sample to @var{n}.
22579 The default indentation is 3.
22580
22581 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22582 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22583 Order local bodies alphabetically. (By default local bodies are ordered
22584 in the same way as the corresponding local specs in the argument spec file.)
22585
22586 @item ^-i^/INDENTATION=^@var{n}
22587 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22588 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22589
22590 @item ^-k^/TREE_FILE=SAVE^
22591 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22592 Do not remove the tree file (i.e., the snapshot of the compiler internal
22593 structures used by @command{gnatstub}) after creating the body stub.
22594
22595 @item ^-l^/LINE_LENGTH=^@var{n}
22596 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22597 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22598
22599 @item ^--no-exception^/NO_EXCEPTION^
22600 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22601 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22602 This is not always possible for function stubs.
22603
22604 @item ^-o ^/BODY=^@var{body-name}
22605 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22606 Body file name.  This should be set if the argument file name does not
22607 follow
22608 the GNAT file naming
22609 conventions. If this switch is omitted the default name for the body will be
22610 obtained
22611 from the argument file name according to the GNAT file naming conventions.
22612
22613 @item ^-q^/QUIET^
22614 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22615 Quiet mode: do not generate a confirmation when a body is
22616 successfully created, and do not generate a message when a body is not
22617 required for an
22618 argument unit.
22619
22620 @item ^-r^/TREE_FILE=REUSE^
22621 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22622 Reuse the tree file (if it exists) instead of creating it.  Instead of
22623 creating the tree file for the library unit declaration, @command{gnatstub}
22624 tries to find it in the current directory and use it for creating
22625 a body. If the tree file is not found, no body is created. This option
22626 also implies @option{^-k^/SAVE^}, whether or not
22627 the latter is set explicitly.
22628
22629 @item ^-t^/TREE_FILE=OVERWRITE^
22630 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22631 Overwrite the existing tree file.  If the current directory already
22632 contains the file which, according to the GNAT file naming rules should
22633 be considered as a tree file for the argument source file,
22634 @command{gnatstub}
22635 will refuse to create the tree file needed to create a sample body
22636 unless this option is set.
22637
22638 @item ^-v^/VERBOSE^
22639 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22640 Verbose mode: generate version information.
22641
22642 @end table
22643
22644 @c *********************************
22645 @node Generating Ada Bindings for C and C++ headers
22646 @chapter Generating Ada Bindings for C and C++ headers
22647 @findex binding
22648
22649 @noindent
22650 GNAT now comes with a new experimental binding generator for C and C++
22651 headers which is intended to do 95% of the tedious work of generating
22652 Ada specs from C or C++ header files. Note that this still is a work in
22653 progress, not designed to generate 100% correct Ada specs.
22654
22655 The code generated is using the Ada 2005 syntax, which makes it
22656 easier to interface with other languages than previous versions of Ada.
22657
22658 @menu
22659 * Running the binding generator::
22660 * Generating bindings for C++ headers::
22661 * Switches::
22662 @end menu
22663
22664 @node Running the binding generator
22665 @section Running the binding generator
22666
22667 @noindent
22668 The binding generator is part of the @command{gcc} compiler and can be
22669 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
22670 spec files for the header files specified on the command line, and all
22671 header files needed by these files transitivitely. For example:
22672
22673 @smallexample
22674 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
22675 $ gcc -c -gnat05 *.ads
22676 @end smallexample
22677
22678 will generate, under GNU/Linux, the following files: @file{time_h.ads},
22679 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
22680 correspond to the files @file{/usr/include/time.h},
22681 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
22682 mode these Ada specs.
22683
22684 The @code{-C} switch tells @command{gcc} to extract comments from headers,
22685 and will attempt to generate corresponding Ada comments.
22686
22687 If you want to generate a single Ada file and not the transitive closure, you
22688 can use instead the @option{-fdump-ada-spec-slim} switch.
22689
22690 Note that we recommend when possible to use the @command{g++} driver to
22691 generate bindings, even for most C headers, since this will in general
22692 generate better Ada specs. For generating bindings for C++ headers, it is
22693 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
22694 is equivalent in this case. If @command{g++} cannot work on your C headers
22695 because of incompatibilities between C and C++, then you can fallback to
22696 @command{gcc} instead.
22697
22698 For an example of better bindings generated from the C++ front-end,
22699 the name of the parameters (when available) are actually ignored by the C
22700 front-end. Consider the following C header:
22701
22702 @smallexample
22703 extern void foo (int variable);
22704 @end smallexample
22705
22706 with the C front-end, @code{variable} is ignored, and the above is handled as:
22707
22708 @smallexample
22709 extern void foo (int);
22710 @end smallexample
22711
22712 generating a generic:
22713
22714 @smallexample
22715 procedure foo (param1 : int);
22716 @end smallexample
22717
22718 with the C++ front-end, the name is available, and we generate:
22719
22720 @smallexample
22721 procedure foo (variable : int);
22722 @end smallexample
22723
22724 In some cases, the generated bindings will be more complete or more meaningful
22725 when defining some macros, which you can do via the @option{-D} switch. This
22726 is for example the case with @file{Xlib.h} under GNU/Linux:
22727
22728 @smallexample
22729 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
22730 @end smallexample
22731
22732 The above will generate more complete bindings than a straight call without
22733 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
22734
22735 In other cases, it is not possible to parse a header file in a stand alone
22736 manner, because other include files need to be included first. In this
22737 case, the solution is to create a small header file including the needed
22738 @code{#include} and possible @code{#define} directives. For example, to
22739 generate Ada bindings for @file{readline/readline.h}, you need to first
22740 include @file{stdio.h}, so you can create a file with the following two
22741 lines in e.g. @file{readline1.h}:
22742
22743 @smallexample
22744 #include <stdio.h>
22745 #include <readline/readline.h>
22746 @end smallexample
22747
22748 and then generate Ada bindings from this file:
22749
22750 @smallexample
22751 $ g++ -c -fdump-ada-spec readline1.h
22752 @end smallexample
22753
22754 @node Generating bindings for C++ headers
22755 @section Generating bindings for C++ headers
22756
22757 @noindent
22758 Generating bindings for C++ headers is done using the same options, always
22759 with the @command{g++} compiler.
22760
22761 In this mode, C++ classes will be mapped to Ada tagged types, constructors
22762 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
22763 multiple inheritance of abstract classes will be mapped to Ada interfaces
22764 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
22765 information on interfacing to C++).
22766
22767 For example, given the following C++ header file:
22768
22769 @smallexample
22770 @group
22771 @cartouche
22772 class Carnivore @{
22773 public:
22774    virtual int Number_Of_Teeth () = 0;
22775 @};
22776
22777 class Domestic @{
22778 public:
22779    virtual void Set_Owner (char* Name) = 0;
22780 @};
22781
22782 class Animal @{
22783 public:
22784   int Age_Count;
22785   virtual void Set_Age (int New_Age);
22786 @};
22787
22788 class Dog : Animal, Carnivore, Domestic @{
22789  public:
22790   int  Tooth_Count;
22791   char *Owner;
22792
22793   virtual int  Number_Of_Teeth ();
22794   virtual void Set_Owner (char* Name);
22795
22796   Dog();
22797 @};
22798 @end cartouche
22799 @end group
22800 @end smallexample
22801
22802 The corresponding Ada code is generated:
22803
22804 @smallexample @c ada
22805 @group
22806 @cartouche
22807   package Class_Carnivore is
22808     type Carnivore is limited interface;
22809     pragma Import (CPP, Carnivore);
22810
22811     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
22812   end;
22813   use Class_Carnivore;
22814
22815   package Class_Domestic is
22816     type Domestic is limited interface;
22817     pragma Import (CPP, Domestic);
22818
22819     procedure Set_Owner
22820       (this : access Domestic;
22821        Name : Interfaces.C.Strings.chars_ptr) is abstract;
22822   end;
22823   use Class_Domestic;
22824
22825   package Class_Animal is
22826     type Animal is tagged limited record
22827       Age_Count : aliased int;
22828     end record;
22829     pragma Import (CPP, Animal);
22830
22831     procedure Set_Age (this : access Animal; New_Age : int);
22832     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
22833   end;
22834   use Class_Animal;
22835
22836   package Class_Dog is
22837     type Dog is new Animal and Carnivore and Domestic with record
22838       Tooth_Count : aliased int;
22839       Owner : Interfaces.C.Strings.chars_ptr;
22840     end record;
22841     pragma Import (CPP, Dog);
22842
22843     function Number_Of_Teeth (this : access Dog) return int;
22844     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
22845
22846     procedure Set_Owner
22847       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
22848     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
22849
22850     function New_Dog return Dog;
22851     pragma CPP_Constructor (New_Dog);
22852     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
22853   end;
22854   use Class_Dog;
22855 @end cartouche
22856 @end group
22857 @end smallexample
22858
22859 @node Switches
22860 @section Switches
22861
22862 @table @option
22863 @item -fdump-ada-spec
22864 @cindex @option{-fdump-ada-spec} (@command{gcc})
22865 Generate Ada spec files for the given header files transitively (including
22866 all header files that these headers depend upon).
22867
22868 @item -fdump-ada-spec-slim
22869 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
22870 Generate Ada spec files for the header files specified on the command line
22871 only.
22872
22873 @item -C
22874 @cindex @option{-C} (@command{gcc})
22875 Extract comments from headers and generate Ada comments in the Ada spec files.
22876 @end table
22877
22878 @node Other Utility Programs
22879 @chapter Other Utility Programs
22880
22881 @noindent
22882 This chapter discusses some other utility programs available in the Ada
22883 environment.
22884
22885 @menu
22886 * Using Other Utility Programs with GNAT::
22887 * The External Symbol Naming Scheme of GNAT::
22888 * Converting Ada Files to html with gnathtml::
22889 * Installing gnathtml::
22890 @ifset vms
22891 * LSE::
22892 * Profiling::
22893 @end ifset
22894 @end menu
22895
22896 @node Using Other Utility Programs with GNAT
22897 @section Using Other Utility Programs with GNAT
22898
22899 @noindent
22900 The object files generated by GNAT are in standard system format and in
22901 particular the debugging information uses this format. This means
22902 programs generated by GNAT can be used with existing utilities that
22903 depend on these formats.
22904
22905 @ifclear vms
22906 In general, any utility program that works with C will also often work with
22907 Ada programs generated by GNAT. This includes software utilities such as
22908 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22909 as Purify.
22910 @end ifclear
22911
22912 @node The External Symbol Naming Scheme of GNAT
22913 @section The External Symbol Naming Scheme of GNAT
22914
22915 @noindent
22916 In order to interpret the output from GNAT, when using tools that are
22917 originally intended for use with other languages, it is useful to
22918 understand the conventions used to generate link names from the Ada
22919 entity names.
22920
22921 All link names are in all lowercase letters. With the exception of library
22922 procedure names, the mechanism used is simply to use the full expanded
22923 Ada name with dots replaced by double underscores. For example, suppose
22924 we have the following package spec:
22925
22926 @smallexample @c ada
22927 @group
22928 @cartouche
22929 package QRS is
22930    MN : Integer;
22931 end QRS;
22932 @end cartouche
22933 @end group
22934 @end smallexample
22935
22936 @noindent
22937 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22938 the corresponding link name is @code{qrs__mn}.
22939 @findex Export
22940 Of course if a @code{pragma Export} is used this may be overridden:
22941
22942 @smallexample @c ada
22943 @group
22944 @cartouche
22945 package Exports is
22946    Var1 : Integer;
22947    pragma Export (Var1, C, External_Name => "var1_name");
22948    Var2 : Integer;
22949    pragma Export (Var2, C, Link_Name => "var2_link_name");
22950 end Exports;
22951 @end cartouche
22952 @end group
22953 @end smallexample
22954
22955 @noindent
22956 In this case, the link name for @var{Var1} is whatever link name the
22957 C compiler would assign for the C function @var{var1_name}. This typically
22958 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22959 system conventions, but other possibilities exist. The link name for
22960 @var{Var2} is @var{var2_link_name}, and this is not operating system
22961 dependent.
22962
22963 @findex _main
22964 One exception occurs for library level procedures. A potential ambiguity
22965 arises between the required name @code{_main} for the C main program,
22966 and the name we would otherwise assign to an Ada library level procedure
22967 called @code{Main} (which might well not be the main program).
22968
22969 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22970 names. So if we have a library level procedure such as
22971
22972 @smallexample @c ada
22973 @group
22974 @cartouche
22975 procedure Hello (S : String);
22976 @end cartouche
22977 @end group
22978 @end smallexample
22979
22980 @noindent
22981 the external name of this procedure will be @var{_ada_hello}.
22982
22983
22984 @node Converting Ada Files to html with gnathtml
22985 @section Converting Ada Files to HTML with @code{gnathtml}
22986
22987 @noindent
22988 This @code{Perl} script allows Ada source files to be browsed using
22989 standard Web browsers. For installation procedure, see the section
22990 @xref{Installing gnathtml}.
22991
22992 Ada reserved keywords are highlighted in a bold font and Ada comments in
22993 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22994 switch to suppress the generation of cross-referencing information, user
22995 defined variables and types will appear in a different color; you will
22996 be able to click on any identifier and go to its declaration.
22997
22998 The command line is as follow:
22999 @smallexample
23000 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23001 @end smallexample
23002
23003 @noindent
23004 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23005 an html file for every ada file, and a global file called @file{index.htm}.
23006 This file is an index of every identifier defined in the files.
23007
23008 The available ^switches^options^ are the following ones:
23009
23010 @table @option
23011 @item -83
23012 @cindex @option{-83} (@code{gnathtml})
23013 Only the Ada 83 subset of keywords will be highlighted.
23014
23015 @item -cc @var{color}
23016 @cindex @option{-cc} (@code{gnathtml})
23017 This option allows you to change the color used for comments. The default
23018 value is green. The color argument can be any name accepted by html.
23019
23020 @item -d
23021 @cindex @option{-d} (@code{gnathtml})
23022 If the Ada files depend on some other files (for instance through
23023 @code{with} clauses, the latter files will also be converted to html.
23024 Only the files in the user project will be converted to html, not the files
23025 in the run-time library itself.
23026
23027 @item -D
23028 @cindex @option{-D} (@code{gnathtml})
23029 This command is the same as @option{-d} above, but @command{gnathtml} will
23030 also look for files in the run-time library, and generate html files for them.
23031
23032 @item -ext @var{extension}
23033 @cindex @option{-ext} (@code{gnathtml})
23034 This option allows you to change the extension of the generated HTML files.
23035 If you do not specify an extension, it will default to @file{htm}.
23036
23037 @item -f
23038 @cindex @option{-f} (@code{gnathtml})
23039 By default, gnathtml will generate html links only for global entities
23040 ('with'ed units, global variables and types,@dots{}).  If you specify
23041 @option{-f} on the command line, then links will be generated for local
23042 entities too.
23043
23044 @item -l @var{number}
23045 @cindex @option{-l} (@code{gnathtml})
23046 If this ^switch^option^ is provided and @var{number} is not 0, then
23047 @code{gnathtml} will number the html files every @var{number} line.
23048
23049 @item -I @var{dir}
23050 @cindex @option{-I} (@code{gnathtml})
23051 Specify a directory to search for library files (@file{.ALI} files) and
23052 source files. You can provide several -I switches on the command line,
23053 and the directories will be parsed in the order of the command line.
23054
23055 @item -o @var{dir}
23056 @cindex @option{-o} (@code{gnathtml})
23057 Specify the output directory for html files. By default, gnathtml will
23058 saved the generated html files in a subdirectory named @file{html/}.
23059
23060 @item -p @var{file}
23061 @cindex @option{-p} (@code{gnathtml})
23062 If you are using Emacs and the most recent Emacs Ada mode, which provides
23063 a full Integrated Development Environment for compiling, checking,
23064 running and debugging applications, you may use @file{.gpr} files
23065 to give the directories where Emacs can find sources and object files.
23066
23067 Using this ^switch^option^, you can tell gnathtml to use these files.
23068 This allows you to get an html version of your application, even if it
23069 is spread over multiple directories.
23070
23071 @item -sc @var{color}
23072 @cindex @option{-sc} (@code{gnathtml})
23073 This ^switch^option^ allows you to change the color used for symbol
23074 definitions.
23075 The default value is red. The color argument can be any name accepted by html.
23076
23077 @item -t @var{file}
23078 @cindex @option{-t} (@code{gnathtml})
23079 This ^switch^option^ provides the name of a file. This file contains a list of
23080 file names to be converted, and the effect is exactly as though they had
23081 appeared explicitly on the command line. This
23082 is the recommended way to work around the command line length limit on some
23083 systems.
23084
23085 @end table
23086
23087 @node Installing gnathtml
23088 @section Installing @code{gnathtml}
23089
23090 @noindent
23091 @code{Perl} needs to be installed on your machine to run this script.
23092 @code{Perl} is freely available for almost every architecture and
23093 Operating System via the Internet.
23094
23095 On Unix systems, you  may want to modify  the  first line of  the script
23096 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23097 is. The syntax of this line is:
23098 @smallexample
23099 #!full_path_name_to_perl
23100 @end smallexample
23101
23102 @noindent
23103 Alternatively, you may run the script using the following command line:
23104
23105 @smallexample
23106 $ perl gnathtml.pl @ovar{switches} @var{files}
23107 @end smallexample
23108
23109 @ifset vms
23110 @node LSE
23111 @section LSE
23112 @findex LSE
23113
23114 @noindent
23115 The GNAT distribution provides an Ada 95 template for the HP Language
23116 Sensitive Editor (LSE), a component of DECset. In order to
23117 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23118
23119 @node Profiling
23120 @section Profiling
23121 @findex PCA
23122
23123 @noindent
23124 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23125 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23126 the collection phase with the /DEBUG qualifier.
23127
23128 @smallexample
23129 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23130 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23131 $ RUN/DEBUG <PROGRAM_NAME>
23132 @end smallexample
23133 @noindent
23134 @end ifset
23135
23136 @ifclear vms
23137 @c ******************************
23138 @node Code Coverage and Profiling
23139 @chapter Code Coverage and Profiling
23140 @cindex Code Coverage
23141 @cindex Profiling
23142
23143 @noindent
23144 This chapter describes how to use @code{gcov} - coverage testing tool - and
23145 @code{gprof} - profiler tool - on your Ada programs.
23146
23147 @menu
23148 * Code Coverage of Ada Programs using gcov::
23149 * Profiling an Ada Program using gprof::
23150 @end menu
23151
23152 @node Code Coverage of Ada Programs using gcov
23153 @section Code Coverage of Ada Programs using gcov
23154 @cindex gcov
23155 @cindex -fprofile-arcs
23156 @cindex -ftest-coverage
23157 @cindex -coverage
23158 @cindex Code Coverage
23159
23160 @noindent
23161 @code{gcov} is a test coverage program: it analyzes the execution of a given
23162 program on selected tests, to help you determine the portions of the program
23163 that are still untested.
23164
23165 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23166 User's Guide. You can refer to this documentation for a more complete
23167 description.
23168
23169 This chapter provides a quick startup guide, and
23170 details some Gnat-specific features.
23171
23172 @menu
23173 * Quick startup guide::
23174 * Gnat specifics::
23175 @end menu
23176
23177 @node Quick startup guide
23178 @subsection Quick startup guide
23179
23180 In order to perform coverage analysis of a program using @code{gcov}, 3
23181 steps are needed:
23182
23183 @itemize @bullet
23184 @item
23185 Code instrumentation during the compilation process
23186 @item
23187 Execution of the instrumented program
23188 @item
23189 Execution of the @code{gcov} tool to generate the result.
23190 @end itemize
23191
23192 The code instrumentation needed by gcov is created at the object level:
23193 The source code is not modified in any way, because the instrumentation code is
23194 inserted by gcc during the compilation process. To compile your code with code
23195 coverage activated, you need to recompile your whole project using the
23196 switches
23197 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23198 @code{-fprofile-arcs}.
23199
23200 @smallexample
23201 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23202    -largs -fprofile-arcs
23203 @end smallexample
23204
23205 This compilation process will create @file{.gcno} files together with
23206 the usual object files.
23207
23208 Once the program is compiled with coverage instrumentation, you can
23209 run it as many times as needed - on portions of a test suite for
23210 example. The first execution will produce @file{.gcda} files at the
23211 same location as the @file{.gcno} files.  The following executions
23212 will update those files, so that a cumulative result of the covered
23213 portions of the program is generated.
23214
23215 Finally, you need to call the @code{gcov} tool. The different options of
23216 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23217
23218 This will create annotated source files with a @file{.gcov} extension:
23219 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23220
23221 @node Gnat specifics
23222 @subsection Gnat specifics
23223
23224 Because Ada semantics, portions of the source code may be shared among
23225 several object files. This is the case for example when generics are
23226 involved, when inlining is active  or when declarations generate  initialisation
23227 calls. In order to take
23228 into account this shared code, you need to call @code{gcov} on all
23229 source files of the tested program at once.
23230
23231 The list of source files might exceed the system's maximum command line
23232 length. In order to bypass this limitation, a new mechanism has been
23233 implemented in @code{gcov}: you can now list all your project's files into a
23234 text file, and provide this file to gcov as a parameter,  preceded by a @@
23235 (e.g. @samp{gcov @@mysrclist.txt}).
23236
23237 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23238 not supported as there can be unresolved symbols during the final link.
23239
23240 @node Profiling an Ada Program using gprof
23241 @section Profiling an Ada Program using gprof
23242 @cindex gprof
23243 @cindex -pg
23244 @cindex Profiling
23245
23246 @noindent
23247 This section is not meant to be an exhaustive documentation of @code{gprof}.
23248 Full documentation for it can be found in the GNU Profiler User's Guide
23249 documentation that is part of this GNAT distribution.
23250
23251 Profiling a program helps determine the parts of a program that are executed
23252 most often, and are therefore the most time-consuming.
23253
23254 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23255 better handle Ada programs and multitasking.
23256 It is currently supported on the following platforms
23257 @itemize @bullet
23258 @item
23259 linux x86/x86_64
23260 @item
23261 solaris sparc/sparc64/x86
23262 @item
23263 windows x86
23264 @end itemize
23265
23266 @noindent
23267 In order to profile a program using @code{gprof}, 3 steps are needed:
23268
23269 @itemize @bullet
23270 @item
23271 Code instrumentation, requiring a full recompilation of the project with the
23272 proper switches.
23273 @item
23274 Execution of the program under the analysis conditions, i.e. with the desired
23275 input.
23276 @item
23277 Analysis of the results using the @code{gprof} tool.
23278 @end itemize
23279
23280 @noindent
23281 The following sections detail the different steps, and indicate how
23282 to interpret the results:
23283 @menu
23284 * Compilation for profiling::
23285 * Program execution::
23286 * Running gprof::
23287 * Interpretation of profiling results::
23288 @end menu
23289
23290 @node Compilation for profiling
23291 @subsection Compilation for profiling
23292 @cindex -pg
23293 @cindex Profiling
23294
23295 In order to profile a program the first step is to tell the compiler
23296 to generate the necessary profiling information. The compiler switch to be used
23297 is @code{-pg}, which must be added to other compilation switches. This
23298 switch needs to be specified both during compilation and link stages, and can
23299 be specified once when using gnatmake:
23300
23301 @smallexample
23302 gnatmake -f -pg -P my_project
23303 @end smallexample
23304
23305 @noindent
23306 Note that only the objects that were compiled with the @samp{-pg} switch will be
23307 profiled; if you need to profile your whole project, use the
23308 @samp{-f} gnatmake switch to force full recompilation.
23309
23310 @node Program execution
23311 @subsection Program execution
23312
23313 @noindent
23314 Once the program has been compiled for profiling, you can run it as usual.
23315
23316 The only constraint imposed by profiling is that the program must terminate
23317 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23318 properly analyzed.
23319
23320 Once the program completes execution, a data file called @file{gmon.out} is
23321 generated in the directory where the program was launched from. If this file
23322 already exists, it will be overwritten.
23323
23324 @node Running gprof
23325 @subsection Running gprof
23326
23327 @noindent
23328 The @code{gprof} tool is called as follow:
23329
23330 @smallexample
23331 gprof my_prog gmon.out
23332 @end smallexample
23333
23334 @noindent
23335 or simpler:
23336
23337 @smallexample
23338 gprof my_prog
23339 @end smallexample
23340
23341 @noindent
23342 The complete form of the gprof command line is the following:
23343
23344 @smallexample
23345 gprof [^switches^options^] [executable [data-file]]
23346 @end smallexample
23347
23348 @noindent
23349 @code{gprof} supports numerous ^switch^options^. The order of these
23350 ^switch^options^ does not matter. The full list of options can be found in
23351 the GNU Profiler User's Guide documentation that comes with this documentation.
23352
23353 The following is the subset of those switches that is most relevant:
23354
23355 @table @option
23356
23357 @item --demangle[=@var{style}]
23358 @itemx --no-demangle
23359 @cindex @option{--demangle} (@code{gprof})
23360 These options control whether symbol names should be demangled when
23361 printing output.  The default is to demangle C++ symbols.  The
23362 @code{--no-demangle} option may be used to turn off demangling. Different
23363 compilers have different mangling styles.  The optional demangling style
23364 argument can be used to choose an appropriate demangling style for your
23365 compiler, in particular Ada symbols generated by GNAT can be demangled using
23366 @code{--demangle=gnat}.
23367
23368 @item -e @var{function_name}
23369 @cindex @option{-e} (@code{gprof})
23370 The @samp{-e @var{function}} option tells @code{gprof} not to print
23371 information about the function @var{function_name} (and its
23372 children@dots{}) in the call graph.  The function will still be listed
23373 as a child of any functions that call it, but its index number will be
23374 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23375 given; only one @var{function_name} may be indicated with each @samp{-e}
23376 option.
23377
23378 @item -E @var{function_name}
23379 @cindex @option{-E} (@code{gprof})
23380 The @code{-E @var{function}} option works like the @code{-e} option, but
23381 execution time spent in the function (and children who were not called from
23382 anywhere else), will not be used to compute the percentages-of-time for
23383 the call graph.  More than one @samp{-E} option may be given; only one
23384 @var{function_name} may be indicated with each @samp{-E} option.
23385
23386 @item -f @var{function_name}
23387 @cindex @option{-f} (@code{gprof})
23388 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23389 call graph to the function @var{function_name} and its children (and
23390 their children@dots{}).  More than one @samp{-f} option may be given;
23391 only one @var{function_name} may be indicated with each @samp{-f}
23392 option.
23393
23394 @item -F @var{function_name}
23395 @cindex @option{-F} (@code{gprof})
23396 The @samp{-F @var{function}} option works like the @code{-f} option, but
23397 only time spent in the function and its children (and their
23398 children@dots{}) will be used to determine total-time and
23399 percentages-of-time for the call graph.  More than one @samp{-F} option
23400 may be given; only one @var{function_name} may be indicated with each
23401 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23402
23403 @end table
23404
23405 @node Interpretation of profiling results
23406 @subsection Interpretation of profiling results
23407
23408 @noindent
23409
23410 The results of the profiling analysis are represented by two arrays: the
23411 'flat profile' and the 'call graph'. Full documentation of those outputs
23412 can be found in the GNU Profiler User's Guide.
23413
23414 The flat profile shows the time spent in each function of the program, and how
23415 many time it has been called. This allows you to locate easily the most
23416 time-consuming functions.
23417
23418 The call graph shows, for each subprogram, the subprograms that call it,
23419 and the subprograms that it calls. It also provides an estimate of the time
23420 spent in each of those callers/called subprograms.
23421 @end ifclear
23422
23423 @c ******************************
23424 @node Running and Debugging Ada Programs
23425 @chapter Running and Debugging Ada Programs
23426 @cindex Debugging
23427
23428 @noindent
23429 This chapter discusses how to debug Ada programs.
23430 @ifset vms
23431 It applies to GNAT on the Alpha OpenVMS platform;
23432 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23433 since HP has implemented Ada support in the OpenVMS debugger on I64.
23434 @end ifset
23435
23436 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23437
23438 @enumerate
23439 @item
23440 The illegality may be a violation of the static semantics of Ada. In
23441 that case GNAT diagnoses the constructs in the program that are illegal.
23442 It is then a straightforward matter for the user to modify those parts of
23443 the program.
23444
23445 @item
23446 The illegality may be a violation of the dynamic semantics of Ada. In
23447 that case the program compiles and executes, but may generate incorrect
23448 results, or may terminate abnormally with some exception.
23449
23450 @item
23451 When presented with a program that contains convoluted errors, GNAT
23452 itself may terminate abnormally without providing full diagnostics on
23453 the incorrect user program.
23454 @end enumerate
23455
23456 @menu
23457 * The GNAT Debugger GDB::
23458 * Running GDB::
23459 * Introduction to GDB Commands::
23460 * Using Ada Expressions::
23461 * Calling User-Defined Subprograms::
23462 * Using the Next Command in a Function::
23463 * Ada Exceptions::
23464 * Ada Tasks::
23465 * Debugging Generic Units::
23466 * GNAT Abnormal Termination or Failure to Terminate::
23467 * Naming Conventions for GNAT Source Files::
23468 * Getting Internal Debugging Information::
23469 * Stack Traceback::
23470 @end menu
23471
23472 @cindex Debugger
23473 @findex gdb
23474
23475 @node The GNAT Debugger GDB
23476 @section The GNAT Debugger GDB
23477
23478 @noindent
23479 @code{GDB} is a general purpose, platform-independent debugger that
23480 can be used to debug mixed-language programs compiled with @command{gcc},
23481 and in particular is capable of debugging Ada programs compiled with
23482 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23483 complex Ada data structures.
23484
23485 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23486 @ifset vms
23487 located in the GNU:[DOCS] directory,
23488 @end ifset
23489 for full details on the usage of @code{GDB}, including a section on
23490 its usage on programs. This manual should be consulted for full
23491 details. The section that follows is a brief introduction to the
23492 philosophy and use of @code{GDB}.
23493
23494 When GNAT programs are compiled, the compiler optionally writes debugging
23495 information into the generated object file, including information on
23496 line numbers, and on declared types and variables. This information is
23497 separate from the generated code. It makes the object files considerably
23498 larger, but it does not add to the size of the actual executable that
23499 will be loaded into memory, and has no impact on run-time performance. The
23500 generation of debug information is triggered by the use of the
23501 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23502 used to carry out the compilations. It is important to emphasize that
23503 the use of these options does not change the generated code.
23504
23505 The debugging information is written in standard system formats that
23506 are used by many tools, including debuggers and profilers. The format
23507 of the information is typically designed to describe C types and
23508 semantics, but GNAT implements a translation scheme which allows full
23509 details about Ada types and variables to be encoded into these
23510 standard C formats. Details of this encoding scheme may be found in
23511 the file exp_dbug.ads in the GNAT source distribution. However, the
23512 details of this encoding are, in general, of no interest to a user,
23513 since @code{GDB} automatically performs the necessary decoding.
23514
23515 When a program is bound and linked, the debugging information is
23516 collected from the object files, and stored in the executable image of
23517 the program. Again, this process significantly increases the size of
23518 the generated executable file, but it does not increase the size of
23519 the executable program itself. Furthermore, if this program is run in
23520 the normal manner, it runs exactly as if the debug information were
23521 not present, and takes no more actual memory.
23522
23523 However, if the program is run under control of @code{GDB}, the
23524 debugger is activated.  The image of the program is loaded, at which
23525 point it is ready to run.  If a run command is given, then the program
23526 will run exactly as it would have if @code{GDB} were not present. This
23527 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23528 entirely non-intrusive until a breakpoint is encountered.  If no
23529 breakpoint is ever hit, the program will run exactly as it would if no
23530 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23531 the debugging information and can respond to user commands to inspect
23532 variables, and more generally to report on the state of execution.
23533
23534 @c **************
23535 @node Running GDB
23536 @section Running GDB
23537
23538 @noindent
23539 This section describes how to initiate the debugger.
23540 @c The above sentence is really just filler, but it was otherwise
23541 @c clumsy to get the first paragraph nonindented given the conditional
23542 @c nature of the description
23543
23544 @ifclear vms
23545 The debugger can be launched from a @code{GPS} menu or
23546 directly from the command line. The description below covers the latter use.
23547 All the commands shown can be used in the @code{GPS} debug console window,
23548 but there are usually more GUI-based ways to achieve the same effect.
23549 @end ifclear
23550
23551 The command to run @code{GDB} is
23552
23553 @smallexample
23554 $ ^gdb program^GDB PROGRAM^
23555 @end smallexample
23556
23557 @noindent
23558 where @code{^program^PROGRAM^} is the name of the executable file. This
23559 activates the debugger and results in a prompt for debugger commands.
23560 The simplest command is simply @code{run}, which causes the program to run
23561 exactly as if the debugger were not present. The following section
23562 describes some of the additional commands that can be given to @code{GDB}.
23563
23564 @c *******************************
23565 @node Introduction to GDB Commands
23566 @section Introduction to GDB Commands
23567
23568 @noindent
23569 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
23570 Debugging with GDB, gdb, Debugging with GDB},
23571 @ifset vms
23572 located in the GNU:[DOCS] directory,
23573 @end ifset
23574 for extensive documentation on the use
23575 of these commands, together with examples of their use. Furthermore,
23576 the command @command{help} invoked from within GDB activates a simple help
23577 facility which summarizes the available commands and their options.
23578 In this section we summarize a few of the most commonly
23579 used commands to give an idea of what @code{GDB} is about. You should create
23580 a simple program with debugging information and experiment with the use of
23581 these @code{GDB} commands on the program as you read through the
23582 following section.
23583
23584 @table @code
23585 @item set args @var{arguments}
23586 The @var{arguments} list above is a list of arguments to be passed to
23587 the program on a subsequent run command, just as though the arguments
23588 had been entered on a normal invocation of the program. The @code{set args}
23589 command is not needed if the program does not require arguments.
23590
23591 @item run
23592 The @code{run} command causes execution of the program to start from
23593 the beginning. If the program is already running, that is to say if
23594 you are currently positioned at a breakpoint, then a prompt will ask
23595 for confirmation that you want to abandon the current execution and
23596 restart.
23597
23598 @item breakpoint @var{location}
23599 The breakpoint command sets a breakpoint, that is to say a point at which
23600 execution will halt and @code{GDB} will await further
23601 commands. @var{location} is
23602 either a line number within a file, given in the format @code{file:linenumber},
23603 or it is the name of a subprogram. If you request that a breakpoint be set on
23604 a subprogram that is overloaded, a prompt will ask you to specify on which of
23605 those subprograms you want to breakpoint. You can also
23606 specify that all of them should be breakpointed. If the program is run
23607 and execution encounters the breakpoint, then the program
23608 stops and @code{GDB} signals that the breakpoint was encountered by
23609 printing the line of code before which the program is halted.
23610
23611 @item breakpoint exception @var{name}
23612 A special form of the breakpoint command which breakpoints whenever
23613 exception @var{name} is raised.
23614 If @var{name} is omitted,
23615 then a breakpoint will occur when any exception is raised.
23616
23617 @item print @var{expression}
23618 This will print the value of the given expression. Most simple
23619 Ada expression formats are properly handled by @code{GDB}, so the expression
23620 can contain function calls, variables, operators, and attribute references.
23621
23622 @item continue
23623 Continues execution following a breakpoint, until the next breakpoint or the
23624 termination of the program.
23625
23626 @item step
23627 Executes a single line after a breakpoint. If the next statement
23628 is a subprogram call, execution continues into (the first statement of)
23629 the called subprogram.
23630
23631 @item next
23632 Executes a single line. If this line is a subprogram call, executes and
23633 returns from the call.
23634
23635 @item list
23636 Lists a few lines around the current source location. In practice, it
23637 is usually more convenient to have a separate edit window open with the
23638 relevant source file displayed. Successive applications of this command
23639 print subsequent lines. The command can be given an argument which is a
23640 line number, in which case it displays a few lines around the specified one.
23641
23642 @item backtrace
23643 Displays a backtrace of the call chain. This command is typically
23644 used after a breakpoint has occurred, to examine the sequence of calls that
23645 leads to the current breakpoint. The display includes one line for each
23646 activation record (frame) corresponding to an active subprogram.
23647
23648 @item up
23649 At a breakpoint, @code{GDB} can display the values of variables local
23650 to the current frame. The command @code{up} can be used to
23651 examine the contents of other active frames, by moving the focus up
23652 the stack, that is to say from callee to caller, one frame at a time.
23653
23654 @item down
23655 Moves the focus of @code{GDB} down from the frame currently being
23656 examined to the frame of its callee (the reverse of the previous command),
23657
23658 @item frame @var{n}
23659 Inspect the frame with the given number. The value 0 denotes the frame
23660 of the current breakpoint, that is to say the top of the call stack.
23661
23662 @end table
23663
23664 @noindent
23665 The above list is a very short introduction to the commands that
23666 @code{GDB} provides. Important additional capabilities, including conditional
23667 breakpoints, the ability to execute command sequences on a breakpoint,
23668 the ability to debug at the machine instruction level and many other
23669 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23670 Debugging with GDB}.  Note that most commands can be abbreviated
23671 (for example, c for continue, bt for backtrace).
23672
23673 @node Using Ada Expressions
23674 @section Using Ada Expressions
23675 @cindex Ada expressions
23676
23677 @noindent
23678 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23679 extensions. The philosophy behind the design of this subset is
23680
23681 @itemize @bullet
23682 @item
23683 That @code{GDB} should provide basic literals and access to operations for
23684 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23685 leaving more sophisticated computations to subprograms written into the
23686 program (which therefore may be called from @code{GDB}).
23687
23688 @item
23689 That type safety and strict adherence to Ada language restrictions
23690 are not particularly important to the @code{GDB} user.
23691
23692 @item
23693 That brevity is important to the @code{GDB} user.
23694 @end itemize
23695
23696 @noindent
23697 Thus, for brevity, the debugger acts as if there were
23698 implicit @code{with} and @code{use} clauses in effect for all user-written
23699 packages, thus making it unnecessary to fully qualify most names with
23700 their packages, regardless of context. Where this causes ambiguity,
23701 @code{GDB} asks the user's intent.
23702
23703 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23704 GDB, gdb, Debugging with GDB}.
23705
23706 @node Calling User-Defined Subprograms
23707 @section Calling User-Defined Subprograms
23708
23709 @noindent
23710 An important capability of @code{GDB} is the ability to call user-defined
23711 subprograms while debugging. This is achieved simply by entering
23712 a subprogram call statement in the form:
23713
23714 @smallexample
23715 call subprogram-name (parameters)
23716 @end smallexample
23717
23718 @noindent
23719 The keyword @code{call} can be omitted in the normal case where the
23720 @code{subprogram-name} does not coincide with any of the predefined
23721 @code{GDB} commands.
23722
23723 The effect is to invoke the given subprogram, passing it the
23724 list of parameters that is supplied. The parameters can be expressions and
23725 can include variables from the program being debugged. The
23726 subprogram must be defined
23727 at the library level within your program, and @code{GDB} will call the
23728 subprogram within the environment of your program execution (which
23729 means that the subprogram is free to access or even modify variables
23730 within your program).
23731
23732 The most important use of this facility is in allowing the inclusion of
23733 debugging routines that are tailored to particular data structures
23734 in your program. Such debugging routines can be written to provide a suitably
23735 high-level description of an abstract type, rather than a low-level dump
23736 of its physical layout. After all, the standard
23737 @code{GDB print} command only knows the physical layout of your
23738 types, not their abstract meaning. Debugging routines can provide information
23739 at the desired semantic level and are thus enormously useful.
23740
23741 For example, when debugging GNAT itself, it is crucial to have access to
23742 the contents of the tree nodes used to represent the program internally.
23743 But tree nodes are represented simply by an integer value (which in turn
23744 is an index into a table of nodes).
23745 Using the @code{print} command on a tree node would simply print this integer
23746 value, which is not very useful. But the PN routine (defined in file
23747 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23748 a useful high level representation of the tree node, which includes the
23749 syntactic category of the node, its position in the source, the integers
23750 that denote descendant nodes and parent node, as well as varied
23751 semantic information. To study this example in more detail, you might want to
23752 look at the body of the PN procedure in the stated file.
23753
23754 @node Using the Next Command in a Function
23755 @section Using the Next Command in a Function
23756
23757 @noindent
23758 When you use the @code{next} command in a function, the current source
23759 location will advance to the next statement as usual. A special case
23760 arises in the case of a @code{return} statement.
23761
23762 Part of the code for a return statement is the ``epilog'' of the function.
23763 This is the code that returns to the caller. There is only one copy of
23764 this epilog code, and it is typically associated with the last return
23765 statement in the function if there is more than one return. In some
23766 implementations, this epilog is associated with the first statement
23767 of the function.
23768
23769 The result is that if you use the @code{next} command from a return
23770 statement that is not the last return statement of the function you
23771 may see a strange apparent jump to the last return statement or to
23772 the start of the function. You should simply ignore this odd jump.
23773 The value returned is always that from the first return statement
23774 that was stepped through.
23775
23776 @node Ada Exceptions
23777 @section Breaking on Ada Exceptions
23778 @cindex Exceptions
23779
23780 @noindent
23781 You can set breakpoints that trip when your program raises
23782 selected exceptions.
23783
23784 @table @code
23785 @item break exception
23786 Set a breakpoint that trips whenever (any task in the) program raises
23787 any exception.
23788
23789 @item break exception @var{name}
23790 Set a breakpoint that trips whenever (any task in the) program raises
23791 the exception @var{name}.
23792
23793 @item break exception unhandled
23794 Set a breakpoint that trips whenever (any task in the) program raises an
23795 exception for which there is no handler.
23796
23797 @item info exceptions
23798 @itemx info exceptions @var{regexp}
23799 The @code{info exceptions} command permits the user to examine all defined
23800 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23801 argument, prints out only those exceptions whose name matches @var{regexp}.
23802 @end table
23803
23804 @node Ada Tasks
23805 @section Ada Tasks
23806 @cindex Tasks
23807
23808 @noindent
23809 @code{GDB} allows the following task-related commands:
23810
23811 @table @code
23812 @item info tasks
23813 This command shows a list of current Ada tasks, as in the following example:
23814
23815 @smallexample
23816 @iftex
23817 @leftskip=0cm
23818 @end iftex
23819 (gdb) info tasks
23820   ID       TID P-ID   Thread Pri State                 Name
23821    1   8088000   0   807e000  15 Child Activation Wait main_task
23822    2   80a4000   1   80ae000  15 Accept/Select Wait    b
23823    3   809a800   1   80a4800  15 Child Activation Wait a
23824 *  4   80ae800   3   80b8000  15 Running               c
23825 @end smallexample
23826
23827 @noindent
23828 In this listing, the asterisk before the first task indicates it to be the
23829 currently running task. The first column lists the task ID that is used
23830 to refer to tasks in the following commands.
23831
23832 @item break @var{linespec} task @var{taskid}
23833 @itemx break @var{linespec} task @var{taskid} if @dots{}
23834 @cindex Breakpoints and tasks
23835 These commands are like the @code{break @dots{} thread @dots{}}.
23836 @var{linespec} specifies source lines.
23837
23838 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23839 to specify that you only want @code{GDB} to stop the program when a
23840 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23841 numeric task identifiers assigned by @code{GDB}, shown in the first
23842 column of the @samp{info tasks} display.
23843
23844 If you do not specify @samp{task @var{taskid}} when you set a
23845 breakpoint, the breakpoint applies to @emph{all} tasks of your
23846 program.
23847
23848 You can use the @code{task} qualifier on conditional breakpoints as
23849 well; in this case, place @samp{task @var{taskid}} before the
23850 breakpoint condition (before the @code{if}).
23851
23852 @item task @var{taskno}
23853 @cindex Task switching
23854
23855 This command allows to switch to the task referred by @var{taskno}. In
23856 particular, This allows to browse the backtrace of the specified
23857 task. It is advised to switch back to the original task before
23858 continuing execution otherwise the scheduling of the program may be
23859 perturbed.
23860 @end table
23861
23862 @noindent
23863 For more detailed information on the tasking support,
23864 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23865
23866 @node Debugging Generic Units
23867 @section Debugging Generic Units
23868 @cindex Debugging Generic Units
23869 @cindex Generics
23870
23871 @noindent
23872 GNAT always uses code expansion for generic instantiation. This means that
23873 each time an instantiation occurs, a complete copy of the original code is
23874 made, with appropriate substitutions of formals by actuals.
23875
23876 It is not possible to refer to the original generic entities in
23877 @code{GDB}, but it is always possible to debug a particular instance of
23878 a generic, by using the appropriate expanded names. For example, if we have
23879
23880 @smallexample @c ada
23881 @group
23882 @cartouche
23883 procedure g is
23884
23885    generic package k is
23886       procedure kp (v1 : in out integer);
23887    end k;
23888
23889    package body k is
23890       procedure kp (v1 : in out integer) is
23891       begin
23892          v1 := v1 + 1;
23893       end kp;
23894    end k;
23895
23896    package k1 is new k;
23897    package k2 is new k;
23898
23899    var : integer := 1;
23900
23901 begin
23902    k1.kp (var);
23903    k2.kp (var);
23904    k1.kp (var);
23905    k2.kp (var);
23906 end;
23907 @end cartouche
23908 @end group
23909 @end smallexample
23910
23911 @noindent
23912 Then to break on a call to procedure kp in the k2 instance, simply
23913 use the command:
23914
23915 @smallexample
23916 (gdb) break g.k2.kp
23917 @end smallexample
23918
23919 @noindent
23920 When the breakpoint occurs, you can step through the code of the
23921 instance in the normal manner and examine the values of local variables, as for
23922 other units.
23923
23924 @node GNAT Abnormal Termination or Failure to Terminate
23925 @section GNAT Abnormal Termination or Failure to Terminate
23926 @cindex GNAT Abnormal Termination or Failure to Terminate
23927
23928 @noindent
23929 When presented with programs that contain serious errors in syntax
23930 or semantics,
23931 GNAT may on rare occasions  experience problems in operation, such
23932 as aborting with a
23933 segmentation fault or illegal memory access, raising an internal
23934 exception, terminating abnormally, or failing to terminate at all.
23935 In such cases, you can activate
23936 various features of GNAT that can help you pinpoint the construct in your
23937 program that is the likely source of the problem.
23938
23939 The following strategies are presented in increasing order of
23940 difficulty, corresponding to your experience in using GNAT and your
23941 familiarity with compiler internals.
23942
23943 @enumerate
23944 @item
23945 Run @command{gcc} with the @option{-gnatf}. This first
23946 switch causes all errors on a given line to be reported. In its absence,
23947 only the first error on a line is displayed.
23948
23949 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23950 are encountered, rather than after compilation is terminated. If GNAT
23951 terminates prematurely or goes into an infinite loop, the last error
23952 message displayed may help to pinpoint the culprit.
23953
23954 @item
23955 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23956 mode, @command{gcc} produces ongoing information about the progress of the
23957 compilation and provides the name of each procedure as code is
23958 generated. This switch allows you to find which Ada procedure was being
23959 compiled when it encountered a code generation problem.
23960
23961 @item
23962 @cindex @option{-gnatdc} switch
23963 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23964 switch that does for the front-end what @option{^-v^VERBOSE^} does
23965 for the back end. The system prints the name of each unit,
23966 either a compilation unit or nested unit, as it is being analyzed.
23967 @item
23968 Finally, you can start
23969 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23970 front-end of GNAT, and can be run independently (normally it is just
23971 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23972 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23973 @code{where} command is the first line of attack; the variable
23974 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23975 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23976 which the execution stopped, and @code{input_file name} indicates the name of
23977 the source file.
23978 @end enumerate
23979
23980 @node Naming Conventions for GNAT Source Files
23981 @section Naming Conventions for GNAT Source Files
23982
23983 @noindent
23984 In order to examine the workings of the GNAT system, the following
23985 brief description of its organization may be helpful:
23986
23987 @itemize @bullet
23988 @item
23989 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23990
23991 @item
23992 All files prefixed with @file{^par^PAR^} are components of the parser. The
23993 numbers correspond to chapters of the Ada Reference Manual. For example,
23994 parsing of select statements can be found in @file{par-ch9.adb}.
23995
23996 @item
23997 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23998 numbers correspond to chapters of the Ada standard. For example, all
23999 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24000 addition, some features of the language require sufficient special processing
24001 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24002 dynamic dispatching, etc.
24003
24004 @item
24005 All files prefixed with @file{^exp^EXP^} perform normalization and
24006 expansion of the intermediate representation (abstract syntax tree, or AST).
24007 these files use the same numbering scheme as the parser and semantics files.
24008 For example, the construction of record initialization procedures is done in
24009 @file{exp_ch3.adb}.
24010
24011 @item
24012 The files prefixed with @file{^bind^BIND^} implement the binder, which
24013 verifies the consistency of the compilation, determines an order of
24014 elaboration, and generates the bind file.
24015
24016 @item
24017 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24018 data structures used by the front-end.
24019
24020 @item
24021 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24022 the abstract syntax tree as produced by the parser.
24023
24024 @item
24025 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24026 all entities, computed during semantic analysis.
24027
24028 @item
24029 Library management issues are dealt with in files with prefix
24030 @file{^lib^LIB^}.
24031
24032 @item
24033 @findex Ada
24034 @cindex Annex A
24035 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24036 defined in Annex A.
24037
24038 @item
24039 @findex Interfaces
24040 @cindex Annex B
24041 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24042 defined in Annex B.
24043
24044 @item
24045 @findex System
24046 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24047 both language-defined children and GNAT run-time routines.
24048
24049 @item
24050 @findex GNAT
24051 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24052 general-purpose packages, fully documented in their specs. All
24053 the other @file{.c} files are modifications of common @command{gcc} files.
24054 @end itemize
24055
24056 @node Getting Internal Debugging Information
24057 @section Getting Internal Debugging Information
24058
24059 @noindent
24060 Most compilers have internal debugging switches and modes. GNAT
24061 does also, except GNAT internal debugging switches and modes are not
24062 secret. A summary and full description of all the compiler and binder
24063 debug flags are in the file @file{debug.adb}. You must obtain the
24064 sources of the compiler to see the full detailed effects of these flags.
24065
24066 The switches that print the source of the program (reconstructed from
24067 the internal tree) are of general interest for user programs, as are the
24068 options to print
24069 the full internal tree, and the entity table (the symbol table
24070 information). The reconstructed source provides a readable version of the
24071 program after the front-end has completed analysis and  expansion,
24072 and is useful when studying the performance of specific constructs.
24073 For example, constraint checks are indicated, complex aggregates
24074 are replaced with loops and assignments, and tasking primitives
24075 are replaced with run-time calls.
24076
24077 @node Stack Traceback
24078 @section Stack Traceback
24079 @cindex traceback
24080 @cindex stack traceback
24081 @cindex stack unwinding
24082
24083 @noindent
24084 Traceback is a mechanism to display the sequence of subprogram calls that
24085 leads to a specified execution point in a program. Often (but not always)
24086 the execution point is an instruction at which an exception has been raised.
24087 This mechanism is also known as @i{stack unwinding} because it obtains
24088 its information by scanning the run-time stack and recovering the activation
24089 records of all active subprograms. Stack unwinding is one of the most
24090 important tools for program debugging.
24091
24092 The first entry stored in traceback corresponds to the deepest calling level,
24093 that is to say the subprogram currently executing the instruction
24094 from which we want to obtain the traceback.
24095
24096 Note that there is no runtime performance penalty when stack traceback
24097 is enabled, and no exception is raised during program execution.
24098
24099 @menu
24100 * Non-Symbolic Traceback::
24101 * Symbolic Traceback::
24102 @end menu
24103
24104 @node Non-Symbolic Traceback
24105 @subsection Non-Symbolic Traceback
24106 @cindex traceback, non-symbolic
24107
24108 @noindent
24109 Note: this feature is not supported on all platforms. See
24110 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24111 platforms.
24112
24113 @menu
24114 * Tracebacks From an Unhandled Exception::
24115 * Tracebacks From Exception Occurrences (non-symbolic)::
24116 * Tracebacks From Anywhere in a Program (non-symbolic)::
24117 @end menu
24118
24119 @node Tracebacks From an Unhandled Exception
24120 @subsubsection Tracebacks From an Unhandled Exception
24121
24122 @noindent
24123 A runtime non-symbolic traceback is a list of addresses of call instructions.
24124 To enable this feature you must use the @option{-E}
24125 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24126 of exception information. You can retrieve this information using the
24127 @code{addr2line} tool.
24128
24129 Here is a simple example:
24130
24131 @smallexample @c ada
24132 @cartouche
24133 procedure STB is
24134
24135    procedure P1 is
24136    begin
24137       raise Constraint_Error;
24138    end P1;
24139
24140    procedure P2 is
24141    begin
24142       P1;
24143    end P2;
24144
24145 begin
24146    P2;
24147 end STB;
24148 @end cartouche
24149 @end smallexample
24150
24151 @smallexample
24152 $ gnatmake stb -bargs -E
24153 $ stb
24154
24155 Execution terminated by unhandled exception
24156 Exception name: CONSTRAINT_ERROR
24157 Message: stb.adb:5
24158 Call stack traceback locations:
24159 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24160 @end smallexample
24161
24162 @noindent
24163 As we see the traceback lists a sequence of addresses for the unhandled
24164 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24165 guess that this exception come from procedure P1. To translate these
24166 addresses into the source lines where the calls appear, the
24167 @code{addr2line} tool, described below, is invaluable. The use of this tool
24168 requires the program to be compiled with debug information.
24169
24170 @smallexample
24171 $ gnatmake -g stb -bargs -E
24172 $ stb
24173
24174 Execution terminated by unhandled exception
24175 Exception name: CONSTRAINT_ERROR
24176 Message: stb.adb:5
24177 Call stack traceback locations:
24178 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24179
24180 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24181    0x4011f1 0x77e892a4
24182
24183 00401373 at d:/stb/stb.adb:5
24184 0040138B at d:/stb/stb.adb:10
24185 0040139C at d:/stb/stb.adb:14
24186 00401335 at d:/stb/b~stb.adb:104
24187 004011C4 at /build/@dots{}/crt1.c:200
24188 004011F1 at /build/@dots{}/crt1.c:222
24189 77E892A4 in ?? at ??:0
24190 @end smallexample
24191
24192 @noindent
24193 The @code{addr2line} tool has several other useful options:
24194
24195 @table @code
24196 @item --functions
24197 to get the function name corresponding to any location
24198
24199 @item --demangle=gnat
24200 to use the gnat decoding mode for the function names. Note that
24201 for binutils version 2.9.x the option is simply @option{--demangle}.
24202 @end table
24203
24204 @smallexample
24205 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24206    0x40139c 0x401335 0x4011c4 0x4011f1
24207
24208 00401373 in stb.p1 at d:/stb/stb.adb:5
24209 0040138B in stb.p2 at d:/stb/stb.adb:10
24210 0040139C in stb at d:/stb/stb.adb:14
24211 00401335 in main at d:/stb/b~stb.adb:104
24212 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24213 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24214 @end smallexample
24215
24216 @noindent
24217 From this traceback we can see that the exception was raised in
24218 @file{stb.adb} at line 5, which was reached from a procedure call in
24219 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24220 which contains the call to the main program.
24221 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24222 and the output will vary from platform to platform.
24223
24224 It is also possible to use @code{GDB} with these traceback addresses to debug
24225 the program. For example, we can break at a given code location, as reported
24226 in the stack traceback:
24227
24228 @smallexample
24229 $ gdb -nw stb
24230 @ifclear vms
24231 @noindent
24232 Furthermore, this feature is not implemented inside Windows DLL. Only
24233 the non-symbolic traceback is reported in this case.
24234 @end ifclear
24235
24236 (gdb) break *0x401373
24237 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24238 @end smallexample
24239
24240 @noindent
24241 It is important to note that the stack traceback addresses
24242 do not change when debug information is included. This is particularly useful
24243 because it makes it possible to release software without debug information (to
24244 minimize object size), get a field report that includes a stack traceback
24245 whenever an internal bug occurs, and then be able to retrieve the sequence
24246 of calls with the same program compiled with debug information.
24247
24248 @node Tracebacks From Exception Occurrences (non-symbolic)
24249 @subsubsection Tracebacks From Exception Occurrences
24250
24251 @noindent
24252 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24253 The stack traceback is attached to the exception information string, and can
24254 be retrieved in an exception handler within the Ada program, by means of the
24255 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24256
24257 @smallexample @c ada
24258 with Ada.Text_IO;
24259 with Ada.Exceptions;
24260
24261 procedure STB is
24262
24263    use Ada;
24264    use Ada.Exceptions;
24265
24266    procedure P1 is
24267       K : Positive := 1;
24268    begin
24269       K := K - 1;
24270    exception
24271       when E : others =>
24272          Text_IO.Put_Line (Exception_Information (E));
24273    end P1;
24274
24275    procedure P2 is
24276    begin
24277       P1;
24278    end P2;
24279
24280 begin
24281    P2;
24282 end STB;
24283 @end smallexample
24284
24285 @noindent
24286 This program will output:
24287
24288 @smallexample
24289 $ stb
24290
24291 Exception name: CONSTRAINT_ERROR
24292 Message: stb.adb:12
24293 Call stack traceback locations:
24294 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24295 @end smallexample
24296
24297 @node Tracebacks From Anywhere in a Program (non-symbolic)
24298 @subsubsection Tracebacks From Anywhere in a Program
24299
24300 @noindent
24301 It is also possible to retrieve a stack traceback from anywhere in a
24302 program. For this you need to
24303 use the @code{GNAT.Traceback} API. This package includes a procedure called
24304 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24305 display procedures described below. It is not necessary to use the
24306 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24307 is invoked explicitly.
24308
24309 @noindent
24310 In the following example we compute a traceback at a specific location in
24311 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24312 convert addresses to strings:
24313
24314 @smallexample @c ada
24315 with Ada.Text_IO;
24316 with GNAT.Traceback;
24317 with GNAT.Debug_Utilities;
24318
24319 procedure STB is
24320
24321    use Ada;
24322    use GNAT;
24323    use GNAT.Traceback;
24324
24325    procedure P1 is
24326       TB  : Tracebacks_Array (1 .. 10);
24327       --  We are asking for a maximum of 10 stack frames.
24328       Len : Natural;
24329       --  Len will receive the actual number of stack frames returned.
24330    begin
24331       Call_Chain (TB, Len);
24332
24333       Text_IO.Put ("In STB.P1 : ");
24334
24335       for K in 1 .. Len loop
24336          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24337          Text_IO.Put (' ');
24338       end loop;
24339
24340       Text_IO.New_Line;
24341    end P1;
24342
24343    procedure P2 is
24344    begin
24345       P1;
24346    end P2;
24347
24348 begin
24349    P2;
24350 end STB;
24351 @end smallexample
24352
24353 @smallexample
24354 $ gnatmake -g stb
24355 $ stb
24356
24357 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24358 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24359 @end smallexample
24360
24361 @noindent
24362 You can then get further information by invoking the @code{addr2line}
24363 tool as described earlier (note that the hexadecimal addresses
24364 need to be specified in C format, with a leading ``0x'').
24365
24366 @node Symbolic Traceback
24367 @subsection Symbolic Traceback
24368 @cindex traceback, symbolic
24369
24370 @noindent
24371 A symbolic traceback is a stack traceback in which procedure names are
24372 associated with each code location.
24373
24374 @noindent
24375 Note that this feature is not supported on all platforms. See
24376 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24377 list of currently supported platforms.
24378
24379 @noindent
24380 Note that the symbolic traceback requires that the program be compiled
24381 with debug information. If it is not compiled with debug information
24382 only the non-symbolic information will be valid.
24383
24384 @menu
24385 * Tracebacks From Exception Occurrences (symbolic)::
24386 * Tracebacks From Anywhere in a Program (symbolic)::
24387 @end menu
24388
24389 @node Tracebacks From Exception Occurrences (symbolic)
24390 @subsubsection Tracebacks From Exception Occurrences
24391
24392 @smallexample @c ada
24393 with Ada.Text_IO;
24394 with GNAT.Traceback.Symbolic;
24395
24396 procedure STB is
24397
24398    procedure P1 is
24399    begin
24400       raise Constraint_Error;
24401    end P1;
24402
24403    procedure P2 is
24404    begin
24405       P1;
24406    end P2;
24407
24408    procedure P3 is
24409    begin
24410       P2;
24411    end P3;
24412
24413 begin
24414    P3;
24415 exception
24416    when E : others =>
24417       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24418 end STB;
24419 @end smallexample
24420
24421 @smallexample
24422 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24423 $ stb
24424
24425 0040149F in stb.p1 at stb.adb:8
24426 004014B7 in stb.p2 at stb.adb:13
24427 004014CF in stb.p3 at stb.adb:18
24428 004015DD in ada.stb at stb.adb:22
24429 00401461 in main at b~stb.adb:168
24430 004011C4 in __mingw_CRTStartup at crt1.c:200
24431 004011F1 in mainCRTStartup at crt1.c:222
24432 77E892A4 in ?? at ??:0
24433 @end smallexample
24434
24435 @noindent
24436 In the above example the ``.\'' syntax in the @command{gnatmake} command
24437 is currently required by @command{addr2line} for files that are in
24438 the current working directory.
24439 Moreover, the exact sequence of linker options may vary from platform
24440 to platform.
24441 The above @option{-largs} section is for Windows platforms. By contrast,
24442 under Unix there is no need for the @option{-largs} section.
24443 Differences across platforms are due to details of linker implementation.
24444
24445 @node Tracebacks From Anywhere in a Program (symbolic)
24446 @subsubsection Tracebacks From Anywhere in a Program
24447
24448 @noindent
24449 It is possible to get a symbolic stack traceback
24450 from anywhere in a program, just as for non-symbolic tracebacks.
24451 The first step is to obtain a non-symbolic
24452 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24453 information. Here is an example:
24454
24455 @smallexample @c ada
24456 with Ada.Text_IO;
24457 with GNAT.Traceback;
24458 with GNAT.Traceback.Symbolic;
24459
24460 procedure STB is
24461
24462    use Ada;
24463    use GNAT.Traceback;
24464    use GNAT.Traceback.Symbolic;
24465
24466    procedure P1 is
24467       TB  : Tracebacks_Array (1 .. 10);
24468       --  We are asking for a maximum of 10 stack frames.
24469       Len : Natural;
24470       --  Len will receive the actual number of stack frames returned.
24471    begin
24472       Call_Chain (TB, Len);
24473       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24474    end P1;
24475
24476    procedure P2 is
24477    begin
24478       P1;
24479    end P2;
24480
24481 begin
24482    P2;
24483 end STB;
24484 @end smallexample
24485
24486 @c ******************************
24487 @ifset vms
24488 @node Compatibility with HP Ada
24489 @chapter Compatibility with HP Ada
24490 @cindex Compatibility
24491
24492 @noindent
24493 @cindex DEC Ada
24494 @cindex HP Ada
24495 @cindex Compatibility between GNAT and HP Ada
24496 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24497 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24498 GNAT is highly compatible
24499 with HP Ada, and it should generally be straightforward to port code
24500 from the HP Ada environment to GNAT. However, there are a few language
24501 and implementation differences of which the user must be aware. These
24502 differences are discussed in this chapter. In
24503 addition, the operating environment and command structure for the
24504 compiler are different, and these differences are also discussed.
24505
24506 For further details on these and other compatibility issues,
24507 see Appendix E of the HP publication
24508 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24509
24510 Except where otherwise indicated, the description of GNAT for OpenVMS
24511 applies to both the Alpha and I64 platforms.
24512
24513 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24514 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24515
24516 The discussion in this chapter addresses specifically the implementation
24517 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24518 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24519 GNAT always follows the Alpha implementation.
24520
24521 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24522 attributes are recognized, although only a subset of them can sensibly
24523 be implemented.  The description of pragmas in
24524 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24525 indicates whether or not they are applicable to non-VMS systems.
24526
24527 @menu
24528 * Ada Language Compatibility::
24529 * Differences in the Definition of Package System::
24530 * Language-Related Features::
24531 * The Package STANDARD::
24532 * The Package SYSTEM::
24533 * Tasking and Task-Related Features::
24534 * Pragmas and Pragma-Related Features::
24535 * Library of Predefined Units::
24536 * Bindings::
24537 * Main Program Definition::
24538 * Implementation-Defined Attributes::
24539 * Compiler and Run-Time Interfacing::
24540 * Program Compilation and Library Management::
24541 * Input-Output::
24542 * Implementation Limits::
24543 * Tools and Utilities::
24544 @end menu
24545
24546 @node Ada Language Compatibility
24547 @section Ada Language Compatibility
24548
24549 @noindent
24550 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24551 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24552 with Ada 83, and therefore Ada 83 programs will compile
24553 and run under GNAT with
24554 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24555 provides details on specific incompatibilities.
24556
24557 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24558 as well as the pragma @code{ADA_83}, to force the compiler to
24559 operate in Ada 83 mode. This mode does not guarantee complete
24560 conformance to Ada 83, but in practice is sufficient to
24561 eliminate most sources of incompatibilities.
24562 In particular, it eliminates the recognition of the
24563 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24564 in Ada 83 programs is legal, and handles the cases of packages
24565 with optional bodies, and generics that instantiate unconstrained
24566 types without the use of @code{(<>)}.
24567
24568 @node Differences in the Definition of Package System
24569 @section Differences in the Definition of Package @code{System}
24570
24571 @noindent
24572 An Ada compiler is allowed to add
24573 implementation-dependent declarations to package @code{System}.
24574 In normal mode,
24575 GNAT does not take advantage of this permission, and the version of
24576 @code{System} provided by GNAT exactly matches that defined in the Ada
24577 Reference Manual.
24578
24579 However, HP Ada adds an extensive set of declarations to package
24580 @code{System},
24581 as fully documented in the HP Ada manuals. To minimize changes required
24582 for programs that make use of these extensions, GNAT provides the pragma
24583 @code{Extend_System} for extending the definition of package System. By using:
24584 @cindex pragma @code{Extend_System}
24585 @cindex @code{Extend_System} pragma
24586
24587 @smallexample @c ada
24588 @group
24589 @cartouche
24590 pragma Extend_System (Aux_DEC);
24591 @end cartouche
24592 @end group
24593 @end smallexample
24594
24595 @noindent
24596 the set of definitions in @code{System} is extended to include those in
24597 package @code{System.Aux_DEC}.
24598 @cindex @code{System.Aux_DEC} package
24599 @cindex @code{Aux_DEC} package (child of @code{System})
24600 These definitions are incorporated directly into package @code{System},
24601 as though they had been declared there. For a
24602 list of the declarations added, see the spec of this package,
24603 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24604 @cindex @file{s-auxdec.ads} file
24605 The pragma @code{Extend_System} is a configuration pragma, which means that
24606 it can be placed in the file @file{gnat.adc}, so that it will automatically
24607 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24608 for further details.
24609
24610 An alternative approach that avoids the use of the non-standard
24611 @code{Extend_System} pragma is to add a context clause to the unit that
24612 references these facilities:
24613
24614 @smallexample @c ada
24615 @cartouche
24616 with System.Aux_DEC;
24617 use  System.Aux_DEC;
24618 @end cartouche
24619 @end smallexample
24620
24621 @noindent
24622 The effect is not quite semantically identical to incorporating
24623 the declarations directly into package @code{System},
24624 but most programs will not notice a difference
24625 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24626 to reference the entities directly in package @code{System}.
24627 For units containing such references,
24628 the prefixes must either be removed, or the pragma @code{Extend_System}
24629 must be used.
24630
24631 @node Language-Related Features
24632 @section Language-Related Features
24633
24634 @noindent
24635 The following sections highlight differences in types,
24636 representations of types, operations, alignment, and
24637 related topics.
24638
24639 @menu
24640 * Integer Types and Representations::
24641 * Floating-Point Types and Representations::
24642 * Pragmas Float_Representation and Long_Float::
24643 * Fixed-Point Types and Representations::
24644 * Record and Array Component Alignment::
24645 * Address Clauses::
24646 * Other Representation Clauses::
24647 @end menu
24648
24649 @node Integer Types and Representations
24650 @subsection Integer Types and Representations
24651
24652 @noindent
24653 The set of predefined integer types is identical in HP Ada and GNAT.
24654 Furthermore the representation of these integer types is also identical,
24655 including the capability of size clauses forcing biased representation.
24656
24657 In addition,
24658 HP Ada for OpenVMS Alpha systems has defined the
24659 following additional integer types in package @code{System}:
24660
24661 @itemize @bullet
24662
24663 @item
24664 @code{INTEGER_8}
24665
24666 @item
24667 @code{INTEGER_16}
24668
24669 @item
24670 @code{INTEGER_32}
24671
24672 @item
24673 @code{INTEGER_64}
24674
24675 @item
24676 @code{LARGEST_INTEGER}
24677 @end itemize
24678
24679 @noindent
24680 In GNAT, the first four of these types may be obtained from the
24681 standard Ada package @code{Interfaces}.
24682 Alternatively, by use of the pragma @code{Extend_System}, identical
24683 declarations can be referenced directly in package @code{System}.
24684 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24685
24686 @node Floating-Point Types and Representations
24687 @subsection Floating-Point Types and Representations
24688 @cindex Floating-Point types
24689
24690 @noindent
24691 The set of predefined floating-point types is identical in HP Ada and GNAT.
24692 Furthermore the representation of these floating-point
24693 types is also identical. One important difference is that the default
24694 representation for HP Ada is @code{VAX_Float}, but the default representation
24695 for GNAT is IEEE.
24696
24697 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24698 pragma @code{Float_Representation} as described in the HP Ada
24699 documentation.
24700 For example, the declarations:
24701
24702 @smallexample @c ada
24703 @cartouche
24704 type F_Float is digits 6;
24705 pragma Float_Representation (VAX_Float, F_Float);
24706 @end cartouche
24707 @end smallexample
24708
24709 @noindent
24710 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24711 format.
24712 This set of declarations actually appears in @code{System.Aux_DEC},
24713 which contains
24714 the full set of additional floating-point declarations provided in
24715 the HP Ada version of package @code{System}.
24716 This and similar declarations may be accessed in a user program
24717 by using pragma @code{Extend_System}. The use of this
24718 pragma, and the related pragma @code{Long_Float} is described in further
24719 detail in the following section.
24720
24721 @node Pragmas Float_Representation and Long_Float
24722 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24723
24724 @noindent
24725 HP Ada provides the pragma @code{Float_Representation}, which
24726 acts as a program library switch to allow control over
24727 the internal representation chosen for the predefined
24728 floating-point types declared in the package @code{Standard}.
24729 The format of this pragma is as follows:
24730
24731 @smallexample @c ada
24732 @cartouche
24733 pragma Float_Representation(VAX_Float | IEEE_Float);
24734 @end cartouche
24735 @end smallexample
24736
24737 @noindent
24738 This pragma controls the representation of floating-point
24739 types as follows:
24740
24741 @itemize @bullet
24742 @item
24743 @code{VAX_Float} specifies that floating-point
24744 types are represented by default with the VAX system hardware types
24745 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24746 Note that the @code{H-floating}
24747 type was available only on VAX systems, and is not available
24748 in either HP Ada or GNAT.
24749
24750 @item
24751 @code{IEEE_Float} specifies that floating-point
24752 types are represented by default with the IEEE single and
24753 double floating-point types.
24754 @end itemize
24755
24756 @noindent
24757 GNAT provides an identical implementation of the pragma
24758 @code{Float_Representation}, except that it functions as a
24759 configuration pragma. Note that the
24760 notion of configuration pragma corresponds closely to the
24761 HP Ada notion of a program library switch.
24762
24763 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24764 which is different
24765 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24766 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24767 advisable to change the format of numbers passed to standard library
24768 routines, and if necessary explicit type conversions may be needed.
24769
24770 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24771 efficient, and (given that it conforms to an international standard)
24772 potentially more portable.
24773 The situation in which @code{VAX_Float} may be useful is in interfacing
24774 to existing code and data that expect the use of @code{VAX_Float}.
24775 In such a situation use the predefined @code{VAX_Float}
24776 types in package @code{System}, as extended by
24777 @code{Extend_System}. For example, use @code{System.F_Float}
24778 to specify the 32-bit @code{F-Float} format.
24779
24780 @noindent
24781 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24782 to allow control over the internal representation chosen
24783 for the predefined type @code{Long_Float} and for floating-point
24784 type declarations with digits specified in the range 7 .. 15.
24785 The format of this pragma is as follows:
24786
24787 @smallexample @c ada
24788 @cartouche
24789 pragma Long_Float (D_FLOAT | G_FLOAT);
24790 @end cartouche
24791 @end smallexample
24792
24793 @node Fixed-Point Types and Representations
24794 @subsection Fixed-Point Types and Representations
24795
24796 @noindent
24797 On HP Ada for OpenVMS Alpha systems, rounding is
24798 away from zero for both positive and negative numbers.
24799 Therefore, @code{+0.5} rounds to @code{1},
24800 and @code{-0.5} rounds to @code{-1}.
24801
24802 On GNAT the results of operations
24803 on fixed-point types are in accordance with the Ada
24804 rules. In particular, results of operations on decimal
24805 fixed-point types are truncated.
24806
24807 @node Record and Array Component Alignment
24808 @subsection Record and Array Component Alignment
24809
24810 @noindent
24811 On HP Ada for OpenVMS Alpha, all non-composite components
24812 are aligned on natural boundaries. For example, 1-byte
24813 components are aligned on byte boundaries, 2-byte
24814 components on 2-byte boundaries, 4-byte components on 4-byte
24815 byte boundaries, and so on. The OpenVMS Alpha hardware
24816 runs more efficiently with naturally aligned data.
24817
24818 On GNAT, alignment rules are compatible
24819 with HP Ada for OpenVMS Alpha.
24820
24821 @node Address Clauses
24822 @subsection Address Clauses
24823
24824 @noindent
24825 In HP Ada and GNAT, address clauses are supported for
24826 objects and imported subprograms.
24827 The predefined type @code{System.Address} is a private type
24828 in both compilers on Alpha OpenVMS, with the same representation
24829 (it is simply a machine pointer). Addition, subtraction, and comparison
24830 operations are available in the standard Ada package
24831 @code{System.Storage_Elements}, or in package @code{System}
24832 if it is extended to include @code{System.Aux_DEC} using a
24833 pragma @code{Extend_System} as previously described.
24834
24835 Note that code that @code{with}'s both this extended package @code{System}
24836 and the package @code{System.Storage_Elements} should not @code{use}
24837 both packages, or ambiguities will result. In general it is better
24838 not to mix these two sets of facilities. The Ada package was
24839 designed specifically to provide the kind of features that HP Ada
24840 adds directly to package @code{System}.
24841
24842 The type @code{System.Address} is a 64-bit integer type in GNAT for
24843 I64 OpenVMS.  For more information,
24844 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24845
24846 GNAT is compatible with HP Ada in its handling of address
24847 clauses, except for some limitations in
24848 the form of address clauses for composite objects with
24849 initialization. Such address clauses are easily replaced
24850 by the use of an explicitly-defined constant as described
24851 in the Ada Reference Manual (13.1(22)). For example, the sequence
24852 of declarations:
24853
24854 @smallexample @c ada
24855 @cartouche
24856 X, Y : Integer := Init_Func;
24857 Q : String (X .. Y) := "abc";
24858 @dots{}
24859 for Q'Address use Compute_Address;
24860 @end cartouche
24861 @end smallexample
24862
24863 @noindent
24864 will be rejected by GNAT, since the address cannot be computed at the time
24865 that @code{Q} is declared. To achieve the intended effect, write instead:
24866
24867 @smallexample @c ada
24868 @group
24869 @cartouche
24870 X, Y : Integer := Init_Func;
24871 Q_Address : constant Address := Compute_Address;
24872 Q : String (X .. Y) := "abc";
24873 @dots{}
24874 for Q'Address use Q_Address;
24875 @end cartouche
24876 @end group
24877 @end smallexample
24878
24879 @noindent
24880 which will be accepted by GNAT (and other Ada compilers), and is also
24881 compatible with Ada 83. A fuller description of the restrictions
24882 on address specifications is found in @ref{Top, GNAT Reference Manual,
24883 About This Guide, gnat_rm, GNAT Reference Manual}.
24884
24885 @node Other Representation Clauses
24886 @subsection Other Representation Clauses
24887
24888 @noindent
24889 GNAT implements in a compatible manner all the representation
24890 clauses supported by HP Ada. In addition, GNAT
24891 implements the representation clause forms that were introduced in Ada 95,
24892 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24893
24894 @node The Package STANDARD
24895 @section The Package @code{STANDARD}
24896
24897 @noindent
24898 The package @code{STANDARD}, as implemented by HP Ada, is fully
24899 described in the @cite{Ada Reference Manual} and in the
24900 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24901 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24902
24903 In addition, HP Ada supports the Latin-1 character set in
24904 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24905 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24906 the type @code{WIDE_CHARACTER}.
24907
24908 The floating-point types supported by GNAT are those
24909 supported by HP Ada, but the defaults are different, and are controlled by
24910 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24911
24912 @node The Package SYSTEM
24913 @section The Package @code{SYSTEM}
24914
24915 @noindent
24916 HP Ada provides a specific version of the package
24917 @code{SYSTEM} for each platform on which the language is implemented.
24918 For the complete spec of the package @code{SYSTEM}, see
24919 Appendix F of the @cite{HP Ada Language Reference Manual}.
24920
24921 On HP Ada, the package @code{SYSTEM} includes the following conversion
24922 functions:
24923 @itemize @bullet
24924 @item @code{TO_ADDRESS(INTEGER)}
24925
24926 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24927
24928 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24929
24930 @item @code{TO_INTEGER(ADDRESS)}
24931
24932 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24933
24934 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24935 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24936 @end itemize
24937
24938 @noindent
24939 By default, GNAT supplies a version of @code{SYSTEM} that matches
24940 the definition given in the @cite{Ada Reference Manual}.
24941 This
24942 is a subset of the HP system definitions, which is as
24943 close as possible to the original definitions. The only difference
24944 is that the definition of @code{SYSTEM_NAME} is different:
24945
24946 @smallexample @c ada
24947 @cartouche
24948 type Name is (SYSTEM_NAME_GNAT);
24949 System_Name : constant Name := SYSTEM_NAME_GNAT;
24950 @end cartouche
24951 @end smallexample
24952
24953 @noindent
24954 Also, GNAT adds the Ada declarations for
24955 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24956
24957 However, the use of the following pragma causes GNAT
24958 to extend the definition of package @code{SYSTEM} so that it
24959 encompasses the full set of HP-specific extensions,
24960 including the functions listed above:
24961
24962 @smallexample @c ada
24963 @cartouche
24964 pragma Extend_System (Aux_DEC);
24965 @end cartouche
24966 @end smallexample
24967
24968 @noindent
24969 The pragma @code{Extend_System} is a configuration pragma that
24970 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24971 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24972
24973 HP Ada does not allow the recompilation of the package
24974 @code{SYSTEM}. Instead HP Ada provides several pragmas
24975 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24976 to modify values in the package @code{SYSTEM}.
24977 On OpenVMS Alpha systems, the pragma
24978 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24979 its single argument.
24980
24981 GNAT does permit the recompilation of package @code{SYSTEM} using
24982 the special switch @option{-gnatg}, and this switch can be used if
24983 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24984 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24985 or @code{MEMORY_SIZE} by any other means.
24986
24987 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24988 enumeration literal @code{SYSTEM_NAME_GNAT}.
24989
24990 The definitions provided by the use of
24991
24992 @smallexample @c ada
24993 pragma Extend_System (AUX_Dec);
24994 @end smallexample
24995
24996 @noindent
24997 are virtually identical to those provided by the HP Ada 83 package
24998 @code{SYSTEM}. One important difference is that the name of the
24999 @code{TO_ADDRESS}
25000 function for type @code{UNSIGNED_LONGWORD} is changed to
25001 @code{TO_ADDRESS_LONG}.
25002 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
25003 discussion of why this change was necessary.
25004
25005 @noindent
25006 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25007 is in fact
25008 an extension to Ada 83 not strictly compatible with the reference manual.
25009 GNAT, in order to be exactly compatible with the standard,
25010 does not provide this capability. In HP Ada 83, the
25011 point of this definition is to deal with a call like:
25012
25013 @smallexample @c ada
25014 TO_ADDRESS (16#12777#);
25015 @end smallexample
25016
25017 @noindent
25018 Normally, according to Ada 83 semantics, one would expect this to be
25019 ambiguous, since it matches both the @code{INTEGER} and
25020 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25021 However, in HP Ada 83, there is no ambiguity, since the
25022 definition using @i{universal_integer} takes precedence.
25023
25024 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25025 it is
25026 not possible to be 100% compatible. Since there are many programs using
25027 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25028 GNAT was
25029 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25030 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25031
25032 @smallexample @c ada
25033 function To_Address (X : Integer) return Address;
25034 pragma Pure_Function (To_Address);
25035
25036 function To_Address_Long (X : Unsigned_Longword) return Address;
25037 pragma Pure_Function (To_Address_Long);
25038 @end smallexample
25039
25040 @noindent
25041 This means that programs using @code{TO_ADDRESS} for
25042 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25043
25044 @node Tasking and Task-Related Features
25045 @section Tasking and Task-Related Features
25046
25047 @noindent
25048 This section compares the treatment of tasking in GNAT
25049 and in HP Ada for OpenVMS Alpha.
25050 The GNAT description applies to both Alpha and I64 OpenVMS.
25051 For detailed information on tasking in
25052 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25053 relevant run-time reference manual.
25054
25055 @menu
25056 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25057 * Assigning Task IDs::
25058 * Task IDs and Delays::
25059 * Task-Related Pragmas::
25060 * Scheduling and Task Priority::
25061 * The Task Stack::
25062 * External Interrupts::
25063 @end menu
25064
25065 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25066 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25067
25068 @noindent
25069 On OpenVMS Alpha systems, each Ada task (except a passive
25070 task) is implemented as a single stream of execution
25071 that is created and managed by the kernel. On these
25072 systems, HP Ada tasking support is based on DECthreads,
25073 an implementation of the POSIX standard for threads.
25074
25075 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25076 code that calls DECthreads routines can be used together.
25077 The interaction between Ada tasks and DECthreads routines
25078 can have some benefits. For example when on OpenVMS Alpha,
25079 HP Ada can call C code that is already threaded.
25080
25081 GNAT uses the facilities of DECthreads,
25082 and Ada tasks are mapped to threads.
25083
25084 @node Assigning Task IDs
25085 @subsection Assigning Task IDs
25086
25087 @noindent
25088 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25089 the environment task that executes the main program. On
25090 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25091 that have been created but are not yet activated.
25092
25093 On OpenVMS Alpha systems, task IDs are assigned at
25094 activation. On GNAT systems, task IDs are also assigned at
25095 task creation but do not have the same form or values as
25096 task ID values in HP Ada. There is no null task, and the
25097 environment task does not have a specific task ID value.
25098
25099 @node Task IDs and Delays
25100 @subsection Task IDs and Delays
25101
25102 @noindent
25103 On OpenVMS Alpha systems, tasking delays are implemented
25104 using Timer System Services. The Task ID is used for the
25105 identification of the timer request (the @code{REQIDT} parameter).
25106 If Timers are used in the application take care not to use
25107 @code{0} for the identification, because cancelling such a timer
25108 will cancel all timers and may lead to unpredictable results.
25109
25110 @node Task-Related Pragmas
25111 @subsection Task-Related Pragmas
25112
25113 @noindent
25114 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25115 specification of the size of the guard area for a task
25116 stack. (The guard area forms an area of memory that has no
25117 read or write access and thus helps in the detection of
25118 stack overflow.) On OpenVMS Alpha systems, if the pragma
25119 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25120 area is created. In the absence of a pragma @code{TASK_STORAGE},
25121 a default guard area is created.
25122
25123 GNAT supplies the following task-related pragmas:
25124
25125 @itemize @bullet
25126 @item  @code{TASK_INFO}
25127
25128 This pragma appears within a task definition and
25129 applies to the task in which it appears. The argument
25130 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25131
25132 @item  @code{TASK_STORAGE}
25133
25134 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25135 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25136 @code{SUPPRESS}, and @code{VOLATILE}.
25137 @end itemize
25138 @node Scheduling and Task Priority
25139 @subsection Scheduling and Task Priority
25140
25141 @noindent
25142 HP Ada implements the Ada language requirement that
25143 when two tasks are eligible for execution and they have
25144 different priorities, the lower priority task does not
25145 execute while the higher priority task is waiting. The HP
25146 Ada Run-Time Library keeps a task running until either the
25147 task is suspended or a higher priority task becomes ready.
25148
25149 On OpenVMS Alpha systems, the default strategy is round-
25150 robin with preemption. Tasks of equal priority take turns
25151 at the processor. A task is run for a certain period of
25152 time and then placed at the tail of the ready queue for
25153 its priority level.
25154
25155 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25156 which can be used to enable or disable round-robin
25157 scheduling of tasks with the same priority.
25158 See the relevant HP Ada run-time reference manual for
25159 information on using the pragmas to control HP Ada task
25160 scheduling.
25161
25162 GNAT follows the scheduling rules of Annex D (Real-Time
25163 Annex) of the @cite{Ada Reference Manual}. In general, this
25164 scheduling strategy is fully compatible with HP Ada
25165 although it provides some additional constraints (as
25166 fully documented in Annex D).
25167 GNAT implements time slicing control in a manner compatible with
25168 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25169 are identical to the HP Ada 83 pragma of the same name.
25170 Note that it is not possible to mix GNAT tasking and
25171 HP Ada 83 tasking in the same program, since the two run-time
25172 libraries are not compatible.
25173
25174 @node The Task Stack
25175 @subsection The Task Stack
25176
25177 @noindent
25178 In HP Ada, a task stack is allocated each time a
25179 non-passive task is activated. As soon as the task is
25180 terminated, the storage for the task stack is deallocated.
25181 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25182 a default stack size is used. Also, regardless of the size
25183 specified, some additional space is allocated for task
25184 management purposes. On OpenVMS Alpha systems, at least
25185 one page is allocated.
25186
25187 GNAT handles task stacks in a similar manner. In accordance with
25188 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25189 an alternative method for controlling the task stack size.
25190 The specification of the attribute @code{T'STORAGE_SIZE} is also
25191 supported in a manner compatible with HP Ada.
25192
25193 @node External Interrupts
25194 @subsection External Interrupts
25195
25196 @noindent
25197 On HP Ada, external interrupts can be associated with task entries.
25198 GNAT is compatible with HP Ada in its handling of external interrupts.
25199
25200 @node Pragmas and Pragma-Related Features
25201 @section Pragmas and Pragma-Related Features
25202
25203 @noindent
25204 Both HP Ada and GNAT supply all language-defined pragmas
25205 as specified by the Ada 83 standard. GNAT also supplies all
25206 language-defined pragmas introduced by Ada 95 and Ada 2005.
25207 In addition, GNAT implements the implementation-defined pragmas
25208 from HP Ada 83.
25209
25210 @itemize @bullet
25211 @item  @code{AST_ENTRY}
25212
25213 @item  @code{COMMON_OBJECT}
25214
25215 @item  @code{COMPONENT_ALIGNMENT}
25216
25217 @item  @code{EXPORT_EXCEPTION}
25218
25219 @item  @code{EXPORT_FUNCTION}
25220
25221 @item  @code{EXPORT_OBJECT}
25222
25223 @item  @code{EXPORT_PROCEDURE}
25224
25225 @item  @code{EXPORT_VALUED_PROCEDURE}
25226
25227 @item  @code{FLOAT_REPRESENTATION}
25228
25229 @item  @code{IDENT}
25230
25231 @item  @code{IMPORT_EXCEPTION}
25232
25233 @item  @code{IMPORT_FUNCTION}
25234
25235 @item  @code{IMPORT_OBJECT}
25236
25237 @item  @code{IMPORT_PROCEDURE}
25238
25239 @item  @code{IMPORT_VALUED_PROCEDURE}
25240
25241 @item  @code{INLINE_GENERIC}
25242
25243 @item  @code{INTERFACE_NAME}
25244
25245 @item  @code{LONG_FLOAT}
25246
25247 @item  @code{MAIN_STORAGE}
25248
25249 @item  @code{PASSIVE}
25250
25251 @item  @code{PSECT_OBJECT}
25252
25253 @item  @code{SHARE_GENERIC}
25254
25255 @item  @code{SUPPRESS_ALL}
25256
25257 @item  @code{TASK_STORAGE}
25258
25259 @item  @code{TIME_SLICE}
25260
25261 @item  @code{TITLE}
25262 @end itemize
25263
25264 @noindent
25265 These pragmas are all fully implemented, with the exception of @code{TITLE},
25266 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25267 recognized, but which have no
25268 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25269 use of Ada protected objects. In GNAT, all generics are inlined.
25270
25271 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25272 a separate subprogram specification which must appear before the
25273 subprogram body.
25274
25275 GNAT also supplies a number of implementation-defined pragmas as follows:
25276 @itemize @bullet
25277 @item  @code{ABORT_DEFER}
25278
25279 @item  @code{ADA_83}
25280
25281 @item  @code{ADA_95}
25282
25283 @item  @code{ADA_05}
25284
25285 @item  @code{ANNOTATE}
25286
25287 @item  @code{ASSERT}
25288
25289 @item  @code{C_PASS_BY_COPY}
25290
25291 @item  @code{CPP_CLASS}
25292
25293 @item  @code{CPP_CONSTRUCTOR}
25294
25295 @item  @code{CPP_DESTRUCTOR}
25296
25297 @item  @code{DEBUG}
25298
25299 @item  @code{EXTEND_SYSTEM}
25300
25301 @item  @code{LINKER_ALIAS}
25302
25303 @item  @code{LINKER_SECTION}
25304
25305 @item  @code{MACHINE_ATTRIBUTE}
25306
25307 @item  @code{NO_RETURN}
25308
25309 @item  @code{PURE_FUNCTION}
25310
25311 @item  @code{SOURCE_FILE_NAME}
25312
25313 @item  @code{SOURCE_REFERENCE}
25314
25315 @item  @code{TASK_INFO}
25316
25317 @item  @code{UNCHECKED_UNION}
25318
25319 @item  @code{UNIMPLEMENTED_UNIT}
25320
25321 @item  @code{UNIVERSAL_DATA}
25322
25323 @item  @code{UNSUPPRESS}
25324
25325 @item  @code{WARNINGS}
25326
25327 @item  @code{WEAK_EXTERNAL}
25328 @end itemize
25329
25330 @noindent
25331 For full details on these GNAT implementation-defined pragmas,
25332 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25333 Manual}.
25334
25335 @menu
25336 * Restrictions on the Pragma INLINE::
25337 * Restrictions on the Pragma INTERFACE::
25338 * Restrictions on the Pragma SYSTEM_NAME::
25339 @end menu
25340
25341 @node Restrictions on the Pragma INLINE
25342 @subsection Restrictions on Pragma @code{INLINE}
25343
25344 @noindent
25345 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25346 @itemize @bullet
25347 @item  Parameters cannot have a task type.
25348
25349 @item  Function results cannot be task types, unconstrained
25350 array types, or unconstrained types with discriminants.
25351
25352 @item  Bodies cannot declare the following:
25353 @itemize @bullet
25354 @item  Subprogram body or stub (imported subprogram is allowed)
25355
25356 @item  Tasks
25357
25358 @item  Generic declarations
25359
25360 @item  Instantiations
25361
25362 @item  Exceptions
25363
25364 @item  Access types (types derived from access types allowed)
25365
25366 @item  Array or record types
25367
25368 @item  Dependent tasks
25369
25370 @item  Direct recursive calls of subprogram or containing
25371 subprogram, directly or via a renaming
25372
25373 @end itemize
25374 @end itemize
25375
25376 @noindent
25377 In GNAT, the only restriction on pragma @code{INLINE} is that the
25378 body must occur before the call if both are in the same
25379 unit, and the size must be appropriately small. There are
25380 no other specific restrictions which cause subprograms to
25381 be incapable of being inlined.
25382
25383 @node  Restrictions on the Pragma INTERFACE
25384 @subsection  Restrictions on Pragma @code{INTERFACE}
25385
25386 @noindent
25387 The following restrictions on pragma @code{INTERFACE}
25388 are enforced by both HP Ada and GNAT:
25389 @itemize @bullet
25390 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25391 Default is the default on OpenVMS Alpha systems.
25392
25393 @item  Parameter passing: Language specifies default
25394 mechanisms but can be overridden with an @code{EXPORT} pragma.
25395
25396 @itemize @bullet
25397 @item  Ada: Use internal Ada rules.
25398
25399 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25400 record or task type. Result cannot be a string, an
25401 array, or a record.
25402
25403 @item  Fortran: Parameters cannot have a task type. Result cannot
25404 be a string, an array, or a record.
25405 @end itemize
25406 @end itemize
25407
25408 @noindent
25409 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25410 record parameters for all languages.
25411
25412 @node  Restrictions on the Pragma SYSTEM_NAME
25413 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25414
25415 @noindent
25416 For HP Ada for OpenVMS Alpha, the enumeration literal
25417 for the type @code{NAME} is @code{OPENVMS_AXP}.
25418 In GNAT, the enumeration
25419 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25420
25421 @node  Library of Predefined Units
25422 @section  Library of Predefined Units
25423
25424 @noindent
25425 A library of predefined units is provided as part of the
25426 HP Ada and GNAT implementations. HP Ada does not provide
25427 the package @code{MACHINE_CODE} but instead recommends importing
25428 assembler code.
25429
25430 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25431 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25432 version.
25433 The HP Ada Predefined Library units are modified to remove post-Ada 83
25434 incompatibilities and to make them interoperable with GNAT
25435 (@pxref{Changes to DECLIB}, for details).
25436 The units are located in the @file{DECLIB} directory.
25437
25438 The GNAT RTL is contained in
25439 the @file{ADALIB} directory, and
25440 the default search path is set up to find @code{DECLIB} units in preference
25441 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25442 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25443
25444 @menu
25445 * Changes to DECLIB::
25446 @end menu
25447
25448 @node Changes to DECLIB
25449 @subsection Changes to @code{DECLIB}
25450
25451 @noindent
25452 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25453 compatibility are minor and include the following:
25454
25455 @itemize @bullet
25456 @item  Adjusting the location of pragmas and record representation
25457 clauses to obey Ada 95 (and thus Ada 2005) rules
25458
25459 @item  Adding the proper notation to generic formal parameters
25460 that take unconstrained types in instantiation
25461
25462 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25463 that have package bodies not otherwise allowed
25464
25465 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25466 ``@code{PROTECTD}''.
25467 Currently these are found only in the @code{STARLET} package spec.
25468
25469 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25470 where the address size is constrained to 32 bits.
25471 @end itemize
25472
25473 @noindent
25474 None of the above changes is visible to users.
25475
25476 @node Bindings
25477 @section Bindings
25478
25479 @noindent
25480 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25481 @itemize @bullet
25482
25483 @item  Command Language Interpreter (CLI interface)
25484
25485 @item  DECtalk Run-Time Library (DTK interface)
25486
25487 @item  Librarian utility routines (LBR interface)
25488
25489 @item  General Purpose Run-Time Library (LIB interface)
25490
25491 @item  Math Run-Time Library (MTH interface)
25492
25493 @item  National Character Set Run-Time Library (NCS interface)
25494
25495 @item  Compiled Code Support Run-Time Library (OTS interface)
25496
25497 @item  Parallel Processing Run-Time Library (PPL interface)
25498
25499 @item  Screen Management Run-Time Library (SMG interface)
25500
25501 @item  Sort Run-Time Library (SOR interface)
25502
25503 @item  String Run-Time Library (STR interface)
25504
25505 @item STARLET System Library
25506 @findex Starlet
25507
25508 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25509
25510 @item  X Windows Toolkit (XT interface)
25511
25512 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25513 @end itemize
25514
25515 @noindent
25516 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25517 directory, on both the Alpha and I64 OpenVMS platforms.
25518
25519 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25520 in the
25521 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25522 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25523 @code{Xt}, and @code{X_Lib}
25524 causing the default X/Motif sharable image libraries to be linked in. This
25525 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25526 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25527
25528 It may be necessary to edit these options files to update or correct the
25529 library names if, for example, the newer X/Motif bindings from
25530 @file{ADA$EXAMPLES}
25531 had been (previous to installing GNAT) copied and renamed to supersede the
25532 default @file{ADA$PREDEFINED} versions.
25533
25534 @menu
25535 * Shared Libraries and Options Files::
25536 * Interfaces to C::
25537 @end menu
25538
25539 @node Shared Libraries and Options Files
25540 @subsection Shared Libraries and Options Files
25541
25542 @noindent
25543 When using the HP Ada
25544 predefined X and Motif bindings, the linking with their sharable images is
25545 done automatically by @command{GNAT LINK}.
25546 When using other X and Motif bindings, you need
25547 to add the corresponding sharable images to the command line for
25548 @code{GNAT LINK}. When linking with shared libraries, or with
25549 @file{.OPT} files, you must
25550 also add them to the command line for @command{GNAT LINK}.
25551
25552 A shared library to be used with GNAT is built in the same way as other
25553 libraries under VMS. The VMS Link command can be used in standard fashion.
25554
25555 @node Interfaces to C
25556 @subsection Interfaces to C
25557
25558 @noindent
25559 HP Ada
25560 provides the following Ada types and operations:
25561
25562 @itemize @bullet
25563 @item C types package (@code{C_TYPES})
25564
25565 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25566
25567 @item Other_types (@code{SHORT_INT})
25568 @end itemize
25569
25570 @noindent
25571 Interfacing to C with GNAT, you can use the above approach
25572 described for HP Ada or the facilities of Annex B of
25573 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25574 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25575 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25576
25577 The @option{-gnatF} qualifier forces default and explicit
25578 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25579 to be uppercased for compatibility with the default behavior
25580 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25581
25582 @node Main Program Definition
25583 @section Main Program Definition
25584
25585 @noindent
25586 The following section discusses differences in the
25587 definition of main programs on HP Ada and GNAT.
25588 On HP Ada, main programs are defined to meet the
25589 following conditions:
25590 @itemize @bullet
25591 @item  Procedure with no formal parameters (returns @code{0} upon
25592 normal completion)
25593
25594 @item  Procedure with no formal parameters (returns @code{42} when
25595 an unhandled exception is raised)
25596
25597 @item  Function with no formal parameters whose returned value
25598 is of a discrete type
25599
25600 @item  Procedure with one @code{out} formal of a discrete type for
25601 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25602
25603 @end itemize
25604
25605 @noindent
25606 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25607 a main function or main procedure returns a discrete
25608 value whose size is less than 64 bits (32 on VAX systems),
25609 the value is zero- or sign-extended as appropriate.
25610 On GNAT, main programs are defined as follows:
25611 @itemize @bullet
25612 @item  Must be a non-generic, parameterless subprogram that
25613 is either a procedure or function returning an Ada
25614 @code{STANDARD.INTEGER} (the predefined type)
25615
25616 @item  Cannot be a generic subprogram or an instantiation of a
25617 generic subprogram
25618 @end itemize
25619
25620 @node Implementation-Defined Attributes
25621 @section Implementation-Defined Attributes
25622
25623 @noindent
25624 GNAT provides all HP Ada implementation-defined
25625 attributes.
25626
25627 @node Compiler and Run-Time Interfacing
25628 @section Compiler and Run-Time Interfacing
25629
25630 @noindent
25631 HP Ada provides the following qualifiers to pass options to the linker
25632 (ACS LINK):
25633 @itemize @bullet
25634 @item  @option{/WAIT} and @option{/SUBMIT}
25635
25636 @item  @option{/COMMAND}
25637
25638 @item  @option{/@r{[}NO@r{]}MAP}
25639
25640 @item  @option{/OUTPUT=@var{file-spec}}
25641
25642 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25643 @end itemize
25644
25645 @noindent
25646 To pass options to the linker, GNAT provides the following
25647 switches:
25648
25649 @itemize @bullet
25650 @item   @option{/EXECUTABLE=@var{exec-name}}
25651
25652 @item   @option{/VERBOSE}
25653
25654 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25655 @end itemize
25656
25657 @noindent
25658 For more information on these switches, see
25659 @ref{Switches for gnatlink}.
25660 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25661 to control optimization. HP Ada also supplies the
25662 following pragmas:
25663 @itemize @bullet
25664 @item  @code{OPTIMIZE}
25665
25666 @item  @code{INLINE}
25667
25668 @item  @code{INLINE_GENERIC}
25669
25670 @item  @code{SUPPRESS_ALL}
25671
25672 @item  @code{PASSIVE}
25673 @end itemize
25674
25675 @noindent
25676 In GNAT, optimization is controlled strictly by command
25677 line parameters, as described in the corresponding section of this guide.
25678 The HP pragmas for control of optimization are
25679 recognized but ignored.
25680
25681 Note that in GNAT, the default is optimization off, whereas in HP Ada
25682 the default is that optimization is turned on.
25683
25684 @node Program Compilation and Library Management
25685 @section Program Compilation and Library Management
25686
25687 @noindent
25688 HP Ada and GNAT provide a comparable set of commands to
25689 build programs. HP Ada also provides a program library,
25690 which is a concept that does not exist on GNAT. Instead,
25691 GNAT provides directories of sources that are compiled as
25692 needed.
25693
25694 The following table summarizes
25695 the HP Ada commands and provides
25696 equivalent GNAT commands. In this table, some GNAT
25697 equivalents reflect the fact that GNAT does not use the
25698 concept of a program library. Instead, it uses a model
25699 in which collections of source and object files are used
25700 in a manner consistent with other languages like C and
25701 Fortran. Therefore, standard system file commands are used
25702 to manipulate these elements. Those GNAT commands are marked with
25703 an asterisk.
25704 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25705
25706 @need 1500
25707 @multitable @columnfractions .35 .65
25708
25709 @item @emph{HP Ada Command}
25710 @tab @emph{GNAT Equivalent / Description}
25711
25712 @item @command{ADA}
25713 @tab @command{GNAT COMPILE}@*
25714 Invokes the compiler to compile one or more Ada source files.
25715
25716 @item @command{ACS ATTACH}@*
25717 @tab [No equivalent]@*
25718 Switches control of terminal from current process running the program
25719 library manager.
25720
25721 @item @command{ACS CHECK}
25722 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25723 Forms the execution closure of one
25724 or more compiled units and checks completeness and currency.
25725
25726 @item @command{ACS COMPILE}
25727 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25728 Forms the execution closure of one or
25729 more specified units, checks completeness and currency,
25730 identifies units that have revised source files, compiles same,
25731 and recompiles units that are or will become obsolete.
25732 Also completes incomplete generic instantiations.
25733
25734 @item @command{ACS COPY FOREIGN}
25735 @tab Copy (*)@*
25736 Copies a foreign object file into the program library as a
25737 library unit body.
25738
25739 @item @command{ACS COPY UNIT}
25740 @tab Copy (*)@*
25741 Copies a compiled unit from one program library to another.
25742
25743 @item @command{ACS CREATE LIBRARY}
25744 @tab Create /directory (*)@*
25745 Creates a program library.
25746
25747 @item @command{ACS CREATE SUBLIBRARY}
25748 @tab Create /directory (*)@*
25749 Creates a program sublibrary.
25750
25751 @item @command{ACS DELETE LIBRARY}
25752 @tab @*
25753 Deletes a program library and its contents.
25754
25755 @item @command{ACS DELETE SUBLIBRARY}
25756 @tab @*
25757 Deletes a program sublibrary and its contents.
25758
25759 @item @command{ACS DELETE UNIT}
25760 @tab Delete file (*)@*
25761 On OpenVMS systems, deletes one or more compiled units from
25762 the current program library.
25763
25764 @item @command{ACS DIRECTORY}
25765 @tab Directory (*)@*
25766 On OpenVMS systems, lists units contained in the current
25767 program library.
25768
25769 @item @command{ACS ENTER FOREIGN}
25770 @tab Copy (*)@*
25771 Allows the import of a foreign body as an Ada library
25772 spec and enters a reference to a pointer.
25773
25774 @item @command{ACS ENTER UNIT}
25775 @tab Copy (*)@*
25776 Enters a reference (pointer) from the current program library to
25777 a unit compiled into another program library.
25778
25779 @item @command{ACS EXIT}
25780 @tab [No equivalent]@*
25781 Exits from the program library manager.
25782
25783 @item @command{ACS EXPORT}
25784 @tab Copy (*)@*
25785 Creates an object file that contains system-specific object code
25786 for one or more units. With GNAT, object files can simply be copied
25787 into the desired directory.
25788
25789 @item @command{ACS EXTRACT SOURCE}
25790 @tab Copy (*)@*
25791 Allows access to the copied source file for each Ada compilation unit
25792
25793 @item @command{ACS HELP}
25794 @tab @command{HELP GNAT}@*
25795 Provides online help.
25796
25797 @item @command{ACS LINK}
25798 @tab @command{GNAT LINK}@*
25799 Links an object file containing Ada units into an executable file.
25800
25801 @item @command{ACS LOAD}
25802 @tab Copy (*)@*
25803 Loads (partially compiles) Ada units into the program library.
25804 Allows loading a program from a collection of files into a library
25805 without knowing the relationship among units.
25806
25807 @item @command{ACS MERGE}
25808 @tab Copy (*)@*
25809 Merges into the current program library, one or more units from
25810 another library where they were modified.
25811
25812 @item @command{ACS RECOMPILE}
25813 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25814 Recompiles from   external or copied source files any obsolete
25815 unit in the closure. Also, completes any incomplete generic
25816 instantiations.
25817
25818 @item @command{ACS REENTER}
25819 @tab @command{GNAT MAKE}@*
25820 Reenters current references to units compiled after last entered
25821 with the @command{ACS ENTER UNIT} command.
25822
25823 @item @command{ACS SET LIBRARY}
25824 @tab Set default (*)@*
25825 Defines a program library to be the compilation context as well
25826 as the target library for compiler output and commands in general.
25827
25828 @item @command{ACS SET PRAGMA}
25829 @tab Edit @file{gnat.adc} (*)@*
25830 Redefines specified  values of the library characteristics
25831 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25832 and @code{Float_Representation}.
25833
25834 @item @command{ACS SET SOURCE}
25835 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25836 Defines the source file search list for the @command{ACS COMPILE} command.
25837
25838 @item @command{ACS SHOW LIBRARY}
25839 @tab Directory (*)@*
25840 Lists information about one or more program libraries.
25841
25842 @item @command{ACS SHOW PROGRAM}
25843 @tab [No equivalent]@*
25844 Lists information about the execution closure of one or
25845 more units in the program library.
25846
25847 @item @command{ACS SHOW SOURCE}
25848 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25849 Shows the source file search used when compiling units.
25850
25851 @item @command{ACS SHOW VERSION}
25852 @tab Compile with @option{VERBOSE} option
25853 Displays the version number of the compiler and program library
25854 manager used.
25855
25856 @item @command{ACS SPAWN}
25857 @tab [No equivalent]@*
25858 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25859 command).
25860
25861 @item @command{ACS VERIFY}
25862 @tab [No equivalent]@*
25863 Performs a series of consistency checks on a program library to
25864 determine whether the library structure and library files are in
25865 valid form.
25866 @end multitable
25867
25868 @noindent
25869
25870 @node Input-Output
25871 @section Input-Output
25872
25873 @noindent
25874 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25875 Management Services (RMS) to perform operations on
25876 external files.
25877
25878 @noindent
25879 HP Ada and GNAT predefine an identical set of input-
25880 output packages. To make the use of the
25881 generic @code{TEXT_IO} operations more convenient, HP Ada
25882 provides predefined library packages that instantiate the
25883 integer and floating-point operations for the predefined
25884 integer and floating-point types as shown in the following table.
25885
25886 @multitable @columnfractions .45 .55
25887 @item @emph{Package Name} @tab Instantiation
25888
25889 @item @code{INTEGER_TEXT_IO}
25890 @tab @code{INTEGER_IO(INTEGER)}
25891
25892 @item @code{SHORT_INTEGER_TEXT_IO}
25893 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25894
25895 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25896 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25897
25898 @item @code{FLOAT_TEXT_IO}
25899 @tab @code{FLOAT_IO(FLOAT)}
25900
25901 @item @code{LONG_FLOAT_TEXT_IO}
25902 @tab @code{FLOAT_IO(LONG_FLOAT)}
25903 @end multitable
25904
25905 @noindent
25906 The HP Ada predefined packages and their operations
25907 are implemented using OpenVMS Alpha files and input-output
25908 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25909 Familiarity with the following is recommended:
25910 @itemize @bullet
25911 @item  RMS file organizations and access methods
25912
25913 @item  OpenVMS file specifications and directories
25914
25915 @item  OpenVMS File Definition Language (FDL)
25916 @end itemize
25917
25918 @noindent
25919 GNAT provides I/O facilities that are completely
25920 compatible with HP Ada. The distribution includes the
25921 standard HP Ada versions of all I/O packages, operating
25922 in a manner compatible with HP Ada. In particular, the
25923 following packages are by default the HP Ada (Ada 83)
25924 versions of these packages rather than the renamings
25925 suggested in Annex J of the Ada Reference Manual:
25926 @itemize @bullet
25927 @item  @code{TEXT_IO}
25928
25929 @item  @code{SEQUENTIAL_IO}
25930
25931 @item  @code{DIRECT_IO}
25932 @end itemize
25933
25934 @noindent
25935 The use of the standard child package syntax (for
25936 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25937 packages.
25938 GNAT provides HP-compatible predefined instantiations
25939 of the @code{TEXT_IO} packages, and also
25940 provides the standard predefined instantiations required
25941 by the @cite{Ada Reference Manual}.
25942
25943 For further information on how GNAT interfaces to the file
25944 system or how I/O is implemented in programs written in
25945 mixed languages, see @ref{Implementation of the Standard I/O,,,
25946 gnat_rm, GNAT Reference Manual}.
25947 This chapter covers the following:
25948 @itemize @bullet
25949 @item  Standard I/O packages
25950
25951 @item  @code{FORM} strings
25952
25953 @item  @code{ADA.DIRECT_IO}
25954
25955 @item  @code{ADA.SEQUENTIAL_IO}
25956
25957 @item  @code{ADA.TEXT_IO}
25958
25959 @item  Stream pointer positioning
25960
25961 @item  Reading and writing non-regular files
25962
25963 @item  @code{GET_IMMEDIATE}
25964
25965 @item  Treating @code{TEXT_IO} files as streams
25966
25967 @item  Shared files
25968
25969 @item  Open modes
25970 @end itemize
25971
25972 @node Implementation Limits
25973 @section Implementation Limits
25974
25975 @noindent
25976 The following table lists implementation limits for HP Ada
25977 and GNAT systems.
25978 @multitable @columnfractions .60 .20 .20
25979 @sp 1
25980 @item  @emph{Compilation Parameter}
25981 @tab   @emph{HP Ada}
25982 @tab   @emph{GNAT}
25983 @sp 1
25984
25985 @item  In a subprogram or entry  declaration, maximum number of
25986 formal parameters that are of an unconstrained record type
25987 @tab   32
25988 @tab   No set limit
25989 @sp 1
25990
25991 @item  Maximum identifier length (number of characters)
25992 @tab   255
25993 @tab   32766
25994 @sp 1
25995
25996 @item  Maximum number of characters in a source line
25997 @tab   255
25998 @tab   32766
25999 @sp 1
26000
26001 @item  Maximum collection size   (number of bytes)
26002 @tab   2**31-1
26003 @tab   2**31-1
26004 @sp 1
26005
26006 @item  Maximum number of discriminants for a record type
26007 @tab   245
26008 @tab   No set limit
26009 @sp 1
26010
26011 @item  Maximum number of formal parameters in an entry or
26012 subprogram declaration
26013 @tab   246
26014 @tab    No set limit
26015 @sp 1
26016
26017 @item  Maximum number of dimensions in an array type
26018 @tab   255
26019 @tab   No set limit
26020 @sp 1
26021
26022 @item  Maximum number of library  units and subunits in a compilation.
26023 @tab   4095
26024 @tab   No set limit
26025 @sp 1
26026
26027 @item  Maximum number of library units and subunits in an execution.
26028 @tab   16383
26029 @tab   No set limit
26030 @sp 1
26031
26032 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26033 or @code{PSECT_OBJECT}
26034 @tab   32757
26035 @tab   No set limit
26036 @sp 1
26037
26038 @item  Maximum number of enumeration literals in an enumeration type
26039 definition
26040 @tab   65535
26041 @tab   No set limit
26042 @sp 1
26043
26044 @item  Maximum number of lines in a source file
26045 @tab   65534
26046 @tab   No set limit
26047 @sp 1
26048
26049 @item  Maximum number of bits in any object
26050 @tab   2**31-1
26051 @tab   2**31-1
26052 @sp 1
26053
26054 @item  Maximum size of the static portion of a stack frame (approximate)
26055 @tab   2**31-1
26056 @tab   2**31-1
26057 @end multitable
26058
26059 @node Tools and Utilities
26060 @section Tools and Utilities
26061
26062 @noindent
26063 The following table lists some of the OpenVMS development tools
26064 available for HP Ada, and the corresponding tools for
26065 use with @value{EDITION} on Alpha and I64 platforms.
26066 Aside from the debugger, all the OpenVMS tools identified are part
26067 of the DECset package.
26068
26069 @iftex
26070 @c Specify table in TeX since Texinfo does a poor job
26071 @tex
26072 \smallskip
26073 \smallskip
26074 \settabs\+Language-Sensitive Editor\quad
26075    &Product with HP Ada\quad
26076    &\cr
26077 \+\it Tool
26078    &\it Product with HP Ada
26079    & \it Product with GNAT Pro\cr
26080 \smallskip
26081 \+Code Management System
26082    &HP CMS
26083    & HP CMS\cr
26084 \smallskip
26085 \+Language-Sensitive Editor
26086    &HP LSE
26087    & emacs or HP LSE (Alpha)\cr
26088 \+
26089    &
26090    & HP LSE (I64)\cr
26091 \smallskip
26092 \+Debugger
26093    &OpenVMS Debug
26094    & gdb (Alpha),\cr
26095 \+
26096    &
26097    & OpenVMS Debug (I64)\cr
26098 \smallskip
26099 \+Source Code Analyzer /
26100    &HP SCA
26101    & GNAT XREF\cr
26102 \+Cross Referencer
26103    &
26104    &\cr
26105 \smallskip
26106 \+Test Manager
26107    &HP Digital Test
26108    & HP DTM\cr
26109 \+
26110    &Manager (DTM)
26111    &\cr
26112 \smallskip
26113 \+Performance and
26114    & HP PCA
26115    & HP PCA\cr
26116 \+Coverage Analyzer
26117    &
26118    &\cr
26119 \smallskip
26120 \+Module Management
26121    & HP MMS
26122    & Not applicable\cr
26123 \+ System
26124    &
26125    &\cr
26126 \smallskip
26127 \smallskip
26128 @end tex
26129 @end iftex
26130
26131 @ifnottex
26132 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26133 @c the TeX version above for the printed version
26134 @flushleft
26135 @c @multitable @columnfractions .3 .4 .4
26136 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26137 @item @i{Tool}
26138 @tab @i{Tool with HP Ada}
26139 @tab @i{Tool with @value{EDITION}}
26140 @item Code Management@*System
26141 @tab HP CMS
26142 @tab HP CMS
26143 @item Language-Sensitive@*Editor
26144 @tab HP LSE
26145 @tab emacs or HP LSE (Alpha)
26146 @item
26147 @tab
26148 @tab HP LSE (I64)
26149 @item Debugger
26150 @tab OpenVMS Debug
26151 @tab gdb (Alpha),
26152 @item
26153 @tab
26154 @tab OpenVMS Debug (I64)
26155 @item Source Code Analyzer /@*Cross Referencer
26156 @tab HP SCA
26157 @tab GNAT XREF
26158 @item Test Manager
26159 @tab HP Digital Test@*Manager (DTM)
26160 @tab HP DTM
26161 @item Performance and@*Coverage Analyzer
26162 @tab HP PCA
26163 @tab HP PCA
26164 @item Module Management@*System
26165 @tab HP MMS
26166 @tab Not applicable
26167 @end multitable
26168 @end flushleft
26169 @end ifnottex
26170
26171 @end ifset
26172
26173 @c **************************************
26174 @node Platform-Specific Information for the Run-Time Libraries
26175 @appendix Platform-Specific Information for the Run-Time Libraries
26176 @cindex Tasking and threads libraries
26177 @cindex Threads libraries and tasking
26178 @cindex Run-time libraries (platform-specific information)
26179
26180 @noindent
26181 The GNAT run-time implementation may vary with respect to both the
26182 underlying threads library and the exception handling scheme.
26183 For threads support, one or more of the following are supplied:
26184 @itemize @bullet
26185 @item @b{native threads library}, a binding to the thread package from
26186 the underlying operating system
26187
26188 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26189 POSIX thread package
26190 @end itemize
26191
26192 @noindent
26193 For exception handling, either or both of two models are supplied:
26194 @itemize @bullet
26195 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26196 Most programs should experience a substantial speed improvement by
26197 being compiled with a ZCX run-time.
26198 This is especially true for
26199 tasking applications or applications with many exception handlers.}
26200 @cindex Zero-Cost Exceptions
26201 @cindex ZCX (Zero-Cost Exceptions)
26202 which uses binder-generated tables that
26203 are interrogated at run time to locate a handler
26204
26205 @item @b{setjmp / longjmp} (``SJLJ''),
26206 @cindex setjmp/longjmp Exception Model
26207 @cindex SJLJ (setjmp/longjmp Exception Model)
26208 which uses dynamically-set data to establish
26209 the set of handlers
26210 @end itemize
26211
26212 @noindent
26213 This appendix summarizes which combinations of threads and exception support
26214 are supplied on various GNAT platforms.
26215 It then shows how to select a particular library either
26216 permanently or temporarily,
26217 explains the properties of (and tradeoffs among) the various threads
26218 libraries, and provides some additional
26219 information about several specific platforms.
26220
26221 @menu
26222 * Summary of Run-Time Configurations::
26223 * Specifying a Run-Time Library::
26224 * Choosing the Scheduling Policy::
26225 * Solaris-Specific Considerations::
26226 * Linux-Specific Considerations::
26227 * AIX-Specific Considerations::
26228 * Irix-Specific Considerations::
26229 * RTX-Specific Considerations::
26230 @end menu
26231
26232 @node Summary of Run-Time Configurations
26233 @section Summary of Run-Time Configurations
26234
26235 @multitable @columnfractions .30 .70
26236 @item @b{alpha-openvms}
26237 @item @code{@ @ }@i{rts-native (default)}
26238 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26239 @item @code{@ @ @ @ }Exceptions @tab ZCX
26240 @*
26241 @item @b{alpha-tru64}
26242 @item @code{@ @ }@i{rts-native (default)}
26243 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26244 @item @code{@ @ @ @ }Exceptions @tab ZCX
26245 @*
26246 @item @code{@ @ }@i{rts-sjlj}
26247 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26248 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26249 @*
26250 @item @b{ia64-hp_linux}
26251 @item @code{@ @ }@i{rts-native (default)}
26252 @item @code{@ @ @ @ }Tasking    @tab pthread library
26253 @item @code{@ @ @ @ }Exceptions @tab ZCX
26254 @*
26255 @item @b{ia64-hpux}
26256 @item @code{@ @ }@i{rts-native (default)}
26257 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26258 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26259 @*
26260 @item @b{ia64-openvms}
26261 @item @code{@ @ }@i{rts-native (default)}
26262 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26263 @item @code{@ @ @ @ }Exceptions @tab ZCX
26264 @*
26265 @item @b{ia64-sgi_linux}
26266 @item @code{@ @ }@i{rts-native (default)}
26267 @item @code{@ @ @ @ }Tasking    @tab pthread library
26268 @item @code{@ @ @ @ }Exceptions @tab ZCX
26269 @*
26270 @item @b{mips-irix}
26271 @item @code{@ @ }@i{rts-native (default)}
26272 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26273 @item @code{@ @ @ @ }Exceptions @tab ZCX
26274 @*
26275 @item @b{pa-hpux}
26276 @item @code{@ @ }@i{rts-native (default)}
26277 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26278 @item @code{@ @ @ @ }Exceptions @tab ZCX
26279 @*
26280 @item @code{@ @ }@i{rts-sjlj}
26281 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26282 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26283 @*
26284 @item @b{ppc-aix}
26285 @item @code{@ @ }@i{rts-native (default)}
26286 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26287 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26288 @*
26289 @item @b{ppc-darwin}
26290 @item @code{@ @ }@i{rts-native (default)}
26291 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26292 @item @code{@ @ @ @ }Exceptions @tab ZCX
26293 @*
26294 @item @b{sparc-solaris}  @tab
26295 @item @code{@ @ }@i{rts-native (default)}
26296 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26297 @item @code{@ @ @ @ }Exceptions @tab ZCX
26298 @*
26299 @item @code{@ @ }@i{rts-pthread}
26300 @item @code{@ @ @ @ }Tasking    @tab pthread library
26301 @item @code{@ @ @ @ }Exceptions @tab ZCX
26302 @*
26303 @item @code{@ @ }@i{rts-sjlj}
26304 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26305 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26306 @*
26307 @item @b{sparc64-solaris}  @tab
26308 @item @code{@ @ }@i{rts-native (default)}
26309 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26310 @item @code{@ @ @ @ }Exceptions @tab ZCX
26311 @*
26312 @item @b{x86-linux}
26313 @item @code{@ @ }@i{rts-native (default)}
26314 @item @code{@ @ @ @ }Tasking    @tab pthread library
26315 @item @code{@ @ @ @ }Exceptions @tab ZCX
26316 @*
26317 @item @code{@ @ }@i{rts-sjlj}
26318 @item @code{@ @ @ @ }Tasking    @tab pthread library
26319 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26320 @*
26321 @item @b{x86-lynx}
26322 @item @code{@ @ }@i{rts-native (default)}
26323 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26324 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26325 @*
26326 @item @b{x86-solaris}
26327 @item @code{@ @ }@i{rts-native (default)}
26328 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26329 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26330 @*
26331 @item @b{x86-windows}
26332 @item @code{@ @ }@i{rts-native (default)}
26333 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26334 @item @code{@ @ @ @ }Exceptions @tab ZCX
26335 @*
26336 @item @code{@ @ }@i{rts-sjlj (default)}
26337 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26338 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26339 @*
26340 @item @b{x86-windows-rtx}
26341 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26342 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26343 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26344 @*
26345 @item @code{@ @ }@i{rts-rtx-w32}
26346 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26347 @item @code{@ @ @ @ }Exceptions @tab ZCX
26348 @*
26349 @item @b{x86_64-linux}
26350 @item @code{@ @ }@i{rts-native (default)}
26351 @item @code{@ @ @ @ }Tasking    @tab pthread library
26352 @item @code{@ @ @ @ }Exceptions @tab ZCX
26353 @*
26354 @item @code{@ @ }@i{rts-sjlj}
26355 @item @code{@ @ @ @ }Tasking    @tab pthread library
26356 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26357 @*
26358 @end multitable
26359
26360 @node Specifying a Run-Time Library
26361 @section Specifying a Run-Time Library
26362
26363 @noindent
26364 The @file{adainclude} subdirectory containing the sources of the GNAT
26365 run-time library, and the @file{adalib} subdirectory containing the
26366 @file{ALI} files and the static and/or shared GNAT library, are located
26367 in the gcc target-dependent area:
26368
26369 @smallexample
26370 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26371 @end smallexample
26372
26373 @noindent
26374 As indicated above, on some platforms several run-time libraries are supplied.
26375 These libraries are installed in the target dependent area and
26376 contain a complete source and binary subdirectory. The detailed description
26377 below explains the differences between the different libraries in terms of
26378 their thread support.
26379
26380 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26381 This default run time is selected by the means of soft links.
26382 For example on x86-linux:
26383
26384 @smallexample
26385 @group
26386  $(target-dir)
26387      |
26388      +--- adainclude----------+
26389      |                        |
26390      +--- adalib-----------+  |
26391      |                     |  |
26392      +--- rts-native       |  |
26393      |    |                |  |
26394      |    +--- adainclude <---+
26395      |    |                |
26396      |    +--- adalib <----+
26397      |
26398      +--- rts-sjlj
26399           |
26400           +--- adainclude
26401           |
26402           +--- adalib
26403 @end group
26404 @end smallexample
26405
26406 @noindent
26407 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26408 these soft links can be modified with the following commands:
26409
26410 @smallexample
26411 $ cd $target
26412 $ rm -f adainclude adalib
26413 $ ln -s rts-sjlj/adainclude adainclude
26414 $ ln -s rts-sjlj/adalib adalib
26415 @end smallexample
26416
26417 @noindent
26418 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26419 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26420 @file{$target/ada_object_path}.
26421
26422 Selecting another run-time library temporarily can be
26423 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26424 @cindex @option{--RTS} option
26425
26426 @node Choosing the Scheduling Policy
26427 @section Choosing the Scheduling Policy
26428
26429 @noindent
26430 When using a POSIX threads implementation, you have a choice of several
26431 scheduling policies: @code{SCHED_FIFO},
26432 @cindex @code{SCHED_FIFO} scheduling policy
26433 @code{SCHED_RR}
26434 @cindex @code{SCHED_RR} scheduling policy
26435 and @code{SCHED_OTHER}.
26436 @cindex @code{SCHED_OTHER} scheduling policy
26437 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26438 or @code{SCHED_RR} requires special (e.g., root) privileges.
26439
26440 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26441 @code{SCHED_FIFO},
26442 @cindex @code{SCHED_FIFO} scheduling policy
26443 you can use one of the following:
26444
26445 @itemize @bullet
26446 @item
26447 @code{pragma Time_Slice (0.0)}
26448 @cindex pragma Time_Slice
26449 @item
26450 the corresponding binder option @option{-T0}
26451 @cindex @option{-T0} option
26452 @item
26453 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26454 @cindex pragma Task_Dispatching_Policy
26455 @end itemize
26456
26457 @noindent
26458 To specify @code{SCHED_RR},
26459 @cindex @code{SCHED_RR} scheduling policy
26460 you should use @code{pragma Time_Slice} with a
26461 value greater than @code{0.0}, or else use the corresponding @option{-T}
26462 binder option.
26463
26464 @node Solaris-Specific Considerations
26465 @section Solaris-Specific Considerations
26466 @cindex Solaris Sparc threads libraries
26467
26468 @noindent
26469 This section addresses some topics related to the various threads libraries
26470 on Sparc Solaris.
26471
26472 @menu
26473 * Solaris Threads Issues::
26474 @end menu
26475
26476 @node Solaris Threads Issues
26477 @subsection Solaris Threads Issues
26478
26479 @noindent
26480 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26481 library based on POSIX threads --- @emph{rts-pthread}.
26482 @cindex rts-pthread threads library
26483 This run-time library has the advantage of being mostly shared across all
26484 POSIX-compliant thread implementations, and it also provides under
26485 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26486 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26487 and @code{PTHREAD_PRIO_PROTECT}
26488 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26489 semantics that can be selected using the predefined pragma
26490 @code{Locking_Policy}
26491 @cindex pragma Locking_Policy (under rts-pthread)
26492 with respectively
26493 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26494 @cindex @code{Inheritance_Locking} (under rts-pthread)
26495 @cindex @code{Ceiling_Locking} (under rts-pthread)
26496
26497 As explained above, the native run-time library is based on the Solaris thread
26498 library (@code{libthread}) and is the default library.
26499
26500 When the Solaris threads library is used (this is the default), programs
26501 compiled with GNAT can automatically take advantage of
26502 and can thus execute on multiple processors.
26503 The user can alternatively specify a processor on which the program should run
26504 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26505 is made by
26506 setting the environment variable @env{GNAT_PROCESSOR}
26507 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26508 to one of the following:
26509
26510 @table @code
26511 @item -2
26512 Use the default configuration (run the program on all
26513 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26514 unset
26515
26516 @item -1
26517 Let the run-time implementation choose one processor and run the program on
26518 that processor
26519
26520 @item 0 .. Last_Proc
26521 Run the program on the specified processor.
26522 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26523 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26524 @end table
26525
26526 @node Linux-Specific Considerations
26527 @section Linux-Specific Considerations
26528 @cindex Linux threads libraries
26529
26530 @noindent
26531 On GNU/Linux without NPTL support (usually system with GNU C Library
26532 older than 2.3), the signal model is not POSIX compliant, which means
26533 that to send a signal to the process, you need to send the signal to all
26534 threads, e.g.@: by using @code{killpg()}.
26535
26536 @node AIX-Specific Considerations
26537 @section AIX-Specific Considerations
26538 @cindex AIX resolver library
26539
26540 @noindent
26541 On AIX, the resolver library initializes some internal structure on
26542 the first call to @code{get*by*} functions, which are used to implement
26543 @code{GNAT.Sockets.Get_Host_By_Name} and
26544 @code{GNAT.Sockets.Get_Host_By_Address}.
26545 If such initialization occurs within an Ada task, and the stack size for
26546 the task is the default size, a stack overflow may occur.
26547
26548 To avoid this overflow, the user should either ensure that the first call
26549 to @code{GNAT.Sockets.Get_Host_By_Name} or
26550 @code{GNAT.Sockets.Get_Host_By_Addrss}
26551 occurs in the environment task, or use @code{pragma Storage_Size} to
26552 specify a sufficiently large size for the stack of the task that contains
26553 this call.
26554
26555 @node Irix-Specific Considerations
26556 @section Irix-Specific Considerations
26557 @cindex Irix libraries
26558
26559 @noindent
26560 The GCC support libraries coming with the Irix compiler have moved to
26561 their canonical place with respect to the general Irix ABI related
26562 conventions. Running applications built with the default shared GNAT
26563 run-time now requires the LD_LIBRARY_PATH environment variable to
26564 include this location. A possible way to achieve this is to issue the
26565 following command line on a bash prompt:
26566
26567 @smallexample
26568 @group
26569 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26570 @end group
26571 @end smallexample
26572
26573 @node RTX-Specific Considerations
26574 @section RTX-Specific Considerations
26575 @cindex RTX libraries
26576
26577 @noindent
26578 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26579 API. Applications can be built to work in two different modes:
26580
26581 @itemize @bullet
26582 @item
26583 Windows executables that run in Ring 3 to utilize memory protection
26584 (@emph{rts-rtx-w32}).
26585
26586 @item
26587 Real-time subsystem (RTSS) executables that run in Ring 0, where
26588 performance can be optimized with RTSS applications taking precedent
26589 over all Windows applications (@emph{rts-rtx-rtss}).
26590
26591 @end itemize
26592
26593 @c *******************************
26594 @node Example of Binder Output File
26595 @appendix Example of Binder Output File
26596
26597 @noindent
26598 This Appendix displays the source code for @command{gnatbind}'s output
26599 file generated for a simple ``Hello World'' program.
26600 Comments have been added for clarification purposes.
26601
26602 @smallexample @c adanocomment
26603 @iftex
26604 @leftskip=0cm
26605 @end iftex
26606 --  The package is called Ada_Main unless this name is actually used
26607 --  as a unit name in the partition, in which case some other unique
26608 --  name is used.
26609
26610 with System;
26611 package ada_main is
26612
26613    Elab_Final_Code : Integer;
26614    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26615
26616    --  The main program saves the parameters (argument count,
26617    --  argument values, environment pointer) in global variables
26618    --  for later access by other units including
26619    --  Ada.Command_Line.
26620
26621    gnat_argc : Integer;
26622    gnat_argv : System.Address;
26623    gnat_envp : System.Address;
26624
26625    --  The actual variables are stored in a library routine. This
26626    --  is useful for some shared library situations, where there
26627    --  are problems if variables are not in the library.
26628
26629    pragma Import (C, gnat_argc);
26630    pragma Import (C, gnat_argv);
26631    pragma Import (C, gnat_envp);
26632
26633    --  The exit status is similarly an external location
26634
26635    gnat_exit_status : Integer;
26636    pragma Import (C, gnat_exit_status);
26637
26638    GNAT_Version : constant String :=
26639                     "GNAT Version: 6.0.0w (20061115)";
26640    pragma Export (C, GNAT_Version, "__gnat_version");
26641
26642    --  This is the generated adafinal routine that performs
26643    --  finalization at the end of execution. In the case where
26644    --  Ada is the main program, this main program makes a call
26645    --  to adafinal at program termination.
26646
26647    procedure adafinal;
26648    pragma Export (C, adafinal, "adafinal");
26649
26650    --  This is the generated adainit routine that performs
26651    --  initialization at the start of execution. In the case
26652    --  where Ada is the main program, this main program makes
26653    --  a call to adainit at program startup.
26654
26655    procedure adainit;
26656    pragma Export (C, adainit, "adainit");
26657
26658    --  This routine is called at the start of execution. It is
26659    --  a dummy routine that is used by the debugger to breakpoint
26660    --  at the start of execution.
26661
26662    procedure Break_Start;
26663    pragma Import (C, Break_Start, "__gnat_break_start");
26664
26665    --  This is the actual generated main program (it would be
26666    --  suppressed if the no main program switch were used). As
26667    --  required by standard system conventions, this program has
26668    --  the external name main.
26669
26670    function main
26671      (argc : Integer;
26672       argv : System.Address;
26673       envp : System.Address)
26674       return Integer;
26675    pragma Export (C, main, "main");
26676
26677    --  The following set of constants give the version
26678    --  identification values for every unit in the bound
26679    --  partition. This identification is computed from all
26680    --  dependent semantic units, and corresponds to the
26681    --  string that would be returned by use of the
26682    --  Body_Version or Version attributes.
26683
26684    type Version_32 is mod 2 ** 32;
26685    u00001 : constant Version_32 := 16#7880BEB3#;
26686    u00002 : constant Version_32 := 16#0D24CBD0#;
26687    u00003 : constant Version_32 := 16#3283DBEB#;
26688    u00004 : constant Version_32 := 16#2359F9ED#;
26689    u00005 : constant Version_32 := 16#664FB847#;
26690    u00006 : constant Version_32 := 16#68E803DF#;
26691    u00007 : constant Version_32 := 16#5572E604#;
26692    u00008 : constant Version_32 := 16#46B173D8#;
26693    u00009 : constant Version_32 := 16#156A40CF#;
26694    u00010 : constant Version_32 := 16#033DABE0#;
26695    u00011 : constant Version_32 := 16#6AB38FEA#;
26696    u00012 : constant Version_32 := 16#22B6217D#;
26697    u00013 : constant Version_32 := 16#68A22947#;
26698    u00014 : constant Version_32 := 16#18CC4A56#;
26699    u00015 : constant Version_32 := 16#08258E1B#;
26700    u00016 : constant Version_32 := 16#367D5222#;
26701    u00017 : constant Version_32 := 16#20C9ECA4#;
26702    u00018 : constant Version_32 := 16#50D32CB6#;
26703    u00019 : constant Version_32 := 16#39A8BB77#;
26704    u00020 : constant Version_32 := 16#5CF8FA2B#;
26705    u00021 : constant Version_32 := 16#2F1EB794#;
26706    u00022 : constant Version_32 := 16#31AB6444#;
26707    u00023 : constant Version_32 := 16#1574B6E9#;
26708    u00024 : constant Version_32 := 16#5109C189#;
26709    u00025 : constant Version_32 := 16#56D770CD#;
26710    u00026 : constant Version_32 := 16#02F9DE3D#;
26711    u00027 : constant Version_32 := 16#08AB6B2C#;
26712    u00028 : constant Version_32 := 16#3FA37670#;
26713    u00029 : constant Version_32 := 16#476457A0#;
26714    u00030 : constant Version_32 := 16#731E1B6E#;
26715    u00031 : constant Version_32 := 16#23C2E789#;
26716    u00032 : constant Version_32 := 16#0F1BD6A1#;
26717    u00033 : constant Version_32 := 16#7C25DE96#;
26718    u00034 : constant Version_32 := 16#39ADFFA2#;
26719    u00035 : constant Version_32 := 16#571DE3E7#;
26720    u00036 : constant Version_32 := 16#5EB646AB#;
26721    u00037 : constant Version_32 := 16#4249379B#;
26722    u00038 : constant Version_32 := 16#0357E00A#;
26723    u00039 : constant Version_32 := 16#3784FB72#;
26724    u00040 : constant Version_32 := 16#2E723019#;
26725    u00041 : constant Version_32 := 16#623358EA#;
26726    u00042 : constant Version_32 := 16#107F9465#;
26727    u00043 : constant Version_32 := 16#6843F68A#;
26728    u00044 : constant Version_32 := 16#63305874#;
26729    u00045 : constant Version_32 := 16#31E56CE1#;
26730    u00046 : constant Version_32 := 16#02917970#;
26731    u00047 : constant Version_32 := 16#6CCBA70E#;
26732    u00048 : constant Version_32 := 16#41CD4204#;
26733    u00049 : constant Version_32 := 16#572E3F58#;
26734    u00050 : constant Version_32 := 16#20729FF5#;
26735    u00051 : constant Version_32 := 16#1D4F93E8#;
26736    u00052 : constant Version_32 := 16#30B2EC3D#;
26737    u00053 : constant Version_32 := 16#34054F96#;
26738    u00054 : constant Version_32 := 16#5A199860#;
26739    u00055 : constant Version_32 := 16#0E7F912B#;
26740    u00056 : constant Version_32 := 16#5760634A#;
26741    u00057 : constant Version_32 := 16#5D851835#;
26742
26743    --  The following Export pragmas export the version numbers
26744    --  with symbolic names ending in B (for body) or S
26745    --  (for spec) so that they can be located in a link. The
26746    --  information provided here is sufficient to track down
26747    --  the exact versions of units used in a given build.
26748
26749    pragma Export (C, u00001, "helloB");
26750    pragma Export (C, u00002, "system__standard_libraryB");
26751    pragma Export (C, u00003, "system__standard_libraryS");
26752    pragma Export (C, u00004, "adaS");
26753    pragma Export (C, u00005, "ada__text_ioB");
26754    pragma Export (C, u00006, "ada__text_ioS");
26755    pragma Export (C, u00007, "ada__exceptionsB");
26756    pragma Export (C, u00008, "ada__exceptionsS");
26757    pragma Export (C, u00009, "gnatS");
26758    pragma Export (C, u00010, "gnat__heap_sort_aB");
26759    pragma Export (C, u00011, "gnat__heap_sort_aS");
26760    pragma Export (C, u00012, "systemS");
26761    pragma Export (C, u00013, "system__exception_tableB");
26762    pragma Export (C, u00014, "system__exception_tableS");
26763    pragma Export (C, u00015, "gnat__htableB");
26764    pragma Export (C, u00016, "gnat__htableS");
26765    pragma Export (C, u00017, "system__exceptionsS");
26766    pragma Export (C, u00018, "system__machine_state_operationsB");
26767    pragma Export (C, u00019, "system__machine_state_operationsS");
26768    pragma Export (C, u00020, "system__machine_codeS");
26769    pragma Export (C, u00021, "system__storage_elementsB");
26770    pragma Export (C, u00022, "system__storage_elementsS");
26771    pragma Export (C, u00023, "system__secondary_stackB");
26772    pragma Export (C, u00024, "system__secondary_stackS");
26773    pragma Export (C, u00025, "system__parametersB");
26774    pragma Export (C, u00026, "system__parametersS");
26775    pragma Export (C, u00027, "system__soft_linksB");
26776    pragma Export (C, u00028, "system__soft_linksS");
26777    pragma Export (C, u00029, "system__stack_checkingB");
26778    pragma Export (C, u00030, "system__stack_checkingS");
26779    pragma Export (C, u00031, "system__tracebackB");
26780    pragma Export (C, u00032, "system__tracebackS");
26781    pragma Export (C, u00033, "ada__streamsS");
26782    pragma Export (C, u00034, "ada__tagsB");
26783    pragma Export (C, u00035, "ada__tagsS");
26784    pragma Export (C, u00036, "system__string_opsB");
26785    pragma Export (C, u00037, "system__string_opsS");
26786    pragma Export (C, u00038, "interfacesS");
26787    pragma Export (C, u00039, "interfaces__c_streamsB");
26788    pragma Export (C, u00040, "interfaces__c_streamsS");
26789    pragma Export (C, u00041, "system__file_ioB");
26790    pragma Export (C, u00042, "system__file_ioS");
26791    pragma Export (C, u00043, "ada__finalizationB");
26792    pragma Export (C, u00044, "ada__finalizationS");
26793    pragma Export (C, u00045, "system__finalization_rootB");
26794    pragma Export (C, u00046, "system__finalization_rootS");
26795    pragma Export (C, u00047, "system__finalization_implementationB");
26796    pragma Export (C, u00048, "system__finalization_implementationS");
26797    pragma Export (C, u00049, "system__string_ops_concat_3B");
26798    pragma Export (C, u00050, "system__string_ops_concat_3S");
26799    pragma Export (C, u00051, "system__stream_attributesB");
26800    pragma Export (C, u00052, "system__stream_attributesS");
26801    pragma Export (C, u00053, "ada__io_exceptionsS");
26802    pragma Export (C, u00054, "system__unsigned_typesS");
26803    pragma Export (C, u00055, "system__file_control_blockS");
26804    pragma Export (C, u00056, "ada__finalization__list_controllerB");
26805    pragma Export (C, u00057, "ada__finalization__list_controllerS");
26806
26807    -- BEGIN ELABORATION ORDER
26808    -- ada (spec)
26809    -- gnat (spec)
26810    -- gnat.heap_sort_a (spec)
26811    -- gnat.heap_sort_a (body)
26812    -- gnat.htable (spec)
26813    -- gnat.htable (body)
26814    -- interfaces (spec)
26815    -- system (spec)
26816    -- system.machine_code (spec)
26817    -- system.parameters (spec)
26818    -- system.parameters (body)
26819    -- interfaces.c_streams (spec)
26820    -- interfaces.c_streams (body)
26821    -- system.standard_library (spec)
26822    -- ada.exceptions (spec)
26823    -- system.exception_table (spec)
26824    -- system.exception_table (body)
26825    -- ada.io_exceptions (spec)
26826    -- system.exceptions (spec)
26827    -- system.storage_elements (spec)
26828    -- system.storage_elements (body)
26829    -- system.machine_state_operations (spec)
26830    -- system.machine_state_operations (body)
26831    -- system.secondary_stack (spec)
26832    -- system.stack_checking (spec)
26833    -- system.soft_links (spec)
26834    -- system.soft_links (body)
26835    -- system.stack_checking (body)
26836    -- system.secondary_stack (body)
26837    -- system.standard_library (body)
26838    -- system.string_ops (spec)
26839    -- system.string_ops (body)
26840    -- ada.tags (spec)
26841    -- ada.tags (body)
26842    -- ada.streams (spec)
26843    -- system.finalization_root (spec)
26844    -- system.finalization_root (body)
26845    -- system.string_ops_concat_3 (spec)
26846    -- system.string_ops_concat_3 (body)
26847    -- system.traceback (spec)
26848    -- system.traceback (body)
26849    -- ada.exceptions (body)
26850    -- system.unsigned_types (spec)
26851    -- system.stream_attributes (spec)
26852    -- system.stream_attributes (body)
26853    -- system.finalization_implementation (spec)
26854    -- system.finalization_implementation (body)
26855    -- ada.finalization (spec)
26856    -- ada.finalization (body)
26857    -- ada.finalization.list_controller (spec)
26858    -- ada.finalization.list_controller (body)
26859    -- system.file_control_block (spec)
26860    -- system.file_io (spec)
26861    -- system.file_io (body)
26862    -- ada.text_io (spec)
26863    -- ada.text_io (body)
26864    -- hello (body)
26865    -- END ELABORATION ORDER
26866
26867 end ada_main;
26868
26869 --  The following source file name pragmas allow the generated file
26870 --  names to be unique for different main programs. They are needed
26871 --  since the package name will always be Ada_Main.
26872
26873 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26874 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26875
26876 --  Generated package body for Ada_Main starts here
26877
26878 package body ada_main is
26879
26880    --  The actual finalization is performed by calling the
26881    --  library routine in System.Standard_Library.Adafinal
26882
26883    procedure Do_Finalize;
26884    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26885
26886    -------------
26887    -- adainit --
26888    -------------
26889
26890 @findex adainit
26891    procedure adainit is
26892
26893       --  These booleans are set to True once the associated unit has
26894       --  been elaborated. It is also used to avoid elaborating the
26895       --  same unit twice.
26896
26897       E040 : Boolean;
26898       pragma Import (Ada, E040, "interfaces__c_streams_E");
26899
26900       E008 : Boolean;
26901       pragma Import (Ada, E008, "ada__exceptions_E");
26902
26903       E014 : Boolean;
26904       pragma Import (Ada, E014, "system__exception_table_E");
26905
26906       E053 : Boolean;
26907       pragma Import (Ada, E053, "ada__io_exceptions_E");
26908
26909       E017 : Boolean;
26910       pragma Import (Ada, E017, "system__exceptions_E");
26911
26912       E024 : Boolean;
26913       pragma Import (Ada, E024, "system__secondary_stack_E");
26914
26915       E030 : Boolean;
26916       pragma Import (Ada, E030, "system__stack_checking_E");
26917
26918       E028 : Boolean;
26919       pragma Import (Ada, E028, "system__soft_links_E");
26920
26921       E035 : Boolean;
26922       pragma Import (Ada, E035, "ada__tags_E");
26923
26924       E033 : Boolean;
26925       pragma Import (Ada, E033, "ada__streams_E");
26926
26927       E046 : Boolean;
26928       pragma Import (Ada, E046, "system__finalization_root_E");
26929
26930       E048 : Boolean;
26931       pragma Import (Ada, E048, "system__finalization_implementation_E");
26932
26933       E044 : Boolean;
26934       pragma Import (Ada, E044, "ada__finalization_E");
26935
26936       E057 : Boolean;
26937       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26938
26939       E055 : Boolean;
26940       pragma Import (Ada, E055, "system__file_control_block_E");
26941
26942       E042 : Boolean;
26943       pragma Import (Ada, E042, "system__file_io_E");
26944
26945       E006 : Boolean;
26946       pragma Import (Ada, E006, "ada__text_io_E");
26947
26948       --  Set_Globals is a library routine that stores away the
26949       --  value of the indicated set of global values in global
26950       --  variables within the library.
26951
26952       procedure Set_Globals
26953         (Main_Priority            : Integer;
26954          Time_Slice_Value         : Integer;
26955          WC_Encoding              : Character;
26956          Locking_Policy           : Character;
26957          Queuing_Policy           : Character;
26958          Task_Dispatching_Policy  : Character;
26959          Adafinal                 : System.Address;
26960          Unreserve_All_Interrupts : Integer;
26961          Exception_Tracebacks     : Integer);
26962 @findex __gnat_set_globals
26963       pragma Import (C, Set_Globals, "__gnat_set_globals");
26964
26965       --  SDP_Table_Build is a library routine used to build the
26966       --  exception tables. See unit Ada.Exceptions in files
26967       --  a-except.ads/adb for full details of how zero cost
26968       --  exception handling works. This procedure, the call to
26969       --  it, and the two following tables are all omitted if the
26970       --  build is in longjmp/setjmp exception mode.
26971
26972 @findex SDP_Table_Build
26973 @findex Zero Cost Exceptions
26974       procedure SDP_Table_Build
26975         (SDP_Addresses   : System.Address;
26976          SDP_Count       : Natural;
26977          Elab_Addresses  : System.Address;
26978          Elab_Addr_Count : Natural);
26979       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26980
26981       --  Table of Unit_Exception_Table addresses. Used for zero
26982       --  cost exception handling to build the top level table.
26983
26984       ST : aliased constant array (1 .. 23) of System.Address := (
26985         Hello'UET_Address,
26986         Ada.Text_Io'UET_Address,
26987         Ada.Exceptions'UET_Address,
26988         Gnat.Heap_Sort_A'UET_Address,
26989         System.Exception_Table'UET_Address,
26990         System.Machine_State_Operations'UET_Address,
26991         System.Secondary_Stack'UET_Address,
26992         System.Parameters'UET_Address,
26993         System.Soft_Links'UET_Address,
26994         System.Stack_Checking'UET_Address,
26995         System.Traceback'UET_Address,
26996         Ada.Streams'UET_Address,
26997         Ada.Tags'UET_Address,
26998         System.String_Ops'UET_Address,
26999         Interfaces.C_Streams'UET_Address,
27000         System.File_Io'UET_Address,
27001         Ada.Finalization'UET_Address,
27002         System.Finalization_Root'UET_Address,
27003         System.Finalization_Implementation'UET_Address,
27004         System.String_Ops_Concat_3'UET_Address,
27005         System.Stream_Attributes'UET_Address,
27006         System.File_Control_Block'UET_Address,
27007         Ada.Finalization.List_Controller'UET_Address);
27008
27009       --  Table of addresses of elaboration routines. Used for
27010       --  zero cost exception handling to make sure these
27011       --  addresses are included in the top level procedure
27012       --  address table.
27013
27014       EA : aliased constant array (1 .. 23) of System.Address := (
27015         adainit'Code_Address,
27016         Do_Finalize'Code_Address,
27017         Ada.Exceptions'Elab_Spec'Address,
27018         System.Exceptions'Elab_Spec'Address,
27019         Interfaces.C_Streams'Elab_Spec'Address,
27020         System.Exception_Table'Elab_Body'Address,
27021         Ada.Io_Exceptions'Elab_Spec'Address,
27022         System.Stack_Checking'Elab_Spec'Address,
27023         System.Soft_Links'Elab_Body'Address,
27024         System.Secondary_Stack'Elab_Body'Address,
27025         Ada.Tags'Elab_Spec'Address,
27026         Ada.Tags'Elab_Body'Address,
27027         Ada.Streams'Elab_Spec'Address,
27028         System.Finalization_Root'Elab_Spec'Address,
27029         Ada.Exceptions'Elab_Body'Address,
27030         System.Finalization_Implementation'Elab_Spec'Address,
27031         System.Finalization_Implementation'Elab_Body'Address,
27032         Ada.Finalization'Elab_Spec'Address,
27033         Ada.Finalization.List_Controller'Elab_Spec'Address,
27034         System.File_Control_Block'Elab_Spec'Address,
27035         System.File_Io'Elab_Body'Address,
27036         Ada.Text_Io'Elab_Spec'Address,
27037         Ada.Text_Io'Elab_Body'Address);
27038
27039    --  Start of processing for adainit
27040
27041    begin
27042
27043       --  Call SDP_Table_Build to build the top level procedure
27044       --  table for zero cost exception handling (omitted in
27045       --  longjmp/setjmp mode).
27046
27047       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27048
27049       --  Call Set_Globals to record various information for
27050       --  this partition.  The values are derived by the binder
27051       --  from information stored in the ali files by the compiler.
27052
27053 @findex __gnat_set_globals
27054       Set_Globals
27055         (Main_Priority            => -1,
27056          --  Priority of main program, -1 if no pragma Priority used
27057
27058          Time_Slice_Value         => -1,
27059          --  Time slice from Time_Slice pragma, -1 if none used
27060
27061          WC_Encoding              => 'b',
27062          --  Wide_Character encoding used, default is brackets
27063
27064          Locking_Policy           => ' ',
27065          --  Locking_Policy used, default of space means not
27066          --  specified, otherwise it is the first character of
27067          --  the policy name.
27068
27069          Queuing_Policy           => ' ',
27070          --  Queuing_Policy used, default of space means not
27071          --  specified, otherwise it is the first character of
27072          --  the policy name.
27073
27074          Task_Dispatching_Policy  => ' ',
27075          --  Task_Dispatching_Policy used, default of space means
27076          --  not specified, otherwise first character of the
27077          --  policy name.
27078
27079          Adafinal                 => System.Null_Address,
27080          --  Address of Adafinal routine, not used anymore
27081
27082          Unreserve_All_Interrupts => 0,
27083          --  Set true if pragma Unreserve_All_Interrupts was used
27084
27085          Exception_Tracebacks     => 0);
27086          --  Indicates if exception tracebacks are enabled
27087
27088       Elab_Final_Code := 1;
27089
27090       --  Now we have the elaboration calls for all units in the partition.
27091       --  The Elab_Spec and Elab_Body attributes generate references to the
27092       --  implicit elaboration procedures generated by the compiler for
27093       --  each unit that requires elaboration.
27094
27095       if not E040 then
27096          Interfaces.C_Streams'Elab_Spec;
27097       end if;
27098       E040 := True;
27099       if not E008 then
27100          Ada.Exceptions'Elab_Spec;
27101       end if;
27102       if not E014 then
27103          System.Exception_Table'Elab_Body;
27104          E014 := True;
27105       end if;
27106       if not E053 then
27107          Ada.Io_Exceptions'Elab_Spec;
27108          E053 := True;
27109       end if;
27110       if not E017 then
27111          System.Exceptions'Elab_Spec;
27112          E017 := True;
27113       end if;
27114       if not E030 then
27115          System.Stack_Checking'Elab_Spec;
27116       end if;
27117       if not E028 then
27118          System.Soft_Links'Elab_Body;
27119          E028 := True;
27120       end if;
27121       E030 := True;
27122       if not E024 then
27123          System.Secondary_Stack'Elab_Body;
27124          E024 := True;
27125       end if;
27126       if not E035 then
27127          Ada.Tags'Elab_Spec;
27128       end if;
27129       if not E035 then
27130          Ada.Tags'Elab_Body;
27131          E035 := True;
27132       end if;
27133       if not E033 then
27134          Ada.Streams'Elab_Spec;
27135          E033 := True;
27136       end if;
27137       if not E046 then
27138          System.Finalization_Root'Elab_Spec;
27139       end if;
27140       E046 := True;
27141       if not E008 then
27142          Ada.Exceptions'Elab_Body;
27143          E008 := True;
27144       end if;
27145       if not E048 then
27146          System.Finalization_Implementation'Elab_Spec;
27147       end if;
27148       if not E048 then
27149          System.Finalization_Implementation'Elab_Body;
27150          E048 := True;
27151       end if;
27152       if not E044 then
27153          Ada.Finalization'Elab_Spec;
27154       end if;
27155       E044 := True;
27156       if not E057 then
27157          Ada.Finalization.List_Controller'Elab_Spec;
27158       end if;
27159       E057 := True;
27160       if not E055 then
27161          System.File_Control_Block'Elab_Spec;
27162          E055 := True;
27163       end if;
27164       if not E042 then
27165          System.File_Io'Elab_Body;
27166          E042 := True;
27167       end if;
27168       if not E006 then
27169          Ada.Text_Io'Elab_Spec;
27170       end if;
27171       if not E006 then
27172          Ada.Text_Io'Elab_Body;
27173          E006 := True;
27174       end if;
27175
27176       Elab_Final_Code := 0;
27177    end adainit;
27178
27179    --------------
27180    -- adafinal --
27181    --------------
27182
27183 @findex adafinal
27184    procedure adafinal is
27185    begin
27186       Do_Finalize;
27187    end adafinal;
27188
27189    ----------
27190    -- main --
27191    ----------
27192
27193    --  main is actually a function, as in the ANSI C standard,
27194    --  defined to return the exit status. The three parameters
27195    --  are the argument count, argument values and environment
27196    --  pointer.
27197
27198 @findex Main Program
27199    function main
27200      (argc : Integer;
27201       argv : System.Address;
27202       envp : System.Address)
27203       return Integer
27204    is
27205       --  The initialize routine performs low level system
27206       --  initialization using a standard library routine which
27207       --  sets up signal handling and performs any other
27208       --  required setup. The routine can be found in file
27209       --  a-init.c.
27210
27211 @findex __gnat_initialize
27212       procedure initialize;
27213       pragma Import (C, initialize, "__gnat_initialize");
27214
27215       --  The finalize routine performs low level system
27216       --  finalization using a standard library routine. The
27217       --  routine is found in file a-final.c and in the standard
27218       --  distribution is a dummy routine that does nothing, so
27219       --  really this is a hook for special user finalization.
27220
27221 @findex __gnat_finalize
27222       procedure finalize;
27223       pragma Import (C, finalize, "__gnat_finalize");
27224
27225       --  We get to the main program of the partition by using
27226       --  pragma Import because if we try to with the unit and
27227       --  call it Ada style, then not only do we waste time
27228       --  recompiling it, but also, we don't really know the right
27229       --  switches (e.g.@: identifier character set) to be used
27230       --  to compile it.
27231
27232       procedure Ada_Main_Program;
27233       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27234
27235    --  Start of processing for main
27236
27237    begin
27238       --  Save global variables
27239
27240       gnat_argc := argc;
27241       gnat_argv := argv;
27242       gnat_envp := envp;
27243
27244       --  Call low level system initialization
27245
27246       Initialize;
27247
27248       --  Call our generated Ada initialization routine
27249
27250       adainit;
27251
27252       --  This is the point at which we want the debugger to get
27253       --  control
27254
27255       Break_Start;
27256
27257       --  Now we call the main program of the partition
27258
27259       Ada_Main_Program;
27260
27261       --  Perform Ada finalization
27262
27263       adafinal;
27264
27265       --  Perform low level system finalization
27266
27267       Finalize;
27268
27269       --  Return the proper exit status
27270       return (gnat_exit_status);
27271    end;
27272
27273 --  This section is entirely comments, so it has no effect on the
27274 --  compilation of the Ada_Main package. It provides the list of
27275 --  object files and linker options, as well as some standard
27276 --  libraries needed for the link. The gnatlink utility parses
27277 --  this b~hello.adb file to read these comment lines to generate
27278 --  the appropriate command line arguments for the call to the
27279 --  system linker. The BEGIN/END lines are used for sentinels for
27280 --  this parsing operation.
27281
27282 --  The exact file names will of course depend on the environment,
27283 --  host/target and location of files on the host system.
27284
27285 @findex Object file list
27286 -- BEGIN Object file/option list
27287    --   ./hello.o
27288    --   -L./
27289    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27290    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27291 -- END Object file/option list
27292
27293 end ada_main;
27294 @end smallexample
27295
27296 @noindent
27297 The Ada code in the above example is exactly what is generated by the
27298 binder. We have added comments to more clearly indicate the function
27299 of each part of the generated @code{Ada_Main} package.
27300
27301 The code is standard Ada in all respects, and can be processed by any
27302 tools that handle Ada. In particular, it is possible to use the debugger
27303 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27304 suppose that for reasons that you do not understand, your program is crashing
27305 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27306 you can place a breakpoint on the call:
27307
27308 @smallexample @c ada
27309 Ada.Text_Io'Elab_Body;
27310 @end smallexample
27311
27312 @noindent
27313 and trace the elaboration routine for this package to find out where
27314 the problem might be (more usually of course you would be debugging
27315 elaboration code in your own application).
27316
27317 @node Elaboration Order Handling in GNAT
27318 @appendix Elaboration Order Handling in GNAT
27319 @cindex Order of elaboration
27320 @cindex Elaboration control
27321
27322 @menu
27323 * Elaboration Code::
27324 * Checking the Elaboration Order::
27325 * Controlling the Elaboration Order::
27326 * Controlling Elaboration in GNAT - Internal Calls::
27327 * Controlling Elaboration in GNAT - External Calls::
27328 * Default Behavior in GNAT - Ensuring Safety::
27329 * Treatment of Pragma Elaborate::
27330 * Elaboration Issues for Library Tasks::
27331 * Mixing Elaboration Models::
27332 * What to Do If the Default Elaboration Behavior Fails::
27333 * Elaboration for Access-to-Subprogram Values::
27334 * Summary of Procedures for Elaboration Control::
27335 * Other Elaboration Order Considerations::
27336 @end menu
27337
27338 @noindent
27339 This chapter describes the handling of elaboration code in Ada and
27340 in GNAT, and discusses how the order of elaboration of program units can
27341 be controlled in GNAT, either automatically or with explicit programming
27342 features.
27343
27344 @node Elaboration Code
27345 @section Elaboration Code
27346
27347 @noindent
27348 Ada provides rather general mechanisms for executing code at elaboration
27349 time, that is to say before the main program starts executing. Such code arises
27350 in three contexts:
27351
27352 @table @asis
27353 @item Initializers for variables.
27354 Variables declared at the library level, in package specs or bodies, can
27355 require initialization that is performed at elaboration time, as in:
27356 @smallexample @c ada
27357 @cartouche
27358 Sqrt_Half : Float := Sqrt (0.5);
27359 @end cartouche
27360 @end smallexample
27361
27362 @item Package initialization code
27363 Code in a @code{BEGIN-END} section at the outer level of a package body is
27364 executed as part of the package body elaboration code.
27365
27366 @item Library level task allocators
27367 Tasks that are declared using task allocators at the library level
27368 start executing immediately and hence can execute at elaboration time.
27369 @end table
27370
27371 @noindent
27372 Subprogram calls are possible in any of these contexts, which means that
27373 any arbitrary part of the program may be executed as part of the elaboration
27374 code. It is even possible to write a program which does all its work at
27375 elaboration time, with a null main program, although stylistically this
27376 would usually be considered an inappropriate way to structure
27377 a program.
27378
27379 An important concern arises in the context of elaboration code:
27380 we have to be sure that it is executed in an appropriate order. What we
27381 have is a series of elaboration code sections, potentially one section
27382 for each unit in the program. It is important that these execute
27383 in the correct order. Correctness here means that, taking the above
27384 example of the declaration of @code{Sqrt_Half},
27385 if some other piece of
27386 elaboration code references @code{Sqrt_Half},
27387 then it must run after the
27388 section of elaboration code that contains the declaration of
27389 @code{Sqrt_Half}.
27390
27391 There would never be any order of elaboration problem if we made a rule
27392 that whenever you @code{with} a unit, you must elaborate both the spec and body
27393 of that unit before elaborating the unit doing the @code{with}'ing:
27394
27395 @smallexample @c ada
27396 @group
27397 @cartouche
27398 with Unit_1;
27399 package Unit_2 is @dots{}
27400 @end cartouche
27401 @end group
27402 @end smallexample
27403
27404 @noindent
27405 would require that both the body and spec of @code{Unit_1} be elaborated
27406 before the spec of @code{Unit_2}. However, a rule like that would be far too
27407 restrictive. In particular, it would make it impossible to have routines
27408 in separate packages that were mutually recursive.
27409
27410 You might think that a clever enough compiler could look at the actual
27411 elaboration code and determine an appropriate correct order of elaboration,
27412 but in the general case, this is not possible. Consider the following
27413 example.
27414
27415 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27416 that references
27417 the variable @code{Sqrt_1}, which is declared in the elaboration code
27418 of the body of @code{Unit_1}:
27419
27420 @smallexample @c ada
27421 @cartouche
27422 Sqrt_1 : Float := Sqrt (0.1);
27423 @end cartouche
27424 @end smallexample
27425
27426 @noindent
27427 The elaboration code of the body of @code{Unit_1} also contains:
27428
27429 @smallexample @c ada
27430 @group
27431 @cartouche
27432 if expression_1 = 1 then
27433    Q := Unit_2.Func_2;
27434 end if;
27435 @end cartouche
27436 @end group
27437 @end smallexample
27438
27439 @noindent
27440 @code{Unit_2} is exactly parallel,
27441 it has a procedure @code{Func_2} that references
27442 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27443 the body @code{Unit_2}:
27444
27445 @smallexample @c ada
27446 @cartouche
27447 Sqrt_2 : Float := Sqrt (0.1);
27448 @end cartouche
27449 @end smallexample
27450
27451 @noindent
27452 The elaboration code of the body of @code{Unit_2} also contains:
27453
27454 @smallexample @c ada
27455 @group
27456 @cartouche
27457 if expression_2 = 2 then
27458    Q := Unit_1.Func_1;
27459 end if;
27460 @end cartouche
27461 @end group
27462 @end smallexample
27463
27464 @noindent
27465 Now the question is, which of the following orders of elaboration is
27466 acceptable:
27467
27468 @smallexample
27469 @group
27470 Spec of Unit_1
27471 Spec of Unit_2
27472 Body of Unit_1
27473 Body of Unit_2
27474 @end group
27475 @end smallexample
27476
27477 @noindent
27478 or
27479
27480 @smallexample
27481 @group
27482 Spec of Unit_2
27483 Spec of Unit_1
27484 Body of Unit_2
27485 Body of Unit_1
27486 @end group
27487 @end smallexample
27488
27489 @noindent
27490 If you carefully analyze the flow here, you will see that you cannot tell
27491 at compile time the answer to this question.
27492 If @code{expression_1} is not equal to 1,
27493 and @code{expression_2} is not equal to 2,
27494 then either order is acceptable, because neither of the function calls is
27495 executed. If both tests evaluate to true, then neither order is acceptable
27496 and in fact there is no correct order.
27497
27498 If one of the two expressions is true, and the other is false, then one
27499 of the above orders is correct, and the other is incorrect. For example,
27500 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27501 then the call to @code{Func_1}
27502 will occur, but not the call to @code{Func_2.}
27503 This means that it is essential
27504 to elaborate the body of @code{Unit_1} before
27505 the body of @code{Unit_2}, so the first
27506 order of elaboration is correct and the second is wrong.
27507
27508 By making @code{expression_1} and @code{expression_2}
27509 depend on input data, or perhaps
27510 the time of day, we can make it impossible for the compiler or binder
27511 to figure out which of these expressions will be true, and hence it
27512 is impossible to guarantee a safe order of elaboration at run time.
27513
27514 @node Checking the Elaboration Order
27515 @section Checking the Elaboration Order
27516
27517 @noindent
27518 In some languages that involve the same kind of elaboration problems,
27519 e.g.@: Java and C++, the programmer is expected to worry about these
27520 ordering problems himself, and it is common to
27521 write a program in which an incorrect elaboration order  gives
27522 surprising results, because it references variables before they
27523 are initialized.
27524 Ada is designed to be a safe language, and a programmer-beware approach is
27525 clearly not sufficient. Consequently, the language provides three lines
27526 of defense:
27527
27528 @table @asis
27529 @item Standard rules
27530 Some standard rules restrict the possible choice of elaboration
27531 order. In particular, if you @code{with} a unit, then its spec is always
27532 elaborated before the unit doing the @code{with}. Similarly, a parent
27533 spec is always elaborated before the child spec, and finally
27534 a spec is always elaborated before its corresponding body.
27535
27536 @item Dynamic elaboration checks
27537 @cindex Elaboration checks
27538 @cindex Checks, elaboration
27539 Dynamic checks are made at run time, so that if some entity is accessed
27540 before it is elaborated (typically  by means of a subprogram call)
27541 then the exception (@code{Program_Error}) is raised.
27542
27543 @item Elaboration control
27544 Facilities are provided for the programmer to specify the desired order
27545 of elaboration.
27546 @end table
27547
27548 Let's look at these facilities in more detail. First, the rules for
27549 dynamic checking. One possible rule would be simply to say that the
27550 exception is raised if you access a variable which has not yet been
27551 elaborated. The trouble with this approach is that it could require
27552 expensive checks on every variable reference. Instead Ada has two
27553 rules which are a little more restrictive, but easier to check, and
27554 easier to state:
27555
27556 @table @asis
27557 @item Restrictions on calls
27558 A subprogram can only be called at elaboration time if its body
27559 has been elaborated. The rules for elaboration given above guarantee
27560 that the spec of the subprogram has been elaborated before the
27561 call, but not the body. If this rule is violated, then the
27562 exception @code{Program_Error} is raised.
27563
27564 @item Restrictions on instantiations
27565 A generic unit can only be instantiated if the body of the generic
27566 unit has been elaborated. Again, the rules for elaboration given above
27567 guarantee that the spec of the generic unit has been elaborated
27568 before the instantiation, but not the body. If this rule is
27569 violated, then the exception @code{Program_Error} is raised.
27570 @end table
27571
27572 @noindent
27573 The idea is that if the body has been elaborated, then any variables
27574 it references must have been elaborated; by checking for the body being
27575 elaborated we guarantee that none of its references causes any
27576 trouble. As we noted above, this is a little too restrictive, because a
27577 subprogram that has no non-local references in its body may in fact be safe
27578 to call. However, it really would be unsafe to rely on this, because
27579 it would mean that the caller was aware of details of the implementation
27580 in the body. This goes against the basic tenets of Ada.
27581
27582 A plausible implementation can be described as follows.
27583 A Boolean variable is associated with each subprogram
27584 and each generic unit. This variable is initialized to False, and is set to
27585 True at the point body is elaborated. Every call or instantiation checks the
27586 variable, and raises @code{Program_Error} if the variable is False.
27587
27588 Note that one might think that it would be good enough to have one Boolean
27589 variable for each package, but that would not deal with cases of trying
27590 to call a body in the same package as the call
27591 that has not been elaborated yet.
27592 Of course a compiler may be able to do enough analysis to optimize away
27593 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27594 does such optimizations, but still the easiest conceptual model is to
27595 think of there being one variable per subprogram.
27596
27597 @node Controlling the Elaboration Order
27598 @section Controlling the Elaboration Order
27599
27600 @noindent
27601 In the previous section we discussed the rules in Ada which ensure
27602 that @code{Program_Error} is raised if an incorrect elaboration order is
27603 chosen. This prevents erroneous executions, but we need mechanisms to
27604 specify a correct execution and avoid the exception altogether.
27605 To achieve this, Ada provides a number of features for controlling
27606 the order of elaboration. We discuss these features in this section.
27607
27608 First, there are several ways of indicating to the compiler that a given
27609 unit has no elaboration problems:
27610
27611 @table @asis
27612 @item packages that do not require a body
27613 A library package that does not require a body does not permit
27614 a body (this rule was introduced in Ada 95).
27615 Thus if we have a such a package, as in:
27616
27617 @smallexample @c ada
27618 @group
27619 @cartouche
27620 package Definitions is
27621    generic
27622       type m is new integer;
27623    package Subp is
27624       type a is array (1 .. 10) of m;
27625       type b is array (1 .. 20) of m;
27626    end Subp;
27627 end Definitions;
27628 @end cartouche
27629 @end group
27630 @end smallexample
27631
27632 @noindent
27633 A package that @code{with}'s @code{Definitions} may safely instantiate
27634 @code{Definitions.Subp} because the compiler can determine that there
27635 definitely is no package body to worry about in this case
27636
27637 @item pragma Pure
27638 @cindex pragma Pure
27639 @findex Pure
27640 Places sufficient restrictions on a unit to guarantee that
27641 no call to any subprogram in the unit can result in an
27642 elaboration problem. This means that the compiler does not need
27643 to worry about the point of elaboration of such units, and in
27644 particular, does not need to check any calls to any subprograms
27645 in this unit.
27646
27647 @item pragma Preelaborate
27648 @findex Preelaborate
27649 @cindex pragma Preelaborate
27650 This pragma places slightly less stringent restrictions on a unit than
27651 does pragma Pure,
27652 but these restrictions are still sufficient to ensure that there
27653 are no elaboration problems with any calls to the unit.
27654
27655 @item pragma Elaborate_Body
27656 @findex Elaborate_Body
27657 @cindex pragma Elaborate_Body
27658 This pragma requires that the body of a unit be elaborated immediately
27659 after its spec. Suppose a unit @code{A} has such a pragma,
27660 and unit @code{B} does
27661 a @code{with} of unit @code{A}. Recall that the standard rules require
27662 the spec of unit @code{A}
27663 to be elaborated before the @code{with}'ing unit; given the pragma in
27664 @code{A}, we also know that the body of @code{A}
27665 will be elaborated before @code{B}, so
27666 that calls to @code{A} are safe and do not need a check.
27667 @end table
27668
27669 @noindent
27670 Note that,
27671 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27672 the use of
27673 @code{Elaborate_Body} does not guarantee that the program is
27674 free of elaboration problems, because it may not be possible
27675 to satisfy the requested elaboration order.
27676 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27677 If a programmer
27678 marks @code{Unit_1} as @code{Elaborate_Body},
27679 and not @code{Unit_2,} then the order of
27680 elaboration will be:
27681
27682 @smallexample
27683 @group
27684 Spec of Unit_2
27685 Spec of Unit_1
27686 Body of Unit_1
27687 Body of Unit_2
27688 @end group
27689 @end smallexample
27690
27691 @noindent
27692 Now that means that the call to @code{Func_1} in @code{Unit_2}
27693 need not be checked,
27694 it must be safe. But the call to @code{Func_2} in
27695 @code{Unit_1} may still fail if
27696 @code{Expression_1} is equal to 1,
27697 and the programmer must still take
27698 responsibility for this not being the case.
27699
27700 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27701 eliminated, except for calls entirely within a body, which are
27702 in any case fully under programmer control. However, using the pragma
27703 everywhere is not always possible.
27704 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27705 we marked both of them as having pragma @code{Elaborate_Body}, then
27706 clearly there would be no possible elaboration order.
27707
27708 The above pragmas allow a server to guarantee safe use by clients, and
27709 clearly this is the preferable approach. Consequently a good rule
27710 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27711 and if this is not possible,
27712 mark them as @code{Elaborate_Body} if possible.
27713 As we have seen, there are situations where neither of these
27714 three pragmas can be used.
27715 So we also provide methods for clients to control the
27716 order of elaboration of the servers on which they depend:
27717
27718 @table @asis
27719 @item pragma Elaborate (unit)
27720 @findex Elaborate
27721 @cindex pragma Elaborate
27722 This pragma is placed in the context clause, after a @code{with} clause,
27723 and it requires that the body of the named unit be elaborated before
27724 the unit in which the pragma occurs. The idea is to use this pragma
27725 if the current unit calls at elaboration time, directly or indirectly,
27726 some subprogram in the named unit.
27727
27728 @item pragma Elaborate_All (unit)
27729 @findex Elaborate_All
27730 @cindex pragma Elaborate_All
27731 This is a stronger version of the Elaborate pragma. Consider the
27732 following example:
27733
27734 @smallexample
27735 Unit A @code{with}'s unit B and calls B.Func in elab code
27736 Unit B @code{with}'s unit C, and B.Func calls C.Func
27737 @end smallexample
27738
27739 @noindent
27740 Now if we put a pragma @code{Elaborate (B)}
27741 in unit @code{A}, this ensures that the
27742 body of @code{B} is elaborated before the call, but not the
27743 body of @code{C}, so
27744 the call to @code{C.Func} could still cause @code{Program_Error} to
27745 be raised.
27746
27747 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27748 not only that the body of the named unit be elaborated before the
27749 unit doing the @code{with}, but also the bodies of all units that the
27750 named unit uses, following @code{with} links transitively. For example,
27751 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27752 then it requires
27753 not only that the body of @code{B} be elaborated before @code{A},
27754 but also the
27755 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27756 @end table
27757
27758 @noindent
27759 We are now in a position to give a usage rule in Ada for avoiding
27760 elaboration problems, at least if dynamic dispatching and access to
27761 subprogram values are not used. We will handle these cases separately
27762 later.
27763
27764 The rule is simple. If a unit has elaboration code that can directly or
27765 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27766 a generic package in a @code{with}'ed unit,
27767 then if the @code{with}'ed unit does not have
27768 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27769 a pragma @code{Elaborate_All}
27770 for the @code{with}'ed unit. By following this rule a client is
27771 assured that calls can be made without risk of an exception.
27772
27773 For generic subprogram instantiations, the rule can be relaxed to
27774 require only a pragma @code{Elaborate} since elaborating the body
27775 of a subprogram cannot cause any transitive elaboration (we are
27776 not calling the subprogram in this case, just elaborating its
27777 declaration).
27778
27779 If this rule is not followed, then a program may be in one of four
27780 states:
27781
27782 @table @asis
27783 @item No order exists
27784 No order of elaboration exists which follows the rules, taking into
27785 account any @code{Elaborate}, @code{Elaborate_All},
27786 or @code{Elaborate_Body} pragmas. In
27787 this case, an Ada compiler must diagnose the situation at bind
27788 time, and refuse to build an executable program.
27789
27790 @item One or more orders exist, all incorrect
27791 One or more acceptable elaboration orders exist, and all of them
27792 generate an elaboration order problem. In this case, the binder
27793 can build an executable program, but @code{Program_Error} will be raised
27794 when the program is run.
27795
27796 @item Several orders exist, some right, some incorrect
27797 One or more acceptable elaboration orders exists, and some of them
27798 work, and some do not. The programmer has not controlled
27799 the order of elaboration, so the binder may or may not pick one of
27800 the correct orders, and the program may or may not raise an
27801 exception when it is run. This is the worst case, because it means
27802 that the program may fail when moved to another compiler, or even
27803 another version of the same compiler.
27804
27805 @item One or more orders exists, all correct
27806 One ore more acceptable elaboration orders exist, and all of them
27807 work. In this case the program runs successfully. This state of
27808 affairs can be guaranteed by following the rule we gave above, but
27809 may be true even if the rule is not followed.
27810 @end table
27811
27812 @noindent
27813 Note that one additional advantage of following our rules on the use
27814 of @code{Elaborate} and @code{Elaborate_All}
27815 is that the program continues to stay in the ideal (all orders OK) state
27816 even if maintenance
27817 changes some bodies of some units. Conversely, if a program that does
27818 not follow this rule happens to be safe at some point, this state of affairs
27819 may deteriorate silently as a result of maintenance changes.
27820
27821 You may have noticed that the above discussion did not mention
27822 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27823 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27824 code in the body makes calls to some other unit, so it is still necessary
27825 to use @code{Elaborate_All} on such units.
27826
27827 @node Controlling Elaboration in GNAT - Internal Calls
27828 @section Controlling Elaboration in GNAT - Internal Calls
27829
27830 @noindent
27831 In the case of internal calls, i.e., calls within a single package, the
27832 programmer has full control over the order of elaboration, and it is up
27833 to the programmer to elaborate declarations in an appropriate order. For
27834 example writing:
27835
27836 @smallexample @c ada
27837 @group
27838 @cartouche
27839 function One return Float;
27840
27841 Q : Float := One;
27842
27843 function One return Float is
27844 begin
27845      return 1.0;
27846 end One;
27847 @end cartouche
27848 @end group
27849 @end smallexample
27850
27851 @noindent
27852 will obviously raise @code{Program_Error} at run time, because function
27853 One will be called before its body is elaborated. In this case GNAT will
27854 generate a warning that the call will raise @code{Program_Error}:
27855
27856 @smallexample
27857 @group
27858 @cartouche
27859  1. procedure y is
27860  2.    function One return Float;
27861  3.
27862  4.    Q : Float := One;
27863                     |
27864     >>> warning: cannot call "One" before body is elaborated
27865     >>> warning: Program_Error will be raised at run time
27866
27867  5.
27868  6.    function One return Float is
27869  7.    begin
27870  8.         return 1.0;
27871  9.    end One;
27872 10.
27873 11. begin
27874 12.    null;
27875 13. end;
27876 @end cartouche
27877 @end group
27878 @end smallexample
27879
27880 @noindent
27881 Note that in this particular case, it is likely that the call is safe, because
27882 the function @code{One} does not access any global variables.
27883 Nevertheless in Ada, we do not want the validity of the check to depend on
27884 the contents of the body (think about the separate compilation case), so this
27885 is still wrong, as we discussed in the previous sections.
27886
27887 The error is easily corrected by rearranging the declarations so that the
27888 body of @code{One} appears before the declaration containing the call
27889 (note that in Ada 95 and Ada 2005,
27890 declarations can appear in any order, so there is no restriction that
27891 would prevent this reordering, and if we write:
27892
27893 @smallexample @c ada
27894 @group
27895 @cartouche
27896 function One return Float;
27897
27898 function One return Float is
27899 begin
27900      return 1.0;
27901 end One;
27902
27903 Q : Float := One;
27904 @end cartouche
27905 @end group
27906 @end smallexample
27907
27908 @noindent
27909 then all is well, no warning is generated, and no
27910 @code{Program_Error} exception
27911 will be raised.
27912 Things are more complicated when a chain of subprograms is executed:
27913
27914 @smallexample @c ada
27915 @group
27916 @cartouche
27917 function A return Integer;
27918 function B return Integer;
27919 function C return Integer;
27920
27921 function B return Integer is begin return A; end;
27922 function C return Integer is begin return B; end;
27923
27924 X : Integer := C;
27925
27926 function A return Integer is begin return 1; end;
27927 @end cartouche
27928 @end group
27929 @end smallexample
27930
27931 @noindent
27932 Now the call to @code{C}
27933 at elaboration time in the declaration of @code{X} is correct, because
27934 the body of @code{C} is already elaborated,
27935 and the call to @code{B} within the body of
27936 @code{C} is correct, but the call
27937 to @code{A} within the body of @code{B} is incorrect, because the body
27938 of @code{A} has not been elaborated, so @code{Program_Error}
27939 will be raised on the call to @code{A}.
27940 In this case GNAT will generate a
27941 warning that @code{Program_Error} may be
27942 raised at the point of the call. Let's look at the warning:
27943
27944 @smallexample
27945 @group
27946 @cartouche
27947  1. procedure x is
27948  2.    function A return Integer;
27949  3.    function B return Integer;
27950  4.    function C return Integer;
27951  5.
27952  6.    function B return Integer is begin return A; end;
27953                                                     |
27954     >>> warning: call to "A" before body is elaborated may
27955                  raise Program_Error
27956     >>> warning: "B" called at line 7
27957     >>> warning: "C" called at line 9
27958
27959  7.    function C return Integer is begin return B; end;
27960  8.
27961  9.    X : Integer := C;
27962 10.
27963 11.    function A return Integer is begin return 1; end;
27964 12.
27965 13. begin
27966 14.    null;
27967 15. end;
27968 @end cartouche
27969 @end group
27970 @end smallexample
27971
27972 @noindent
27973 Note that the message here says ``may raise'', instead of the direct case,
27974 where the message says ``will be raised''. That's because whether
27975 @code{A} is
27976 actually called depends in general on run-time flow of control.
27977 For example, if the body of @code{B} said
27978
27979 @smallexample @c ada
27980 @group
27981 @cartouche
27982 function B return Integer is
27983 begin
27984    if some-condition-depending-on-input-data then
27985       return A;
27986    else
27987       return 1;
27988    end if;
27989 end B;
27990 @end cartouche
27991 @end group
27992 @end smallexample
27993
27994 @noindent
27995 then we could not know until run time whether the incorrect call to A would
27996 actually occur, so @code{Program_Error} might
27997 or might not be raised. It is possible for a compiler to
27998 do a better job of analyzing bodies, to
27999 determine whether or not @code{Program_Error}
28000 might be raised, but it certainly
28001 couldn't do a perfect job (that would require solving the halting problem
28002 and is provably impossible), and because this is a warning anyway, it does
28003 not seem worth the effort to do the analysis. Cases in which it
28004 would be relevant are rare.
28005
28006 In practice, warnings of either of the forms given
28007 above will usually correspond to
28008 real errors, and should be examined carefully and eliminated.
28009 In the rare case where a warning is bogus, it can be suppressed by any of
28010 the following methods:
28011
28012 @itemize @bullet
28013 @item
28014 Compile with the @option{-gnatws} switch set
28015
28016 @item
28017 Suppress @code{Elaboration_Check} for the called subprogram
28018
28019 @item
28020 Use pragma @code{Warnings_Off} to turn warnings off for the call
28021 @end itemize
28022
28023 @noindent
28024 For the internal elaboration check case,
28025 GNAT by default generates the
28026 necessary run-time checks to ensure
28027 that @code{Program_Error} is raised if any
28028 call fails an elaboration check. Of course this can only happen if a
28029 warning has been issued as described above. The use of pragma
28030 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28031 some of these checks, meaning that it may be possible (but is not
28032 guaranteed) for a program to be able to call a subprogram whose body
28033 is not yet elaborated, without raising a @code{Program_Error} exception.
28034
28035 @node Controlling Elaboration in GNAT - External Calls
28036 @section Controlling Elaboration in GNAT - External Calls
28037
28038 @noindent
28039 The previous section discussed the case in which the execution of a
28040 particular thread of elaboration code occurred entirely within a
28041 single unit. This is the easy case to handle, because a programmer
28042 has direct and total control over the order of elaboration, and
28043 furthermore, checks need only be generated in cases which are rare
28044 and which the compiler can easily detect.
28045 The situation is more complex when separate compilation is taken into account.
28046 Consider the following:
28047
28048 @smallexample @c ada
28049 @cartouche
28050 @group
28051 package Math is
28052    function Sqrt (Arg : Float) return Float;
28053 end Math;
28054
28055 package body Math is
28056    function Sqrt (Arg : Float) return Float is
28057    begin
28058          @dots{}
28059    end Sqrt;
28060 end Math;
28061 @end group
28062 @group
28063 with Math;
28064 package Stuff is
28065    X : Float := Math.Sqrt (0.5);
28066 end Stuff;
28067
28068 with Stuff;
28069 procedure Main is
28070 begin
28071    @dots{}
28072 end Main;
28073 @end group
28074 @end cartouche
28075 @end smallexample
28076
28077 @noindent
28078 where @code{Main} is the main program. When this program is executed, the
28079 elaboration code must first be executed, and one of the jobs of the
28080 binder is to determine the order in which the units of a program are
28081 to be elaborated. In this case we have four units: the spec and body
28082 of @code{Math},
28083 the spec of @code{Stuff} and the body of @code{Main}).
28084 In what order should the four separate sections of elaboration code
28085 be executed?
28086
28087 There are some restrictions in the order of elaboration that the binder
28088 can choose. In particular, if unit U has a @code{with}
28089 for a package @code{X}, then you
28090 are assured that the spec of @code{X}
28091 is elaborated before U , but you are
28092 not assured that the body of @code{X}
28093 is elaborated before U.
28094 This means that in the above case, the binder is allowed to choose the
28095 order:
28096
28097 @smallexample
28098 spec of Math
28099 spec of Stuff
28100 body of Math
28101 body of Main
28102 @end smallexample
28103
28104 @noindent
28105 but that's not good, because now the call to @code{Math.Sqrt}
28106 that happens during
28107 the elaboration of the @code{Stuff}
28108 spec happens before the body of @code{Math.Sqrt} is
28109 elaborated, and hence causes @code{Program_Error} exception to be raised.
28110 At first glance, one might say that the binder is misbehaving, because
28111 obviously you want to elaborate the body of something you @code{with}
28112 first, but
28113 that is not a general rule that can be followed in all cases. Consider
28114
28115 @smallexample @c ada
28116 @group
28117 @cartouche
28118 package X is @dots{}
28119
28120 package Y is @dots{}
28121
28122 with X;
28123 package body Y is @dots{}
28124
28125 with Y;
28126 package body X is @dots{}
28127 @end cartouche
28128 @end group
28129 @end smallexample
28130
28131 @noindent
28132 This is a common arrangement, and, apart from the order of elaboration
28133 problems that might arise in connection with elaboration code, this works fine.
28134 A rule that says that you must first elaborate the body of anything you
28135 @code{with} cannot work in this case:
28136 the body of @code{X} @code{with}'s @code{Y},
28137 which means you would have to
28138 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28139 which means
28140 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28141 loop that cannot be broken.
28142
28143 It is true that the binder can in many cases guess an order of elaboration
28144 that is unlikely to cause a @code{Program_Error}
28145 exception to be raised, and it tries to do so (in the
28146 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28147 by default
28148 elaborate the body of @code{Math} right after its spec, so all will be well).
28149
28150 However, a program that blindly relies on the binder to be helpful can
28151 get into trouble, as we discussed in the previous sections, so
28152 GNAT
28153 provides a number of facilities for assisting the programmer in
28154 developing programs that are robust with respect to elaboration order.
28155
28156 @node Default Behavior in GNAT - Ensuring Safety
28157 @section Default Behavior in GNAT - Ensuring Safety
28158
28159 @noindent
28160 The default behavior in GNAT ensures elaboration safety. In its
28161 default mode GNAT implements the
28162 rule we previously described as the right approach. Let's restate it:
28163
28164 @itemize
28165 @item
28166 @emph{If a unit has elaboration code that can directly or indirectly make a
28167 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28168 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28169 does not have pragma @code{Pure} or
28170 @code{Preelaborate}, then the client should have an
28171 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28172
28173 @emph{In the case of instantiating a generic subprogram, it is always
28174 sufficient to have only an @code{Elaborate} pragma for the
28175 @code{with}'ed unit.}
28176 @end itemize
28177
28178 @noindent
28179 By following this rule a client is assured that calls and instantiations
28180 can be made without risk of an exception.
28181
28182 In this mode GNAT traces all calls that are potentially made from
28183 elaboration code, and puts in any missing implicit @code{Elaborate}
28184 and @code{Elaborate_All} pragmas.
28185 The advantage of this approach is that no elaboration problems
28186 are possible if the binder can find an elaboration order that is
28187 consistent with these implicit @code{Elaborate} and
28188 @code{Elaborate_All} pragmas. The
28189 disadvantage of this approach is that no such order may exist.
28190
28191 If the binder does not generate any diagnostics, then it means that it has
28192 found an elaboration order that is guaranteed to be safe. However, the binder
28193 may still be relying on implicitly generated @code{Elaborate} and
28194 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28195 guaranteed.
28196
28197 If it is important to guarantee portability, then the compilations should
28198 use the
28199 @option{-gnatwl}
28200 (warn on elaboration problems) switch. This will cause warning messages
28201 to be generated indicating the missing @code{Elaborate} and
28202 @code{Elaborate_All} pragmas.
28203 Consider the following source program:
28204
28205 @smallexample @c ada
28206 @group
28207 @cartouche
28208 with k;
28209 package j is
28210   m : integer := k.r;
28211 end;
28212 @end cartouche
28213 @end group
28214 @end smallexample
28215
28216 @noindent
28217 where it is clear that there
28218 should be a pragma @code{Elaborate_All}
28219 for unit @code{k}. An implicit pragma will be generated, and it is
28220 likely that the binder will be able to honor it. However, if you want
28221 to port this program to some other Ada compiler than GNAT.
28222 it is safer to include the pragma explicitly in the source. If this
28223 unit is compiled with the
28224 @option{-gnatwl}
28225 switch, then the compiler outputs a warning:
28226
28227 @smallexample
28228 @group
28229 @cartouche
28230 1. with k;
28231 2. package j is
28232 3.   m : integer := k.r;
28233                      |
28234    >>> warning: call to "r" may raise Program_Error
28235    >>> warning: missing pragma Elaborate_All for "k"
28236
28237 4. end;
28238 @end cartouche
28239 @end group
28240 @end smallexample
28241
28242 @noindent
28243 and these warnings can be used as a guide for supplying manually
28244 the missing pragmas. It is usually a bad idea to use this warning
28245 option during development. That's because it will warn you when
28246 you need to put in a pragma, but cannot warn you when it is time
28247 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28248 unnecessary dependencies and even false circularities.
28249
28250 This default mode is more restrictive than the Ada Reference
28251 Manual, and it is possible to construct programs which will compile
28252 using the dynamic model described there, but will run into a
28253 circularity using the safer static model we have described.
28254
28255 Of course any Ada compiler must be able to operate in a mode
28256 consistent with the requirements of the Ada Reference Manual,
28257 and in particular must have the capability of implementing the
28258 standard dynamic model of elaboration with run-time checks.
28259
28260 In GNAT, this standard mode can be achieved either by the use of
28261 the @option{-gnatE} switch on the compiler (@command{gcc} or
28262 @command{gnatmake}) command, or by the use of the configuration pragma:
28263
28264 @smallexample @c ada
28265 pragma Elaboration_Checks (RM);
28266 @end smallexample
28267
28268 @noindent
28269 Either approach will cause the unit affected to be compiled using the
28270 standard dynamic run-time elaboration checks described in the Ada
28271 Reference Manual. The static model is generally preferable, since it
28272 is clearly safer to rely on compile and link time checks rather than
28273 run-time checks. However, in the case of legacy code, it may be
28274 difficult to meet the requirements of the static model. This
28275 issue is further discussed in
28276 @ref{What to Do If the Default Elaboration Behavior Fails}.
28277
28278 Note that the static model provides a strict subset of the allowed
28279 behavior and programs of the Ada Reference Manual, so if you do
28280 adhere to the static model and no circularities exist,
28281 then you are assured that your program will
28282 work using the dynamic model, providing that you remove any
28283 pragma Elaborate statements from the source.
28284
28285 @node Treatment of Pragma Elaborate
28286 @section Treatment of Pragma Elaborate
28287 @cindex Pragma Elaborate
28288
28289 @noindent
28290 The use of @code{pragma Elaborate}
28291 should generally be avoided in Ada 95 and Ada 2005 programs,
28292 since there is no guarantee that transitive calls
28293 will be properly handled. Indeed at one point, this pragma was placed
28294 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28295
28296 Now that's a bit restrictive. In practice, the case in which
28297 @code{pragma Elaborate} is useful is when the caller knows that there
28298 are no transitive calls, or that the called unit contains all necessary
28299 transitive @code{pragma Elaborate} statements, and legacy code often
28300 contains such uses.
28301
28302 Strictly speaking the static mode in GNAT should ignore such pragmas,
28303 since there is no assurance at compile time that the necessary safety
28304 conditions are met. In practice, this would cause GNAT to be incompatible
28305 with correctly written Ada 83 code that had all necessary
28306 @code{pragma Elaborate} statements in place. Consequently, we made the
28307 decision that GNAT in its default mode will believe that if it encounters
28308 a @code{pragma Elaborate} then the programmer knows what they are doing,
28309 and it will trust that no elaboration errors can occur.
28310
28311 The result of this decision is two-fold. First to be safe using the
28312 static mode, you should remove all @code{pragma Elaborate} statements.
28313 Second, when fixing circularities in existing code, you can selectively
28314 use @code{pragma Elaborate} statements to convince the static mode of
28315 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28316 statement.
28317
28318 When using the static mode with @option{-gnatwl}, any use of
28319 @code{pragma Elaborate} will generate a warning about possible
28320 problems.
28321
28322 @node Elaboration Issues for Library Tasks
28323 @section Elaboration Issues for Library Tasks
28324 @cindex Library tasks, elaboration issues
28325 @cindex Elaboration of library tasks
28326
28327 @noindent
28328 In this section we examine special elaboration issues that arise for
28329 programs that declare library level tasks.
28330
28331 Generally the model of execution of an Ada program is that all units are
28332 elaborated, and then execution of the program starts. However, the
28333 declaration of library tasks definitely does not fit this model. The
28334 reason for this is that library tasks start as soon as they are declared
28335 (more precisely, as soon as the statement part of the enclosing package
28336 body is reached), that is to say before elaboration
28337 of the program is complete. This means that if such a task calls a
28338 subprogram, or an entry in another task, the callee may or may not be
28339 elaborated yet, and in the standard
28340 Reference Manual model of dynamic elaboration checks, you can even
28341 get timing dependent Program_Error exceptions, since there can be
28342 a race between the elaboration code and the task code.
28343
28344 The static model of elaboration in GNAT seeks to avoid all such
28345 dynamic behavior, by being conservative, and the conservative
28346 approach in this particular case is to assume that all the code
28347 in a task body is potentially executed at elaboration time if
28348 a task is declared at the library level.
28349
28350 This can definitely result in unexpected circularities. Consider
28351 the following example
28352
28353 @smallexample @c ada
28354 package Decls is
28355   task Lib_Task is
28356      entry Start;
28357   end Lib_Task;
28358
28359   type My_Int is new Integer;
28360
28361   function Ident (M : My_Int) return My_Int;
28362 end Decls;
28363
28364 with Utils;
28365 package body Decls is
28366   task body Lib_Task is
28367   begin
28368      accept Start;
28369      Utils.Put_Val (2);
28370   end Lib_Task;
28371
28372   function Ident (M : My_Int) return My_Int is
28373   begin
28374      return M;
28375   end Ident;
28376 end Decls;
28377
28378 with Decls;
28379 package Utils is
28380   procedure Put_Val (Arg : Decls.My_Int);
28381 end Utils;
28382
28383 with Text_IO;
28384 package body Utils is
28385   procedure Put_Val (Arg : Decls.My_Int) is
28386   begin
28387      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28388   end Put_Val;
28389 end Utils;
28390
28391 with Decls;
28392 procedure Main is
28393 begin
28394    Decls.Lib_Task.Start;
28395 end;
28396 @end smallexample
28397
28398 @noindent
28399 If the above example is compiled in the default static elaboration
28400 mode, then a circularity occurs. The circularity comes from the call
28401 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28402 this call occurs in elaboration code, we need an implicit pragma
28403 @code{Elaborate_All} for @code{Utils}. This means that not only must
28404 the spec and body of @code{Utils} be elaborated before the body
28405 of @code{Decls}, but also the spec and body of any unit that is
28406 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28407 the body of @code{Decls}. This is the transitive implication of
28408 pragma @code{Elaborate_All} and it makes sense, because in general
28409 the body of @code{Put_Val} might have a call to something in a
28410 @code{with'ed} unit.
28411
28412 In this case, the body of Utils (actually its spec) @code{with's}
28413 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28414 must be elaborated before itself, in case there is a call from the
28415 body of @code{Utils}.
28416
28417 Here is the exact chain of events we are worrying about:
28418
28419 @enumerate
28420 @item
28421 In the body of @code{Decls} a call is made from within the body of a library
28422 task to a subprogram in the package @code{Utils}. Since this call may
28423 occur at elaboration time (given that the task is activated at elaboration
28424 time), we have to assume the worst, i.e., that the
28425 call does happen at elaboration time.
28426
28427 @item
28428 This means that the body and spec of @code{Util} must be elaborated before
28429 the body of @code{Decls} so that this call does not cause an access before
28430 elaboration.
28431
28432 @item
28433 Within the body of @code{Util}, specifically within the body of
28434 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28435 by this package.
28436
28437 @item
28438 One such @code{with}'ed package is package @code{Decls}, so there
28439 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28440 In fact there is such a call in this example, but we would have to
28441 assume that there was such a call even if it were not there, since
28442 we are not supposed to write the body of @code{Decls} knowing what
28443 is in the body of @code{Utils}; certainly in the case of the
28444 static elaboration model, the compiler does not know what is in
28445 other bodies and must assume the worst.
28446
28447 @item
28448 This means that the spec and body of @code{Decls} must also be
28449 elaborated before we elaborate the unit containing the call, but
28450 that unit is @code{Decls}! This means that the body of @code{Decls}
28451 must be elaborated before itself, and that's a circularity.
28452 @end enumerate
28453
28454 @noindent
28455 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28456 the body of @code{Decls} you will get a true Ada Reference Manual
28457 circularity that makes the program illegal.
28458
28459 In practice, we have found that problems with the static model of
28460 elaboration in existing code often arise from library tasks, so
28461 we must address this particular situation.
28462
28463 Note that if we compile and run the program above, using the dynamic model of
28464 elaboration (that is to say use the @option{-gnatE} switch),
28465 then it compiles, binds,
28466 links, and runs, printing the expected result of 2. Therefore in some sense
28467 the circularity here is only apparent, and we need to capture
28468 the properties of this program that  distinguish it from other library-level
28469 tasks that have real elaboration problems.
28470
28471 We have four possible answers to this question:
28472
28473 @itemize @bullet
28474
28475 @item
28476 Use the dynamic model of elaboration.
28477
28478 If we use the @option{-gnatE} switch, then as noted above, the program works.
28479 Why is this? If we examine the task body, it is apparent that the task cannot
28480 proceed past the
28481 @code{accept} statement until after elaboration has been completed, because
28482 the corresponding entry call comes from the main program, not earlier.
28483 This is why the dynamic model works here. But that's really giving
28484 up on a precise analysis, and we prefer to take this approach only if we cannot
28485 solve the
28486 problem in any other manner. So let us examine two ways to reorganize
28487 the program to avoid the potential elaboration problem.
28488
28489 @item
28490 Split library tasks into separate packages.
28491
28492 Write separate packages, so that library tasks are isolated from
28493 other declarations as much as possible. Let us look at a variation on
28494 the above program.
28495
28496 @smallexample @c ada
28497 package Decls1 is
28498   task Lib_Task is
28499      entry Start;
28500   end Lib_Task;
28501 end Decls1;
28502
28503 with Utils;
28504 package body Decls1 is
28505   task body Lib_Task is
28506   begin
28507      accept Start;
28508      Utils.Put_Val (2);
28509   end Lib_Task;
28510 end Decls1;
28511
28512 package Decls2 is
28513   type My_Int is new Integer;
28514   function Ident (M : My_Int) return My_Int;
28515 end Decls2;
28516
28517 with Utils;
28518 package body Decls2 is
28519   function Ident (M : My_Int) return My_Int is
28520   begin
28521      return M;
28522   end Ident;
28523 end Decls2;
28524
28525 with Decls2;
28526 package Utils is
28527   procedure Put_Val (Arg : Decls2.My_Int);
28528 end Utils;
28529
28530 with Text_IO;
28531 package body Utils is
28532   procedure Put_Val (Arg : Decls2.My_Int) is
28533   begin
28534      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28535   end Put_Val;
28536 end Utils;
28537
28538 with Decls1;
28539 procedure Main is
28540 begin
28541    Decls1.Lib_Task.Start;
28542 end;
28543 @end smallexample
28544
28545 @noindent
28546 All we have done is to split @code{Decls} into two packages, one
28547 containing the library task, and one containing everything else. Now
28548 there is no cycle, and the program compiles, binds, links and executes
28549 using the default static model of elaboration.
28550
28551 @item
28552 Declare separate task types.
28553
28554 A significant part of the problem arises because of the use of the
28555 single task declaration form. This means that the elaboration of
28556 the task type, and the elaboration of the task itself (i.e.@: the
28557 creation of the task) happen at the same time. A good rule
28558 of style in Ada is to always create explicit task types. By
28559 following the additional step of placing task objects in separate
28560 packages from the task type declaration, many elaboration problems
28561 are avoided. Here is another modified example of the example program:
28562
28563 @smallexample @c ada
28564 package Decls is
28565   task type Lib_Task_Type is
28566      entry Start;
28567   end Lib_Task_Type;
28568
28569   type My_Int is new Integer;
28570
28571   function Ident (M : My_Int) return My_Int;
28572 end Decls;
28573
28574 with Utils;
28575 package body Decls is
28576   task body Lib_Task_Type is
28577   begin
28578      accept Start;
28579      Utils.Put_Val (2);
28580   end Lib_Task_Type;
28581
28582   function Ident (M : My_Int) return My_Int is
28583   begin
28584      return M;
28585   end Ident;
28586 end Decls;
28587
28588 with Decls;
28589 package Utils is
28590   procedure Put_Val (Arg : Decls.My_Int);
28591 end Utils;
28592
28593 with Text_IO;
28594 package body Utils is
28595   procedure Put_Val (Arg : Decls.My_Int) is
28596   begin
28597      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28598   end Put_Val;
28599 end Utils;
28600
28601 with Decls;
28602 package Declst is
28603    Lib_Task : Decls.Lib_Task_Type;
28604 end Declst;
28605
28606 with Declst;
28607 procedure Main is
28608 begin
28609    Declst.Lib_Task.Start;
28610 end;
28611 @end smallexample
28612
28613 @noindent
28614 What we have done here is to replace the @code{task} declaration in
28615 package @code{Decls} with a @code{task type} declaration. Then we
28616 introduce a separate package @code{Declst} to contain the actual
28617 task object. This separates the elaboration issues for
28618 the @code{task type}
28619 declaration, which causes no trouble, from the elaboration issues
28620 of the task object, which is also unproblematic, since it is now independent
28621 of the elaboration of  @code{Utils}.
28622 This separation of concerns also corresponds to
28623 a generally sound engineering principle of separating declarations
28624 from instances. This version of the program also compiles, binds, links,
28625 and executes, generating the expected output.
28626
28627 @item
28628 Use No_Entry_Calls_In_Elaboration_Code restriction.
28629 @cindex No_Entry_Calls_In_Elaboration_Code
28630
28631 The previous two approaches described how a program can be restructured
28632 to avoid the special problems caused by library task bodies. in practice,
28633 however, such restructuring may be difficult to apply to existing legacy code,
28634 so we must consider solutions that do not require massive rewriting.
28635
28636 Let us consider more carefully why our original sample program works
28637 under the dynamic model of elaboration. The reason is that the code
28638 in the task body blocks immediately on the @code{accept}
28639 statement. Now of course there is nothing to prohibit elaboration
28640 code from making entry calls (for example from another library level task),
28641 so we cannot tell in isolation that
28642 the task will not execute the accept statement  during elaboration.
28643
28644 However, in practice it is very unusual to see elaboration code
28645 make any entry calls, and the pattern of tasks starting
28646 at elaboration time and then immediately blocking on @code{accept} or
28647 @code{select} statements is very common. What this means is that
28648 the compiler is being too pessimistic when it analyzes the
28649 whole package body as though it might be executed at elaboration
28650 time.
28651
28652 If we know that the elaboration code contains no entry calls, (a very safe
28653 assumption most of the time, that could almost be made the default
28654 behavior), then we can compile all units of the program under control
28655 of the following configuration pragma:
28656
28657 @smallexample
28658 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28659 @end smallexample
28660
28661 @noindent
28662 This pragma can be placed in the @file{gnat.adc} file in the usual
28663 manner. If we take our original unmodified program and compile it
28664 in the presence of a @file{gnat.adc} containing the above pragma,
28665 then once again, we can compile, bind, link, and execute, obtaining
28666 the expected result. In the presence of this pragma, the compiler does
28667 not trace calls in a task body, that appear after the first @code{accept}
28668 or @code{select} statement, and therefore does not report a potential
28669 circularity in the original program.
28670
28671 The compiler will check to the extent it can that the above
28672 restriction is not violated, but it is not always possible to do a
28673 complete check at compile time, so it is important to use this
28674 pragma only if the stated restriction is in fact met, that is to say
28675 no task receives an entry call before elaboration of all units is completed.
28676
28677 @end itemize
28678
28679 @node Mixing Elaboration Models
28680 @section Mixing Elaboration Models
28681 @noindent
28682 So far, we have assumed that the entire program is either compiled
28683 using the dynamic model or static model, ensuring consistency. It
28684 is possible to mix the two models, but rules have to be followed
28685 if this mixing is done to ensure that elaboration checks are not
28686 omitted.
28687
28688 The basic rule is that @emph{a unit compiled with the static model cannot
28689 be @code{with'ed} by a unit compiled with the dynamic model}. The
28690 reason for this is that in the static model, a unit assumes that
28691 its clients guarantee to use (the equivalent of) pragma
28692 @code{Elaborate_All} so that no elaboration checks are required
28693 in inner subprograms, and this assumption is violated if the
28694 client is compiled with dynamic checks.
28695
28696 The precise rule is as follows. A unit that is compiled with dynamic
28697 checks can only @code{with} a unit that meets at least one of the
28698 following criteria:
28699
28700 @itemize @bullet
28701
28702 @item
28703 The @code{with'ed} unit is itself compiled with dynamic elaboration
28704 checks (that is with the @option{-gnatE} switch.
28705
28706 @item
28707 The @code{with'ed} unit is an internal GNAT implementation unit from
28708 the System, Interfaces, Ada, or GNAT hierarchies.
28709
28710 @item
28711 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28712
28713 @item
28714 The @code{with'ing} unit (that is the client) has an explicit pragma
28715 @code{Elaborate_All} for the @code{with'ed} unit.
28716
28717 @end itemize
28718
28719 @noindent
28720 If this rule is violated, that is if a unit with dynamic elaboration
28721 checks @code{with's} a unit that does not meet one of the above four
28722 criteria, then the binder (@code{gnatbind}) will issue a warning
28723 similar to that in the following example:
28724
28725 @smallexample
28726 warning: "x.ads" has dynamic elaboration checks and with's
28727 warning:   "y.ads" which has static elaboration checks
28728 @end smallexample
28729
28730 @noindent
28731 These warnings indicate that the rule has been violated, and that as a result
28732 elaboration checks may be missed in the resulting executable file.
28733 This warning may be suppressed using the @option{-ws} binder switch
28734 in the usual manner.
28735
28736 One useful application of this mixing rule is in the case of a subsystem
28737 which does not itself @code{with} units from the remainder of the
28738 application. In this case, the entire subsystem can be compiled with
28739 dynamic checks to resolve a circularity in the subsystem, while
28740 allowing the main application that uses this subsystem to be compiled
28741 using the more reliable default static model.
28742
28743 @node What to Do If the Default Elaboration Behavior Fails
28744 @section What to Do If the Default Elaboration Behavior Fails
28745
28746 @noindent
28747 If the binder cannot find an acceptable order, it outputs detailed
28748 diagnostics. For example:
28749 @smallexample
28750 @group
28751 @iftex
28752 @leftskip=0cm
28753 @end iftex
28754 error: elaboration circularity detected
28755 info:   "proc (body)" must be elaborated before "pack (body)"
28756 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28757 info:     recompile "pack (body)" with -gnatwl
28758 info:                             for full details
28759 info:       "proc (body)"
28760 info:         is needed by its spec:
28761 info:       "proc (spec)"
28762 info:         which is withed by:
28763 info:       "pack (body)"
28764 info:  "pack (body)" must be elaborated before "proc (body)"
28765 info:     reason: pragma Elaborate in unit "proc (body)"
28766 @end group
28767
28768 @end smallexample
28769
28770 @noindent
28771 In this case we have a cycle that the binder cannot break. On the one
28772 hand, there is an explicit pragma Elaborate in @code{proc} for
28773 @code{pack}. This means that the body of @code{pack} must be elaborated
28774 before the body of @code{proc}. On the other hand, there is elaboration
28775 code in @code{pack} that calls a subprogram in @code{proc}. This means
28776 that for maximum safety, there should really be a pragma
28777 Elaborate_All in @code{pack} for @code{proc} which would require that
28778 the body of @code{proc} be elaborated before the body of
28779 @code{pack}. Clearly both requirements cannot be satisfied.
28780 Faced with a circularity of this kind, you have three different options.
28781
28782 @table @asis
28783 @item Fix the program
28784 The most desirable option from the point of view of long-term maintenance
28785 is to rearrange the program so that the elaboration problems are avoided.
28786 One useful technique is to place the elaboration code into separate
28787 child packages. Another is to move some of the initialization code to
28788 explicitly called subprograms, where the program controls the order
28789 of initialization explicitly. Although this is the most desirable option,
28790 it may be impractical and involve too much modification, especially in
28791 the case of complex legacy code.
28792
28793 @item Perform dynamic checks
28794 If the compilations are done using the
28795 @option{-gnatE}
28796 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28797 manner. Dynamic checks are generated for all calls that could possibly result
28798 in raising an exception. With this switch, the compiler does not generate
28799 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28800 exactly as specified in the @cite{Ada Reference Manual}.
28801 The binder will generate
28802 an executable program that may or may not raise @code{Program_Error}, and then
28803 it is the programmer's job to ensure that it does not raise an exception. Note
28804 that it is important to compile all units with the switch, it cannot be used
28805 selectively.
28806
28807 @item Suppress checks
28808 The drawback of dynamic checks is that they generate a
28809 significant overhead at run time, both in space and time. If you
28810 are absolutely sure that your program cannot raise any elaboration
28811 exceptions, and you still want to use the dynamic elaboration model,
28812 then you can use the configuration pragma
28813 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28814 example this pragma could be placed in the @file{gnat.adc} file.
28815
28816 @item Suppress checks selectively
28817 When you know that certain calls or instantiations in elaboration code cannot
28818 possibly lead to an elaboration error, and the binder nevertheless complains
28819 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28820 elaboration circularities, it is possible to remove those warnings locally and
28821 obtain a program that will bind. Clearly this can be unsafe, and it is the
28822 responsibility of the programmer to make sure that the resulting program has no
28823 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28824 used with different granularity to suppress warnings and break elaboration
28825 circularities:
28826
28827 @itemize @bullet
28828 @item
28829 Place the pragma that names the called subprogram in the declarative part
28830 that contains the call.
28831
28832 @item
28833 Place the pragma in the declarative part, without naming an entity. This
28834 disables warnings on all calls in the corresponding  declarative region.
28835
28836 @item
28837 Place the pragma in the package spec that declares the called subprogram,
28838 and name the subprogram. This disables warnings on all elaboration calls to
28839 that subprogram.
28840
28841 @item
28842 Place the pragma in the package spec that declares the called subprogram,
28843 without naming any entity. This disables warnings on all elaboration calls to
28844 all subprograms declared in this spec.
28845
28846 @item Use Pragma Elaborate
28847 As previously described in section @xref{Treatment of Pragma Elaborate},
28848 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28849 that no elaboration checks are required on calls to the designated unit.
28850 There may be cases in which the caller knows that no transitive calls
28851 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28852 case where @code{pragma Elaborate_All} would cause a circularity.
28853 @end itemize
28854
28855 @noindent
28856 These five cases are listed in order of decreasing safety, and therefore
28857 require increasing programmer care in their application. Consider the
28858 following program:
28859
28860 @smallexample @c adanocomment
28861 package Pack1 is
28862   function F1 return Integer;
28863   X1 : Integer;
28864 end Pack1;
28865
28866 package Pack2 is
28867   function F2 return Integer;
28868   function Pure (x : integer) return integer;
28869   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28870   --  pragma Suppress (Elaboration_Check);              -- (4)
28871 end Pack2;
28872
28873 with Pack2;
28874 package body Pack1 is
28875   function F1 return Integer is
28876   begin
28877     return 100;
28878   end F1;
28879   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28880 begin
28881   declare
28882     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28883     --  pragma Suppress(Elaboration_Check);             -- (2)
28884   begin
28885     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28886   end;
28887 end Pack1;
28888
28889 with Pack1;
28890 package body Pack2 is
28891   function F2 return Integer is
28892   begin
28893      return Pack1.F1;
28894   end F2;
28895   function Pure (x : integer) return integer is
28896   begin
28897      return x ** 3 - 3 * x;
28898   end;
28899 end Pack2;
28900
28901 with Pack1, Ada.Text_IO;
28902 procedure Proc3 is
28903 begin
28904   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28905 end Proc3;
28906 @end smallexample
28907 In the absence of any pragmas, an attempt to bind this program produces
28908 the following diagnostics:
28909 @smallexample
28910 @group
28911 @iftex
28912 @leftskip=.5cm
28913 @end iftex
28914 error: elaboration circularity detected
28915 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28916 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28917 info:       recompile "pack1 (body)" with -gnatwl for full details
28918 info:          "pack1 (body)"
28919 info:             must be elaborated along with its spec:
28920 info:          "pack1 (spec)"
28921 info:             which is withed by:
28922 info:          "pack2 (body)"
28923 info:             which must be elaborated along with its spec:
28924 info:          "pack2 (spec)"
28925 info:             which is withed by:
28926 info:          "pack1 (body)"
28927 @end group
28928 @end smallexample
28929 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28930 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28931 F2 is safe, even though F2 calls F1, because the call appears after the
28932 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28933 remove the warning on the call. It is also possible to use pragma (2)
28934 because there are no other potentially unsafe calls in the block.
28935
28936 @noindent
28937 The call to @code{Pure} is safe because this function does not depend on the
28938 state of @code{Pack2}. Therefore any call to this function is safe, and it
28939 is correct to place pragma (3) in the corresponding package spec.
28940
28941 @noindent
28942 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28943 warnings on all calls to functions declared therein. Note that this is not
28944 necessarily safe, and requires more detailed examination of the subprogram
28945 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28946 be already elaborated.
28947 @end table
28948
28949 @noindent
28950 It is hard to generalize on which of these four approaches should be
28951 taken. Obviously if it is possible to fix the program so that the default
28952 treatment works, this is preferable, but this may not always be practical.
28953 It is certainly simple enough to use
28954 @option{-gnatE}
28955 but the danger in this case is that, even if the GNAT binder
28956 finds a correct elaboration order, it may not always do so,
28957 and certainly a binder from another Ada compiler might not. A
28958 combination of testing and analysis (for which the warnings generated
28959 with the
28960 @option{-gnatwl}
28961 switch can be useful) must be used to ensure that the program is free
28962 of errors. One switch that is useful in this testing is the
28963 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28964 switch for
28965 @code{gnatbind}.
28966 Normally the binder tries to find an order that has the best chance
28967 of avoiding elaboration problems. However, if this switch is used, the binder
28968 plays a devil's advocate role, and tries to choose the order that
28969 has the best chance of failing. If your program works even with this
28970 switch, then it has a better chance of being error free, but this is still
28971 not a guarantee.
28972
28973 For an example of this approach in action, consider the C-tests (executable
28974 tests) from the ACVC suite. If these are compiled and run with the default
28975 treatment, then all but one of them succeed without generating any error
28976 diagnostics from the binder. However, there is one test that fails, and
28977 this is not surprising, because the whole point of this test is to ensure
28978 that the compiler can handle cases where it is impossible to determine
28979 a correct order statically, and it checks that an exception is indeed
28980 raised at run time.
28981
28982 This one test must be compiled and run using the
28983 @option{-gnatE}
28984 switch, and then it passes. Alternatively, the entire suite can
28985 be run using this switch. It is never wrong to run with the dynamic
28986 elaboration switch if your code is correct, and we assume that the
28987 C-tests are indeed correct (it is less efficient, but efficiency is
28988 not a factor in running the ACVC tests.)
28989
28990 @node Elaboration for Access-to-Subprogram Values
28991 @section Elaboration for Access-to-Subprogram Values
28992 @cindex Access-to-subprogram
28993
28994 @noindent
28995 Access-to-subprogram types (introduced in Ada 95) complicate
28996 the handling of elaboration. The trouble is that it becomes
28997 impossible to tell at compile time which procedure
28998 is being called. This means that it is not possible for the binder
28999 to analyze the elaboration requirements in this case.
29000
29001 If at the point at which the access value is created
29002 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29003 the body of the subprogram is
29004 known to have been elaborated, then the access value is safe, and its use
29005 does not require a check. This may be achieved by appropriate arrangement
29006 of the order of declarations if the subprogram is in the current unit,
29007 or, if the subprogram is in another unit, by using pragma
29008 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29009 on the referenced unit.
29010
29011 If the referenced body is not known to have been elaborated at the point
29012 the access value is created, then any use of the access value must do a
29013 dynamic check, and this dynamic check will fail and raise a
29014 @code{Program_Error} exception if the body has not been elaborated yet.
29015 GNAT will generate the necessary checks, and in addition, if the
29016 @option{-gnatwl}
29017 switch is set, will generate warnings that such checks are required.
29018
29019 The use of dynamic dispatching for tagged types similarly generates
29020 a requirement for dynamic checks, and premature calls to any primitive
29021 operation of a tagged type before the body of the operation has been
29022 elaborated, will result in the raising of @code{Program_Error}.
29023
29024 @node Summary of Procedures for Elaboration Control
29025 @section Summary of Procedures for Elaboration Control
29026 @cindex Elaboration control
29027
29028 @noindent
29029 First, compile your program with the default options, using none of
29030 the special elaboration control switches. If the binder successfully
29031 binds your program, then you can be confident that, apart from issues
29032 raised by the use of access-to-subprogram types and dynamic dispatching,
29033 the program is free of elaboration errors. If it is important that the
29034 program be portable, then use the
29035 @option{-gnatwl}
29036 switch to generate warnings about missing @code{Elaborate} or
29037 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29038
29039 If the program fails to bind using the default static elaboration
29040 handling, then you can fix the program to eliminate the binder
29041 message, or recompile the entire program with the
29042 @option{-gnatE} switch to generate dynamic elaboration checks,
29043 and, if you are sure there really are no elaboration problems,
29044 use a global pragma @code{Suppress (Elaboration_Check)}.
29045
29046 @node Other Elaboration Order Considerations
29047 @section Other Elaboration Order Considerations
29048 @noindent
29049 This section has been entirely concerned with the issue of finding a valid
29050 elaboration order, as defined by the Ada Reference Manual. In a case
29051 where several elaboration orders are valid, the task is to find one
29052 of the possible valid elaboration orders (and the static model in GNAT
29053 will ensure that this is achieved).
29054
29055 The purpose of the elaboration rules in the Ada Reference Manual is to
29056 make sure that no entity is accessed before it has been elaborated. For
29057 a subprogram, this means that the spec and body must have been elaborated
29058 before the subprogram is called. For an object, this means that the object
29059 must have been elaborated before its value is read or written. A violation
29060 of either of these two requirements is an access before elaboration order,
29061 and this section has been all about avoiding such errors.
29062
29063 In the case where more than one order of elaboration is possible, in the
29064 sense that access before elaboration errors are avoided, then any one of
29065 the orders is ``correct'' in the sense that it meets the requirements of
29066 the Ada Reference Manual, and no such error occurs.
29067
29068 However, it may be the case for a given program, that there are
29069 constraints on the order of elaboration that come not from consideration
29070 of avoiding elaboration errors, but rather from extra-lingual logic
29071 requirements. Consider this example:
29072
29073 @smallexample @c ada
29074 with Init_Constants;
29075 package Constants is
29076    X : Integer := 0;
29077    Y : Integer := 0;
29078 end Constants;
29079
29080 package Init_Constants is
29081    procedure P; -- require a body
29082 end Init_Constants;
29083
29084 with Constants;
29085 package body Init_Constants is
29086    procedure P is begin null; end;
29087 begin
29088    Constants.X := 3;
29089    Constants.Y := 4;
29090 end Init_Constants;
29091
29092 with Constants;
29093 package Calc is
29094    Z : Integer := Constants.X + Constants.Y;
29095 end Calc;
29096
29097 with Calc;
29098 with Text_IO; use Text_IO;
29099 procedure Main is
29100 begin
29101    Put_Line (Calc.Z'Img);
29102 end Main;
29103 @end smallexample
29104
29105 @noindent
29106 In this example, there is more than one valid order of elaboration. For
29107 example both the following are correct orders:
29108
29109 @smallexample
29110 Init_Constants spec
29111 Constants spec
29112 Calc spec
29113 Init_Constants body
29114 Main body
29115
29116   and
29117
29118 Init_Constants spec
29119 Init_Constants body
29120 Constants spec
29121 Calc spec
29122 Main body
29123 @end smallexample
29124
29125 @noindent
29126 There is no language rule to prefer one or the other, both are correct
29127 from an order of elaboration point of view. But the programmatic effects
29128 of the two orders are very different. In the first, the elaboration routine
29129 of @code{Calc} initializes @code{Z} to zero, and then the main program
29130 runs with this value of zero. But in the second order, the elaboration
29131 routine of @code{Calc} runs after the body of Init_Constants has set
29132 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29133 runs.
29134
29135 One could perhaps by applying pretty clever non-artificial intelligence
29136 to the situation guess that it is more likely that the second order of
29137 elaboration is the one desired, but there is no formal linguistic reason
29138 to prefer one over the other. In fact in this particular case, GNAT will
29139 prefer the second order, because of the rule that bodies are elaborated
29140 as soon as possible, but it's just luck that this is what was wanted
29141 (if indeed the second order was preferred).
29142
29143 If the program cares about the order of elaboration routines in a case like
29144 this, it is important to specify the order required. In this particular
29145 case, that could have been achieved by adding to the spec of Calc:
29146
29147 @smallexample @c ada
29148 pragma Elaborate_All (Constants);
29149 @end smallexample
29150
29151 @noindent
29152 which requires that the body (if any) and spec of @code{Constants},
29153 as well as the body and spec of any unit @code{with}'ed by
29154 @code{Constants} be elaborated before @code{Calc} is elaborated.
29155
29156 Clearly no automatic method can always guess which alternative you require,
29157 and if you are working with legacy code that had constraints of this kind
29158 which were not properly specified by adding @code{Elaborate} or
29159 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29160 compilers can choose different orders.
29161
29162 However, GNAT does attempt to diagnose the common situation where there
29163 are uninitialized variables in the visible part of a package spec, and the
29164 corresponding package body has an elaboration block that directly or
29165 indirectly initialized one or more of these variables. This is the situation
29166 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29167 a warning that suggests this addition if it detects this situation.
29168
29169 The @code{gnatbind}
29170 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29171 out problems. This switch causes bodies to be elaborated as late as possible
29172 instead of as early as possible. In the example above, it would have forced
29173 the choice of the first elaboration order. If you get different results
29174 when using this switch, and particularly if one set of results is right,
29175 and one is wrong as far as you are concerned, it shows that you have some
29176 missing @code{Elaborate} pragmas. For the example above, we have the
29177 following output:
29178
29179 @smallexample
29180 gnatmake -f -q main
29181 main
29182  7
29183 gnatmake -f -q main -bargs -p
29184 main
29185  0
29186 @end smallexample
29187
29188 @noindent
29189 It is of course quite unlikely that both these results are correct, so
29190 it is up to you in a case like this to investigate the source of the
29191 difference, by looking at the two elaboration orders that are chosen,
29192 and figuring out which is correct, and then adding the necessary
29193 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29194
29195
29196
29197 @c *******************************
29198 @node Conditional Compilation
29199 @appendix Conditional Compilation
29200 @c *******************************
29201 @cindex Conditional compilation
29202
29203 @noindent
29204 It is often necessary to arrange for a single source program
29205 to serve multiple purposes, where it is compiled in different
29206 ways to achieve these different goals. Some examples of the
29207 need for this feature are
29208
29209 @itemize @bullet
29210 @item  Adapting a program to a different hardware environment
29211 @item  Adapting a program to a different target architecture
29212 @item  Turning debugging features on and off
29213 @item  Arranging for a program to compile with different compilers
29214 @end itemize
29215
29216 @noindent
29217 In C, or C++, the typical approach would be to use the preprocessor
29218 that is defined as part of the language. The Ada language does not
29219 contain such a feature. This is not an oversight, but rather a very
29220 deliberate design decision, based on the experience that overuse of
29221 the preprocessing features in C and C++ can result in programs that
29222 are extremely difficult to maintain. For example, if we have ten
29223 switches that can be on or off, this means that there are a thousand
29224 separate programs, any one of which might not even be syntactically
29225 correct, and even if syntactically correct, the resulting program
29226 might not work correctly. Testing all combinations can quickly become
29227 impossible.
29228
29229 Nevertheless, the need to tailor programs certainly exists, and in
29230 this Appendix we will discuss how this can
29231 be achieved using Ada in general, and GNAT in particular.
29232
29233 @menu
29234 * Use of Boolean Constants::
29235 * Debugging - A Special Case::
29236 * Conditionalizing Declarations::
29237 * Use of Alternative Implementations::
29238 * Preprocessing::
29239 @end menu
29240
29241 @node Use of Boolean Constants
29242 @section Use of Boolean Constants
29243
29244 @noindent
29245 In the case where the difference is simply which code
29246 sequence is executed, the cleanest solution is to use Boolean
29247 constants to control which code is executed.
29248
29249 @smallexample @c ada
29250 @group
29251 FP_Initialize_Required : constant Boolean := True;
29252 @dots{}
29253 if FP_Initialize_Required then
29254 @dots{}
29255 end if;
29256 @end group
29257 @end smallexample
29258
29259 @noindent
29260 Not only will the code inside the @code{if} statement not be executed if
29261 the constant Boolean is @code{False}, but it will also be completely
29262 deleted from the program.
29263 However, the code is only deleted after the @code{if} statement
29264 has been checked for syntactic and semantic correctness.
29265 (In contrast, with preprocessors the code is deleted before the
29266 compiler ever gets to see it, so it is not checked until the switch
29267 is turned on.)
29268 @cindex Preprocessors (contrasted with conditional compilation)
29269
29270 Typically the Boolean constants will be in a separate package,
29271 something like:
29272
29273 @smallexample @c ada
29274 @group
29275 package Config is
29276    FP_Initialize_Required : constant Boolean := True;
29277    Reset_Available        : constant Boolean := False;
29278    @dots{}
29279 end Config;
29280 @end group
29281 @end smallexample
29282
29283 @noindent
29284 The @code{Config} package exists in multiple forms for the various targets,
29285 with an appropriate script selecting the version of @code{Config} needed.
29286 Then any other unit requiring conditional compilation can do a @code{with}
29287 of @code{Config} to make the constants visible.
29288
29289
29290 @node Debugging - A Special Case
29291 @section Debugging - A Special Case
29292
29293 @noindent
29294 A common use of conditional code is to execute statements (for example
29295 dynamic checks, or output of intermediate results) under control of a
29296 debug switch, so that the debugging behavior can be turned on and off.
29297 This can be done using a Boolean constant to control whether the code
29298 is active:
29299
29300 @smallexample @c ada
29301 @group
29302 if Debugging then
29303    Put_Line ("got to the first stage!");
29304 end if;
29305 @end group
29306 @end smallexample
29307
29308 @noindent
29309 or
29310
29311 @smallexample @c ada
29312 @group
29313 if Debugging and then Temperature > 999.0 then
29314    raise Temperature_Crazy;
29315 end if;
29316 @end group
29317 @end smallexample
29318
29319 @noindent
29320 Since this is a common case, there are special features to deal with
29321 this in a convenient manner. For the case of tests, Ada 2005 has added
29322 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29323 @cindex pragma @code{Assert}
29324 on the @code{Assert} pragma that has always been available in GNAT, so this
29325 feature may be used with GNAT even if you are not using Ada 2005 features.
29326 The use of pragma @code{Assert} is described in
29327 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29328 example, the last test could be written:
29329
29330 @smallexample @c ada
29331 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29332 @end smallexample
29333
29334 @noindent
29335 or simply
29336
29337 @smallexample @c ada
29338 pragma Assert (Temperature <= 999.0);
29339 @end smallexample
29340
29341 @noindent
29342 In both cases, if assertions are active and the temperature is excessive,
29343 the exception @code{Assert_Failure} will be raised, with the given string in
29344 the first case or a string indicating the location of the pragma in the second
29345 case used as the exception message.
29346
29347 You can turn assertions on and off by using the @code{Assertion_Policy}
29348 pragma.
29349 @cindex pragma @code{Assertion_Policy}
29350 This is an Ada 2005 pragma which is implemented in all modes by
29351 GNAT, but only in the latest versions of GNAT which include Ada 2005
29352 capability. Alternatively, you can use the @option{-gnata} switch
29353 @cindex @option{-gnata} switch
29354 to enable assertions from the command line (this is recognized by all versions
29355 of GNAT).
29356
29357 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29358 @code{Debug} can be used:
29359 @cindex pragma @code{Debug}
29360
29361 @smallexample @c ada
29362 pragma Debug (Put_Line ("got to the first stage!"));
29363 @end smallexample
29364
29365 @noindent
29366 If debug pragmas are enabled, the argument, which must be of the form of
29367 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29368 Only one call can be present, but of course a special debugging procedure
29369 containing any code you like can be included in the program and then
29370 called in a pragma @code{Debug} argument as needed.
29371
29372 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29373 construct is that pragma @code{Debug} can appear in declarative contexts,
29374 such as at the very beginning of a procedure, before local declarations have
29375 been elaborated.
29376
29377 Debug pragmas are enabled using either the @option{-gnata} switch that also
29378 controls assertions, or with a separate Debug_Policy pragma.
29379 @cindex pragma @code{Debug_Policy}
29380 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29381 in Ada 95 and Ada 83 programs as well), and is analogous to
29382 pragma @code{Assertion_Policy} to control assertions.
29383
29384 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29385 and thus they can appear in @file{gnat.adc} if you are not using a
29386 project file, or in the file designated to contain configuration pragmas
29387 in a project file.
29388 They then apply to all subsequent compilations. In practice the use of
29389 the @option{-gnata} switch is often the most convenient method of controlling
29390 the status of these pragmas.
29391
29392 Note that a pragma is not a statement, so in contexts where a statement
29393 sequence is required, you can't just write a pragma on its own. You have
29394 to add a @code{null} statement.
29395
29396 @smallexample @c ada
29397 @group
29398 if @dots{} then
29399    @dots{} -- some statements
29400 else
29401    pragma Assert (Num_Cases < 10);
29402    null;
29403 end if;
29404 @end group
29405 @end smallexample
29406
29407
29408 @node Conditionalizing Declarations
29409 @section Conditionalizing Declarations
29410
29411 @noindent
29412 In some cases, it may be necessary to conditionalize declarations to meet
29413 different requirements. For example we might want a bit string whose length
29414 is set to meet some hardware message requirement.
29415
29416 In some cases, it may be possible to do this using declare blocks controlled
29417 by conditional constants:
29418
29419 @smallexample @c ada
29420 @group
29421 if Small_Machine then
29422    declare
29423       X : Bit_String (1 .. 10);
29424    begin
29425       @dots{}
29426    end;
29427 else
29428    declare
29429       X : Large_Bit_String (1 .. 1000);
29430    begin
29431       @dots{}
29432    end;
29433 end if;
29434 @end group
29435 @end smallexample
29436
29437 @noindent
29438 Note that in this approach, both declarations are analyzed by the
29439 compiler so this can only be used where both declarations are legal,
29440 even though one of them will not be used.
29441
29442 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29443 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29444 that are parameterized by these constants. For example
29445
29446 @smallexample @c ada
29447 @group
29448 for Rec use
29449   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29450 end record;
29451 @end group
29452 @end smallexample
29453
29454 @noindent
29455 If @code{Bits_Per_Word} is set to 32, this generates either
29456
29457 @smallexample @c ada
29458 @group
29459 for Rec use
29460   Field1 at 0 range 0 .. 32;
29461 end record;
29462 @end group
29463 @end smallexample
29464
29465 @noindent
29466 for the big endian case, or
29467
29468 @smallexample @c ada
29469 @group
29470 for Rec use record
29471   Field1 at 0 range 10 .. 32;
29472 end record;
29473 @end group
29474 @end smallexample
29475
29476 @noindent
29477 for the little endian case. Since a powerful subset of Ada expression
29478 notation is usable for creating static constants, clever use of this
29479 feature can often solve quite difficult problems in conditionalizing
29480 compilation (note incidentally that in Ada 95, the little endian
29481 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29482 need to define this one yourself).
29483
29484
29485 @node Use of Alternative Implementations
29486 @section Use of Alternative Implementations
29487
29488 @noindent
29489 In some cases, none of the approaches described above are adequate. This
29490 can occur for example if the set of declarations required is radically
29491 different for two different configurations.
29492
29493 In this situation, the official Ada way of dealing with conditionalizing
29494 such code is to write separate units for the different cases. As long as
29495 this does not result in excessive duplication of code, this can be done
29496 without creating maintenance problems. The approach is to share common
29497 code as far as possible, and then isolate the code and declarations
29498 that are different. Subunits are often a convenient method for breaking
29499 out a piece of a unit that is to be conditionalized, with separate files
29500 for different versions of the subunit for different targets, where the
29501 build script selects the right one to give to the compiler.
29502 @cindex Subunits (and conditional compilation)
29503
29504 As an example, consider a situation where a new feature in Ada 2005
29505 allows something to be done in a really nice way. But your code must be able
29506 to compile with an Ada 95 compiler. Conceptually you want to say:
29507
29508 @smallexample @c ada
29509 @group
29510 if Ada_2005 then
29511    @dots{} neat Ada 2005 code
29512 else
29513    @dots{} not quite as neat Ada 95 code
29514 end if;
29515 @end group
29516 @end smallexample
29517
29518 @noindent
29519 where @code{Ada_2005} is a Boolean constant.
29520
29521 But this won't work when @code{Ada_2005} is set to @code{False},
29522 since the @code{then} clause will be illegal for an Ada 95 compiler.
29523 (Recall that although such unreachable code would eventually be deleted
29524 by the compiler, it still needs to be legal.  If it uses features
29525 introduced in Ada 2005, it will be illegal in Ada 95.)
29526
29527 So instead we write
29528
29529 @smallexample @c ada
29530 procedure Insert is separate;
29531 @end smallexample
29532
29533 @noindent
29534 Then we have two files for the subunit @code{Insert}, with the two sets of
29535 code.
29536 If the package containing this is called @code{File_Queries}, then we might
29537 have two files
29538
29539 @itemize @bullet
29540 @item    @file{file_queries-insert-2005.adb}
29541 @item    @file{file_queries-insert-95.adb}
29542 @end itemize
29543
29544 @noindent
29545 and the build script renames the appropriate file to
29546
29547 @smallexample
29548 file_queries-insert.adb
29549 @end smallexample
29550
29551 @noindent
29552 and then carries out the compilation.
29553
29554 This can also be done with project files' naming schemes. For example:
29555
29556 @smallexample @c project
29557 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29558 @end smallexample
29559
29560 @noindent
29561 Note also that with project files it is desirable to use a different extension
29562 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29563 conflict may arise through another commonly used feature: to declare as part
29564 of the project a set of directories containing all the sources obeying the
29565 default naming scheme.
29566
29567 The use of alternative units is certainly feasible in all situations,
29568 and for example the Ada part of the GNAT run-time is conditionalized
29569 based on the target architecture using this approach. As a specific example,
29570 consider the implementation of the AST feature in VMS. There is one
29571 spec:
29572
29573 @smallexample
29574 s-asthan.ads
29575 @end smallexample
29576
29577 @noindent
29578 which is the same for all architectures, and three bodies:
29579
29580 @table @file
29581 @item    s-asthan.adb
29582 used for all non-VMS operating systems
29583 @item    s-asthan-vms-alpha.adb
29584 used for VMS on the Alpha
29585 @item    s-asthan-vms-ia64.adb
29586 used for VMS on the ia64
29587 @end table
29588
29589 @noindent
29590 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29591 this operating system feature is not available, and the two remaining
29592 versions interface with the corresponding versions of VMS to provide
29593 VMS-compatible AST handling. The GNAT build script knows the architecture
29594 and operating system, and automatically selects the right version,
29595 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29596
29597 Another style for arranging alternative implementations is through Ada's
29598 access-to-subprogram facility.
29599 In case some functionality is to be conditionally included,
29600 you can declare an access-to-procedure variable @code{Ref} that is initialized
29601 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29602 when appropriate.
29603 In some library package, set @code{Ref} to @code{Proc'Access} for some
29604 procedure @code{Proc} that performs the relevant processing.
29605 The initialization only occurs if the library package is included in the
29606 program.
29607 The same idea can also be implemented using tagged types and dispatching
29608 calls.
29609
29610
29611 @node Preprocessing
29612 @section Preprocessing
29613 @cindex Preprocessing
29614
29615 @noindent
29616 Although it is quite possible to conditionalize code without the use of
29617 C-style preprocessing, as described earlier in this section, it is
29618 nevertheless convenient in some cases to use the C approach. Moreover,
29619 older Ada compilers have often provided some preprocessing capability,
29620 so legacy code may depend on this approach, even though it is not
29621 standard.
29622
29623 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29624 extent on the various preprocessors that have been used
29625 with legacy code on other compilers, to enable easier transition).
29626
29627 The preprocessor may be used in two separate modes. It can be used quite
29628 separately from the compiler, to generate a separate output source file
29629 that is then fed to the compiler as a separate step. This is the
29630 @code{gnatprep} utility, whose use is fully described in
29631 @ref{Preprocessing Using gnatprep}.
29632 @cindex @code{gnatprep}
29633
29634 The preprocessing language allows such constructs as
29635
29636 @smallexample
29637 @group
29638 #if DEBUG or PRIORITY > 4 then
29639    bunch of declarations
29640 #else
29641    completely different bunch of declarations
29642 #end if;
29643 @end group
29644 @end smallexample
29645
29646 @noindent
29647 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29648 defined either on the command line or in a separate file.
29649
29650 The other way of running the preprocessor is even closer to the C style and
29651 often more convenient. In this approach the preprocessing is integrated into
29652 the compilation process. The compiler is fed the preprocessor input which
29653 includes @code{#if} lines etc, and then the compiler carries out the
29654 preprocessing internally and processes the resulting output.
29655 For more details on this approach, see @ref{Integrated Preprocessing}.
29656
29657
29658 @c *******************************
29659 @node Inline Assembler
29660 @appendix Inline Assembler
29661 @c *******************************
29662
29663 @noindent
29664 If you need to write low-level software that interacts directly
29665 with the hardware, Ada provides two ways to incorporate assembly
29666 language code into your program.  First, you can import and invoke
29667 external routines written in assembly language, an Ada feature fully
29668 supported by GNAT@.  However, for small sections of code it may be simpler
29669 or more efficient to include assembly language statements directly
29670 in your Ada source program, using the facilities of the implementation-defined
29671 package @code{System.Machine_Code}, which incorporates the gcc
29672 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29673 including the following:
29674
29675 @itemize @bullet
29676 @item No need to use non-Ada tools
29677 @item Consistent interface over different targets
29678 @item Automatic usage of the proper calling conventions
29679 @item Access to Ada constants and variables
29680 @item Definition of intrinsic routines
29681 @item Possibility of inlining a subprogram comprising assembler code
29682 @item Code optimizer can take Inline Assembler code into account
29683 @end itemize
29684
29685 This chapter presents a series of examples to show you how to use
29686 the Inline Assembler.  Although it focuses on the Intel x86,
29687 the general approach applies also to other processors.
29688 It is assumed that you are familiar with Ada
29689 and with assembly language programming.
29690
29691 @menu
29692 * Basic Assembler Syntax::
29693 * A Simple Example of Inline Assembler::
29694 * Output Variables in Inline Assembler::
29695 * Input Variables in Inline Assembler::
29696 * Inlining Inline Assembler Code::
29697 * Other Asm Functionality::
29698 @end menu
29699
29700 @c ---------------------------------------------------------------------------
29701 @node Basic Assembler Syntax
29702 @section Basic Assembler Syntax
29703
29704 @noindent
29705 The assembler used by GNAT and gcc is based not on the Intel assembly
29706 language, but rather on a language that descends from the AT&T Unix
29707 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29708 The following table summarizes the main features of @emph{as} syntax
29709 and points out the differences from the Intel conventions.
29710 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29711 pre-processor) documentation for further information.
29712
29713 @table @asis
29714 @item Register names
29715 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29716 @*
29717 Intel: No extra punctuation; for example @code{eax}
29718
29719 @item Immediate operand
29720 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29721 @*
29722 Intel: No extra punctuation; for example @code{4}
29723
29724 @item Address
29725 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29726 @*
29727 Intel: No extra punctuation; for example @code{loc}
29728
29729 @item Memory contents
29730 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29731 @*
29732 Intel: Square brackets; for example @code{[loc]}
29733
29734 @item Register contents
29735 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29736 @*
29737 Intel: Square brackets; for example @code{[eax]}
29738
29739 @item Hexadecimal numbers
29740 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29741 @*
29742 Intel: Trailing ``h''; for example @code{A0h}
29743
29744 @item Operand size
29745 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29746 a 16-bit word
29747 @*
29748 Intel: Implicit, deduced by assembler; for example @code{mov}
29749
29750 @item Instruction repetition
29751 gcc / @emph{as}: Split into two lines; for example
29752 @*
29753 @code{rep}
29754 @*
29755 @code{stosl}
29756 @*
29757 Intel: Keep on one line; for example @code{rep stosl}
29758
29759 @item Order of operands
29760 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29761 @*
29762 Intel: Destination first; for example @code{mov eax, 4}
29763 @end table
29764
29765 @c ---------------------------------------------------------------------------
29766 @node A Simple Example of Inline Assembler
29767 @section A Simple Example of Inline Assembler
29768
29769 @noindent
29770 The following example will generate a single assembly language statement,
29771 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29772 the example will be useful in illustrating the basics of
29773 the Inline Assembler facility.
29774
29775 @smallexample @c ada
29776 @group
29777 with System.Machine_Code; use System.Machine_Code;
29778 procedure Nothing is
29779 begin
29780    Asm ("nop");
29781 end Nothing;
29782 @end group
29783 @end smallexample
29784
29785 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29786 here it takes one parameter, a @emph{template string} that must be a static
29787 expression and that will form the generated instruction.
29788 @code{Asm} may be regarded as a compile-time procedure that parses
29789 the template string and additional parameters (none here),
29790 from which it generates a sequence of assembly language instructions.
29791
29792 The examples in this chapter will illustrate several of the forms
29793 for invoking @code{Asm}; a complete specification of the syntax
29794 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29795 Manual}.
29796
29797 Under the standard GNAT conventions, the @code{Nothing} procedure
29798 should be in a file named @file{nothing.adb}.
29799 You can build the executable in the usual way:
29800 @smallexample
29801 gnatmake nothing
29802 @end smallexample
29803 However, the interesting aspect of this example is not its run-time behavior
29804 but rather the generated assembly code.
29805 To see this output, invoke the compiler as follows:
29806 @smallexample
29807    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29808 @end smallexample
29809 where the options are:
29810
29811 @table @code
29812 @item -c
29813 compile only (no bind or link)
29814 @item -S
29815 generate assembler listing
29816 @item -fomit-frame-pointer
29817 do not set up separate stack frames
29818 @item -gnatp
29819 do not add runtime checks
29820 @end table
29821
29822 This gives a human-readable assembler version of the code. The resulting
29823 file will have the same name as the Ada source file, but with a @code{.s}
29824 extension. In our example, the file @file{nothing.s} has the following
29825 contents:
29826
29827 @smallexample
29828 @group
29829 .file "nothing.adb"
29830 gcc2_compiled.:
29831 ___gnu_compiled_ada:
29832 .text
29833    .align 4
29834 .globl __ada_nothing
29835 __ada_nothing:
29836 #APP
29837    nop
29838 #NO_APP
29839    jmp L1
29840    .align 2,0x90
29841 L1:
29842    ret
29843 @end group
29844 @end smallexample
29845
29846 The assembly code you included is clearly indicated by
29847 the compiler, between the @code{#APP} and @code{#NO_APP}
29848 delimiters. The character before the 'APP' and 'NOAPP'
29849 can differ on different targets. For example, GNU/Linux uses '#APP' while
29850 on NT you will see '/APP'.
29851
29852 If you make a mistake in your assembler code (such as using the
29853 wrong size modifier, or using a wrong operand for the instruction) GNAT
29854 will report this error in a temporary file, which will be deleted when
29855 the compilation is finished.  Generating an assembler file will help
29856 in such cases, since you can assemble this file separately using the
29857 @emph{as} assembler that comes with gcc.
29858
29859 Assembling the file using the command
29860
29861 @smallexample
29862 as @file{nothing.s}
29863 @end smallexample
29864 @noindent
29865 will give you error messages whose lines correspond to the assembler
29866 input file, so you can easily find and correct any mistakes you made.
29867 If there are no errors, @emph{as} will generate an object file
29868 @file{nothing.out}.
29869
29870 @c ---------------------------------------------------------------------------
29871 @node Output Variables in Inline Assembler
29872 @section Output Variables in Inline Assembler
29873
29874 @noindent
29875 The examples in this section, showing how to access the processor flags,
29876 illustrate how to specify the destination operands for assembly language
29877 statements.
29878
29879 @smallexample @c ada
29880 @group
29881 with Interfaces; use Interfaces;
29882 with Ada.Text_IO; use Ada.Text_IO;
29883 with System.Machine_Code; use System.Machine_Code;
29884 procedure Get_Flags is
29885    Flags : Unsigned_32;
29886    use ASCII;
29887 begin
29888    Asm ("pushfl"          & LF & HT & -- push flags on stack
29889         "popl %%eax"      & LF & HT & -- load eax with flags
29890         "movl %%eax, %0",             -- store flags in variable
29891         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29892    Put_Line ("Flags register:" & Flags'Img);
29893 end Get_Flags;
29894 @end group
29895 @end smallexample
29896
29897 In order to have a nicely aligned assembly listing, we have separated
29898 multiple assembler statements in the Asm template string with linefeed
29899 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29900 The resulting section of the assembly output file is:
29901
29902 @smallexample
29903 @group
29904 #APP
29905    pushfl
29906    popl %eax
29907    movl %eax, -40(%ebp)
29908 #NO_APP
29909 @end group
29910 @end smallexample
29911
29912 It would have been legal to write the Asm invocation as:
29913
29914 @smallexample
29915 Asm ("pushfl popl %%eax movl %%eax, %0")
29916 @end smallexample
29917
29918 but in the generated assembler file, this would come out as:
29919
29920 @smallexample
29921 #APP
29922    pushfl popl %eax movl %eax, -40(%ebp)
29923 #NO_APP
29924 @end smallexample
29925
29926 which is not so convenient for the human reader.
29927
29928 We use Ada comments
29929 at the end of each line to explain what the assembler instructions
29930 actually do.  This is a useful convention.
29931
29932 When writing Inline Assembler instructions, you need to precede each register
29933 and variable name with a percent sign.  Since the assembler already requires
29934 a percent sign at the beginning of a register name, you need two consecutive
29935 percent signs for such names in the Asm template string, thus @code{%%eax}.
29936 In the generated assembly code, one of the percent signs will be stripped off.
29937
29938 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29939 variables: operands you later define using @code{Input} or @code{Output}
29940 parameters to @code{Asm}.
29941 An output variable is illustrated in
29942 the third statement in the Asm template string:
29943 @smallexample
29944 movl %%eax, %0
29945 @end smallexample
29946 The intent is to store the contents of the eax register in a variable that can
29947 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29948 necessarily work, since the compiler might optimize by using a register
29949 to hold Flags, and the expansion of the @code{movl} instruction would not be
29950 aware of this optimization.  The solution is not to store the result directly
29951 but rather to advise the compiler to choose the correct operand form;
29952 that is the purpose of the @code{%0} output variable.
29953
29954 Information about the output variable is supplied in the @code{Outputs}
29955 parameter to @code{Asm}:
29956 @smallexample
29957 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29958 @end smallexample
29959
29960 The output is defined by the @code{Asm_Output} attribute of the target type;
29961 the general format is
29962 @smallexample
29963 Type'Asm_Output (constraint_string, variable_name)
29964 @end smallexample
29965
29966 The constraint string directs the compiler how
29967 to store/access the associated variable.  In the example
29968 @smallexample
29969 Unsigned_32'Asm_Output ("=m", Flags);
29970 @end smallexample
29971 the @code{"m"} (memory) constraint tells the compiler that the variable
29972 @code{Flags} should be stored in a memory variable, thus preventing
29973 the optimizer from keeping it in a register.  In contrast,
29974 @smallexample
29975 Unsigned_32'Asm_Output ("=r", Flags);
29976 @end smallexample
29977 uses the @code{"r"} (register) constraint, telling the compiler to
29978 store the variable in a register.
29979
29980 If the constraint is preceded by the equal character (@strong{=}), it tells
29981 the compiler that the variable will be used to store data into it.
29982
29983 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29984 allowing the optimizer to choose whatever it deems best.
29985
29986 There are a fairly large number of constraints, but the ones that are
29987 most useful (for the Intel x86 processor) are the following:
29988
29989 @table @code
29990 @item =
29991 output constraint
29992 @item g
29993 global (i.e.@: can be stored anywhere)
29994 @item m
29995 in memory
29996 @item I
29997 a constant
29998 @item a
29999 use eax
30000 @item b
30001 use ebx
30002 @item c
30003 use ecx
30004 @item d
30005 use edx
30006 @item S
30007 use esi
30008 @item D
30009 use edi
30010 @item r
30011 use one of eax, ebx, ecx or edx
30012 @item q
30013 use one of eax, ebx, ecx, edx, esi or edi
30014 @end table
30015
30016 The full set of constraints is described in the gcc and @emph{as}
30017 documentation; note that it is possible to combine certain constraints
30018 in one constraint string.
30019
30020 You specify the association of an output variable with an assembler operand
30021 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30022 integer.  Thus in
30023 @smallexample @c ada
30024 @group
30025 Asm ("pushfl"          & LF & HT & -- push flags on stack
30026      "popl %%eax"      & LF & HT & -- load eax with flags
30027      "movl %%eax, %0",             -- store flags in variable
30028      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30029 @end group
30030 @end smallexample
30031 @noindent
30032 @code{%0} will be replaced in the expanded code by the appropriate operand,
30033 whatever
30034 the compiler decided for the @code{Flags} variable.
30035
30036 In general, you may have any number of output variables:
30037 @itemize @bullet
30038 @item
30039 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30040 @item
30041 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30042 of @code{Asm_Output} attributes
30043 @end itemize
30044
30045 For example:
30046 @smallexample @c ada
30047 @group
30048 Asm ("movl %%eax, %0" & LF & HT &
30049      "movl %%ebx, %1" & LF & HT &
30050      "movl %%ecx, %2",
30051      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30052                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30053                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30054 @end group
30055 @end smallexample
30056 @noindent
30057 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30058 in the Ada program.
30059
30060 As a variation on the @code{Get_Flags} example, we can use the constraints
30061 string to direct the compiler to store the eax register into the @code{Flags}
30062 variable, instead of including the store instruction explicitly in the
30063 @code{Asm} template string:
30064
30065 @smallexample @c ada
30066 @group
30067 with Interfaces; use Interfaces;
30068 with Ada.Text_IO; use Ada.Text_IO;
30069 with System.Machine_Code; use System.Machine_Code;
30070 procedure Get_Flags_2 is
30071    Flags : Unsigned_32;
30072    use ASCII;
30073 begin
30074    Asm ("pushfl"      & LF & HT & -- push flags on stack
30075         "popl %%eax",             -- save flags in eax
30076         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30077    Put_Line ("Flags register:" & Flags'Img);
30078 end Get_Flags_2;
30079 @end group
30080 @end smallexample
30081
30082 @noindent
30083 The @code{"a"} constraint tells the compiler that the @code{Flags}
30084 variable will come from the eax register. Here is the resulting code:
30085
30086 @smallexample
30087 @group
30088 #APP
30089    pushfl
30090    popl %eax
30091 #NO_APP
30092    movl %eax,-40(%ebp)
30093 @end group
30094 @end smallexample
30095
30096 @noindent
30097 The compiler generated the store of eax into Flags after
30098 expanding the assembler code.
30099
30100 Actually, there was no need to pop the flags into the eax register;
30101 more simply, we could just pop the flags directly into the program variable:
30102
30103 @smallexample @c ada
30104 @group
30105 with Interfaces; use Interfaces;
30106 with Ada.Text_IO; use Ada.Text_IO;
30107 with System.Machine_Code; use System.Machine_Code;
30108 procedure Get_Flags_3 is
30109    Flags : Unsigned_32;
30110    use ASCII;
30111 begin
30112    Asm ("pushfl"  & LF & HT & -- push flags on stack
30113         "pop %0",             -- save flags in Flags
30114         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30115    Put_Line ("Flags register:" & Flags'Img);
30116 end Get_Flags_3;
30117 @end group
30118 @end smallexample
30119
30120 @c ---------------------------------------------------------------------------
30121 @node Input Variables in Inline Assembler
30122 @section Input Variables in Inline Assembler
30123
30124 @noindent
30125 The example in this section illustrates how to specify the source operands
30126 for assembly language statements.
30127 The program simply increments its input value by 1:
30128
30129 @smallexample @c ada
30130 @group
30131 with Interfaces; use Interfaces;
30132 with Ada.Text_IO; use Ada.Text_IO;
30133 with System.Machine_Code; use System.Machine_Code;
30134 procedure Increment is
30135
30136    function Incr (Value : Unsigned_32) return Unsigned_32 is
30137       Result : Unsigned_32;
30138    begin
30139       Asm ("incl %0",
30140            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30141            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30142       return Result;
30143    end Incr;
30144
30145    Value : Unsigned_32;
30146
30147 begin
30148    Value := 5;
30149    Put_Line ("Value before is" & Value'Img);
30150    Value := Incr (Value);
30151    Put_Line ("Value after is" & Value'Img);
30152 end Increment;
30153 @end group
30154 @end smallexample
30155
30156 The @code{Outputs} parameter to @code{Asm} specifies
30157 that the result will be in the eax register and that it is to be stored
30158 in the @code{Result} variable.
30159
30160 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30161 but with an @code{Asm_Input} attribute.
30162 The @code{"="} constraint, indicating an output value, is not present.
30163
30164 You can have multiple input variables, in the same way that you can have more
30165 than one output variable.
30166
30167 The parameter count (%0, %1) etc, now starts at the first input
30168 statement, and continues with the output statements.
30169 When both parameters use the same variable, the
30170 compiler will treat them as the same %n operand, which is the case here.
30171
30172 Just as the @code{Outputs} parameter causes the register to be stored into the
30173 target variable after execution of the assembler statements, so does the
30174 @code{Inputs} parameter cause its variable to be loaded into the register
30175 before execution of the assembler statements.
30176
30177 Thus the effect of the @code{Asm} invocation is:
30178 @enumerate
30179 @item load the 32-bit value of @code{Value} into eax
30180 @item execute the @code{incl %eax} instruction
30181 @item store the contents of eax into the @code{Result} variable
30182 @end enumerate
30183
30184 The resulting assembler file (with @option{-O2} optimization) contains:
30185 @smallexample
30186 @group
30187 _increment__incr.1:
30188    subl $4,%esp
30189    movl 8(%esp),%eax
30190 #APP
30191    incl %eax
30192 #NO_APP
30193    movl %eax,%edx
30194    movl %ecx,(%esp)
30195    addl $4,%esp
30196    ret
30197 @end group
30198 @end smallexample
30199
30200 @c ---------------------------------------------------------------------------
30201 @node Inlining Inline Assembler Code
30202 @section Inlining Inline Assembler Code
30203
30204 @noindent
30205 For a short subprogram such as the @code{Incr} function in the previous
30206 section, the overhead of the call and return (creating / deleting the stack
30207 frame) can be significant, compared to the amount of code in the subprogram
30208 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30209 which directs the compiler to expand invocations of the subprogram at the
30210 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30211 Here is the resulting program:
30212
30213 @smallexample @c ada
30214 @group
30215 with Interfaces; use Interfaces;
30216 with Ada.Text_IO; use Ada.Text_IO;
30217 with System.Machine_Code; use System.Machine_Code;
30218 procedure Increment_2 is
30219
30220    function Incr (Value : Unsigned_32) return Unsigned_32 is
30221       Result : Unsigned_32;
30222    begin
30223       Asm ("incl %0",
30224            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30225            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30226       return Result;
30227    end Incr;
30228    pragma Inline (Increment);
30229
30230    Value : Unsigned_32;
30231
30232 begin
30233    Value := 5;
30234    Put_Line ("Value before is" & Value'Img);
30235    Value := Increment (Value);
30236    Put_Line ("Value after is" & Value'Img);
30237 end Increment_2;
30238 @end group
30239 @end smallexample
30240
30241 Compile the program with both optimization (@option{-O2}) and inlining
30242 (@option{-gnatn}) enabled.
30243
30244 The @code{Incr} function is still compiled as usual, but at the
30245 point in @code{Increment} where our function used to be called:
30246
30247 @smallexample
30248 @group
30249 pushl %edi
30250 call _increment__incr.1
30251 @end group
30252 @end smallexample
30253
30254 @noindent
30255 the code for the function body directly appears:
30256
30257 @smallexample
30258 @group
30259 movl %esi,%eax
30260 #APP
30261    incl %eax
30262 #NO_APP
30263    movl %eax,%edx
30264 @end group
30265 @end smallexample
30266
30267 @noindent
30268 thus saving the overhead of stack frame setup and an out-of-line call.
30269
30270 @c ---------------------------------------------------------------------------
30271 @node Other Asm Functionality
30272 @section Other @code{Asm} Functionality
30273
30274 @noindent
30275 This section describes two important parameters to the @code{Asm}
30276 procedure: @code{Clobber}, which identifies register usage;
30277 and @code{Volatile}, which inhibits unwanted optimizations.
30278
30279 @menu
30280 * The Clobber Parameter::
30281 * The Volatile Parameter::
30282 @end menu
30283
30284 @c ---------------------------------------------------------------------------
30285 @node The Clobber Parameter
30286 @subsection The @code{Clobber} Parameter
30287
30288 @noindent
30289 One of the dangers of intermixing assembly language and a compiled language
30290 such as Ada is that the compiler needs to be aware of which registers are
30291 being used by the assembly code.  In some cases, such as the earlier examples,
30292 the constraint string is sufficient to indicate register usage (e.g.,
30293 @code{"a"} for
30294 the eax register).  But more generally, the compiler needs an explicit
30295 identification of the registers that are used by the Inline Assembly
30296 statements.
30297
30298 Using a register that the compiler doesn't know about
30299 could be a side effect of an instruction (like @code{mull}
30300 storing its result in both eax and edx).
30301 It can also arise from explicit register usage in your
30302 assembly code; for example:
30303 @smallexample
30304 @group
30305 Asm ("movl %0, %%ebx" & LF & HT &
30306      "movl %%ebx, %1",
30307      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30308      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30309 @end group
30310 @end smallexample
30311 @noindent
30312 where the compiler (since it does not analyze the @code{Asm} template string)
30313 does not know you are using the ebx register.
30314
30315 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30316 to identify the registers that will be used by your assembly code:
30317
30318 @smallexample
30319 @group
30320 Asm ("movl %0, %%ebx" & LF & HT &
30321      "movl %%ebx, %1",
30322      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30323      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30324      Clobber => "ebx");
30325 @end group
30326 @end smallexample
30327
30328 The Clobber parameter is a static string expression specifying the
30329 register(s) you are using.  Note that register names are @emph{not} prefixed
30330 by a percent sign. Also, if more than one register is used then their names
30331 are separated by commas; e.g., @code{"eax, ebx"}
30332
30333 The @code{Clobber} parameter has several additional uses:
30334 @enumerate
30335 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30336 @item Use ``register'' name @code{memory} if you changed a memory location
30337 @end enumerate
30338
30339 @c ---------------------------------------------------------------------------
30340 @node The Volatile Parameter
30341 @subsection The @code{Volatile} Parameter
30342 @cindex Volatile parameter
30343
30344 @noindent
30345 Compiler optimizations in the presence of Inline Assembler may sometimes have
30346 unwanted effects.  For example, when an @code{Asm} invocation with an input
30347 variable is inside a loop, the compiler might move the loading of the input
30348 variable outside the loop, regarding it as a one-time initialization.
30349
30350 If this effect is not desired, you can disable such optimizations by setting
30351 the @code{Volatile} parameter to @code{True}; for example:
30352
30353 @smallexample @c ada
30354 @group
30355 Asm ("movl %0, %%ebx" & LF & HT &
30356      "movl %%ebx, %1",
30357      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30358      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30359      Clobber  => "ebx",
30360      Volatile => True);
30361 @end group
30362 @end smallexample
30363
30364 By default, @code{Volatile} is set to @code{False} unless there is no
30365 @code{Outputs} parameter.
30366
30367 Although setting @code{Volatile} to @code{True} prevents unwanted
30368 optimizations, it will also disable other optimizations that might be
30369 important for efficiency. In general, you should set @code{Volatile}
30370 to @code{True} only if the compiler's optimizations have created
30371 problems.
30372 @c END OF INLINE ASSEMBLER CHAPTER
30373 @c ===============================
30374
30375 @c ***********************************
30376 @c * Compatibility and Porting Guide *
30377 @c ***********************************
30378 @node Compatibility and Porting Guide
30379 @appendix Compatibility and Porting Guide
30380
30381 @noindent
30382 This chapter describes the compatibility issues that may arise between
30383 GNAT and other Ada compilation systems (including those for Ada 83),
30384 and shows how GNAT can expedite porting
30385 applications developed in other Ada environments.
30386
30387 @menu
30388 * Compatibility with Ada 83::
30389 * Compatibility between Ada 95 and Ada 2005::
30390 * Implementation-dependent characteristics::
30391 * Compatibility with Other Ada Systems::
30392 * Representation Clauses::
30393 @ifclear vms
30394 @c Brief section is only in non-VMS version
30395 @c Full chapter is in VMS version
30396 * Compatibility with HP Ada 83::
30397 @end ifclear
30398 @ifset vms
30399 * Transitioning to 64-Bit GNAT for OpenVMS::
30400 @end ifset
30401 @end menu
30402
30403 @node Compatibility with Ada 83
30404 @section Compatibility with Ada 83
30405 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30406
30407 @noindent
30408 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30409 particular, the design intention was that the difficulties associated
30410 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30411 that occur when moving from one Ada 83 system to another.
30412
30413 However, there are a number of points at which there are minor
30414 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30415 full details of these issues,
30416 and should be consulted for a complete treatment.
30417 In practice the
30418 following subsections treat the most likely issues to be encountered.
30419
30420 @menu
30421 * Legal Ada 83 programs that are illegal in Ada 95::
30422 * More deterministic semantics::
30423 * Changed semantics::
30424 * Other language compatibility issues::
30425 @end menu
30426
30427 @node Legal Ada 83 programs that are illegal in Ada 95
30428 @subsection Legal Ada 83 programs that are illegal in Ada 95
30429
30430 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30431 Ada 95 and thus also in Ada 2005:
30432
30433 @table @emph
30434 @item Character literals
30435 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30436 @code{Wide_Character} as a new predefined character type, some uses of
30437 character literals that were legal in Ada 83 are illegal in Ada 95.
30438 For example:
30439 @smallexample @c ada
30440    for Char in 'A' .. 'Z' loop @dots{} end loop;
30441 @end smallexample
30442
30443 @noindent
30444 The problem is that @code{'A'} and @code{'Z'} could be from either
30445 @code{Character} or @code{Wide_Character}.  The simplest correction
30446 is to make the type explicit; e.g.:
30447 @smallexample @c ada
30448    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30449 @end smallexample
30450
30451 @item New reserved words
30452 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30453 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30454 Existing Ada 83 code using any of these identifiers must be edited to
30455 use some alternative name.
30456
30457 @item Freezing rules
30458 The rules in Ada 95 are slightly different with regard to the point at
30459 which entities are frozen, and representation pragmas and clauses are
30460 not permitted past the freeze point.  This shows up most typically in
30461 the form of an error message complaining that a representation item
30462 appears too late, and the appropriate corrective action is to move
30463 the item nearer to the declaration of the entity to which it refers.
30464
30465 A particular case is that representation pragmas
30466 @ifset vms
30467 (including the
30468 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30469 @end ifset
30470 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30471 declaration must be introduced to which the pragma can be applied.
30472
30473 @item Optional bodies for library packages
30474 In Ada 83, a package that did not require a package body was nevertheless
30475 allowed to have one.  This lead to certain surprises in compiling large
30476 systems (situations in which the body could be unexpectedly ignored by the
30477 binder).  In Ada 95, if a package does not require a body then it is not
30478 permitted to have a body.  To fix this problem, simply remove a redundant
30479 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30480 into the spec that makes the body required.  One approach is to add a private
30481 part to the package declaration (if necessary), and define a parameterless
30482 procedure called @code{Requires_Body}, which must then be given a dummy
30483 procedure body in the package body, which then becomes required.
30484 Another approach (assuming that this does not introduce elaboration
30485 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30486 since one effect of this pragma is to require the presence of a package body.
30487
30488 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30489 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30490 @code{Constraint_Error}.
30491 This means that it is illegal to have separate exception handlers for
30492 the two exceptions.  The fix is simply to remove the handler for the
30493 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30494 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30495
30496 @item Indefinite subtypes in generics
30497 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30498 as the actual for a generic formal private type, but then the instantiation
30499 would be illegal if there were any instances of declarations of variables
30500 of this type in the generic body.  In Ada 95, to avoid this clear violation
30501 of the methodological principle known as the ``contract model'',
30502 the generic declaration explicitly indicates whether
30503 or not such instantiations are permitted.  If a generic formal parameter
30504 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30505 type name, then it can be instantiated with indefinite types, but no
30506 stand-alone variables can be declared of this type.  Any attempt to declare
30507 such a variable will result in an illegality at the time the generic is
30508 declared.  If the @code{(<>)} notation is not used, then it is illegal
30509 to instantiate the generic with an indefinite type.
30510 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30511 It will show up as a compile time error, and
30512 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30513 @end table
30514
30515 @node More deterministic semantics
30516 @subsection More deterministic semantics
30517
30518 @table @emph
30519 @item Conversions
30520 Conversions from real types to integer types round away from 0.  In Ada 83
30521 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30522 implementation freedom was intended to support unbiased rounding in
30523 statistical applications, but in practice it interfered with portability.
30524 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30525 is required.  Numeric code may be affected by this change in semantics.
30526 Note, though, that this issue is no worse than already existed in Ada 83
30527 when porting code from one vendor to another.
30528
30529 @item Tasking
30530 The Real-Time Annex introduces a set of policies that define the behavior of
30531 features that were implementation dependent in Ada 83, such as the order in
30532 which open select branches are executed.
30533 @end table
30534
30535 @node Changed semantics
30536 @subsection Changed semantics
30537
30538 @noindent
30539 The worst kind of incompatibility is one where a program that is legal in
30540 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30541 possible in Ada 83.  Fortunately this is extremely rare, but the one
30542 situation that you should be alert to is the change in the predefined type
30543 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30544
30545 @table @emph
30546 @item Range of type @code{Character}
30547 The range of @code{Standard.Character} is now the full 256 characters
30548 of Latin-1, whereas in most Ada 83 implementations it was restricted
30549 to 128 characters. Although some of the effects of
30550 this change will be manifest in compile-time rejection of legal
30551 Ada 83 programs it is possible for a working Ada 83 program to have
30552 a different effect in Ada 95, one that was not permitted in Ada 83.
30553 As an example, the expression
30554 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30555 delivers @code{255} as its value.
30556 In general, you should look at the logic of any
30557 character-processing Ada 83 program and see whether it needs to be adapted
30558 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
30559 character handling package that may be relevant if code needs to be adapted
30560 to account for the additional Latin-1 elements.
30561 The desirable fix is to
30562 modify the program to accommodate the full character set, but in some cases
30563 it may be convenient to define a subtype or derived type of Character that
30564 covers only the restricted range.
30565 @cindex Latin-1
30566 @end table
30567
30568 @node Other language compatibility issues
30569 @subsection Other language compatibility issues
30570
30571 @table @emph
30572 @item @option{-gnat83} switch
30573 All implementations of GNAT provide a switch that causes GNAT to operate
30574 in Ada 83 mode.  In this mode, some but not all compatibility problems
30575 of the type described above are handled automatically.  For example, the
30576 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30577 as identifiers as in Ada 83.
30578 However,
30579 in practice, it is usually advisable to make the necessary modifications
30580 to the program to remove the need for using this switch.
30581 See @ref{Compiling Different Versions of Ada}.
30582
30583 @item Support for removed Ada 83 pragmas and attributes
30584 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30585 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
30586 compilers are allowed, but not required, to implement these missing
30587 elements.  In contrast with some other compilers, GNAT implements all
30588 such pragmas and attributes, eliminating this compatibility concern.  These
30589 include @code{pragma Interface} and the floating point type attributes
30590 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30591 @end table
30592
30593
30594 @node Compatibility between Ada 95 and Ada 2005
30595 @section Compatibility between Ada 95 and Ada 2005
30596 @cindex Compatibility between Ada 95 and Ada 2005
30597
30598 @noindent
30599 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30600 a number of incompatibilities. Several are enumerated below;
30601 for a complete description please see the
30602 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30603 @cite{Rationale for Ada 2005}.
30604
30605 @table @emph
30606 @item New reserved words.
30607 The words @code{interface}, @code{overriding} and @code{synchronized} are
30608 reserved in Ada 2005.
30609 A pre-Ada 2005 program that uses any of these as an identifier will be
30610 illegal.
30611
30612 @item New declarations in predefined packages.
30613 A number of packages in the predefined environment contain new declarations:
30614 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30615 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30616 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30617 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30618 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30619 If an Ada 95 program does a @code{with} and @code{use} of any of these
30620 packages, the new declarations may cause name clashes.
30621
30622 @item Access parameters.
30623 A nondispatching subprogram with an access parameter cannot be renamed
30624 as a dispatching operation.  This was permitted in Ada 95.
30625
30626 @item Access types, discriminants, and constraints.
30627 Rule changes in this area have led to some incompatibilities; for example,
30628 constrained subtypes of some access types are not permitted in Ada 2005.
30629
30630 @item Aggregates for limited types.
30631 The allowance of aggregates for limited types in Ada 2005 raises the
30632 possibility of ambiguities in legal Ada 95 programs, since additional types
30633 now need to be considered in expression resolution.
30634
30635 @item Fixed-point multiplication and division.
30636 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30637 were legal in Ada 95 and invoked the predefined versions of these operations,
30638 are now ambiguous.
30639 The ambiguity may be resolved either by applying a type conversion to the
30640 expression, or by explicitly invoking the operation from package
30641 @code{Standard}.
30642
30643 @item Return-by-reference types.
30644 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
30645 can declare a function returning a value from an anonymous access type.
30646 @end table
30647
30648
30649 @node Implementation-dependent characteristics
30650 @section Implementation-dependent characteristics
30651 @noindent
30652 Although the Ada language defines the semantics of each construct as
30653 precisely as practical, in some situations (for example for reasons of
30654 efficiency, or where the effect is heavily dependent on the host or target
30655 platform) the implementation is allowed some freedom.  In porting Ada 83
30656 code to GNAT, you need to be aware of whether / how the existing code
30657 exercised such implementation dependencies.  Such characteristics fall into
30658 several categories, and GNAT offers specific support in assisting the
30659 transition from certain Ada 83 compilers.
30660
30661 @menu
30662 * Implementation-defined pragmas::
30663 * Implementation-defined attributes::
30664 * Libraries::
30665 * Elaboration order::
30666 * Target-specific aspects::
30667 @end menu
30668
30669 @node Implementation-defined pragmas
30670 @subsection Implementation-defined pragmas
30671
30672 @noindent
30673 Ada compilers are allowed to supplement the language-defined pragmas, and
30674 these are a potential source of non-portability.  All GNAT-defined pragmas
30675 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30676 Reference Manual}, and these include several that are specifically
30677 intended to correspond to other vendors' Ada 83 pragmas.
30678 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30679 For compatibility with HP Ada 83, GNAT supplies the pragmas
30680 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30681 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30682 and @code{Volatile}.
30683 Other relevant pragmas include @code{External} and @code{Link_With}.
30684 Some vendor-specific
30685 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30686 recognized, thus
30687 avoiding compiler rejection of units that contain such pragmas; they are not
30688 relevant in a GNAT context and hence are not otherwise implemented.
30689
30690 @node Implementation-defined attributes
30691 @subsection Implementation-defined attributes
30692
30693 Analogous to pragmas, the set of attributes may be extended by an
30694 implementation.  All GNAT-defined attributes are described in
30695 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30696 Manual}, and these include several that are specifically intended
30697 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
30698 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
30699 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30700 @code{Type_Class}.
30701
30702 @node Libraries
30703 @subsection Libraries
30704 @noindent
30705 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
30706 code uses vendor-specific libraries then there are several ways to manage
30707 this in Ada 95 or Ada 2005:
30708 @enumerate
30709 @item
30710 If the source code for the libraries (specs and bodies) are
30711 available, then the libraries can be migrated in the same way as the
30712 application.
30713 @item
30714 If the source code for the specs but not the bodies are
30715 available, then you can reimplement the bodies.
30716 @item
30717 Some features introduced by Ada 95 obviate the need for library support.  For
30718 example most Ada 83 vendors supplied a package for unsigned integers.  The
30719 Ada 95 modular type feature is the preferred way to handle this need, so
30720 instead of migrating or reimplementing the unsigned integer package it may
30721 be preferable to retrofit the application using modular types.
30722 @end enumerate
30723
30724 @node Elaboration order
30725 @subsection Elaboration order
30726 @noindent
30727 The implementation can choose any elaboration order consistent with the unit
30728 dependency relationship.  This freedom means that some orders can result in
30729 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30730 to invoke a subprogram its body has been elaborated, or to instantiate a
30731 generic before the generic body has been elaborated.  By default GNAT
30732 attempts to choose a safe order (one that will not encounter access before
30733 elaboration problems) by implicitly inserting @code{Elaborate} or
30734 @code{Elaborate_All} pragmas where
30735 needed.  However, this can lead to the creation of elaboration circularities
30736 and a resulting rejection of the program by gnatbind.  This issue is
30737 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30738 In brief, there are several
30739 ways to deal with this situation:
30740
30741 @itemize @bullet
30742 @item
30743 Modify the program to eliminate the circularities, e.g.@: by moving
30744 elaboration-time code into explicitly-invoked procedures
30745 @item
30746 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30747 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30748 @code{Elaborate_All}
30749 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30750 (by selectively suppressing elaboration checks via pragma
30751 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30752 @end itemize
30753
30754 @node Target-specific aspects
30755 @subsection Target-specific aspects
30756 @noindent
30757 Low-level applications need to deal with machine addresses, data
30758 representations, interfacing with assembler code, and similar issues.  If
30759 such an Ada 83 application is being ported to different target hardware (for
30760 example where the byte endianness has changed) then you will need to
30761 carefully examine the program logic; the porting effort will heavily depend
30762 on the robustness of the original design.  Moreover, Ada 95 (and thus
30763 Ada 2005) are sometimes
30764 incompatible with typical Ada 83 compiler practices regarding implicit
30765 packing, the meaning of the Size attribute, and the size of access values.
30766 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30767
30768 @node Compatibility with Other Ada Systems
30769 @section Compatibility with Other Ada Systems
30770
30771 @noindent
30772 If programs avoid the use of implementation dependent and
30773 implementation defined features, as documented in the @cite{Ada
30774 Reference Manual}, there should be a high degree of portability between
30775 GNAT and other Ada systems.  The following are specific items which
30776 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30777 compilers, but do not affect porting code to GNAT@.
30778 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30779 the following issues may or may not arise for Ada 2005 programs
30780 when other compilers appear.)
30781
30782 @table @emph
30783 @item Ada 83 Pragmas and Attributes
30784 Ada 95 compilers are allowed, but not required, to implement the missing
30785 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30786 GNAT implements all such pragmas and attributes, eliminating this as
30787 a compatibility concern, but some other Ada 95 compilers reject these
30788 pragmas and attributes.
30789
30790 @item Specialized Needs Annexes
30791 GNAT implements the full set of special needs annexes.  At the
30792 current time, it is the only Ada 95 compiler to do so.  This means that
30793 programs making use of these features may not be portable to other Ada
30794 95 compilation systems.
30795
30796 @item Representation Clauses
30797 Some other Ada 95 compilers implement only the minimal set of
30798 representation clauses required by the Ada 95 reference manual.  GNAT goes
30799 far beyond this minimal set, as described in the next section.
30800 @end table
30801
30802 @node Representation Clauses
30803 @section Representation Clauses
30804
30805 @noindent
30806 The Ada 83 reference manual was quite vague in describing both the minimal
30807 required implementation of representation clauses, and also their precise
30808 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
30809 minimal set of capabilities required is still quite limited.
30810
30811 GNAT implements the full required set of capabilities in
30812 Ada 95 and Ada 2005, but also goes much further, and in particular
30813 an effort has been made to be compatible with existing Ada 83 usage to the
30814 greatest extent possible.
30815
30816 A few cases exist in which Ada 83 compiler behavior is incompatible with
30817 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
30818 intentional or accidental dependence on specific implementation dependent
30819 characteristics of these Ada 83 compilers.  The following is a list of
30820 the cases most likely to arise in existing Ada 83 code.
30821
30822 @table @emph
30823 @item Implicit Packing
30824 Some Ada 83 compilers allowed a Size specification to cause implicit
30825 packing of an array or record.  This could cause expensive implicit
30826 conversions for change of representation in the presence of derived
30827 types, and the Ada design intends to avoid this possibility.
30828 Subsequent AI's were issued to make it clear that such implicit
30829 change of representation in response to a Size clause is inadvisable,
30830 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30831 Reference Manuals as implementation advice that is followed by GNAT@.
30832 The problem will show up as an error
30833 message rejecting the size clause.  The fix is simply to provide
30834 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30835 a Component_Size clause.
30836
30837 @item Meaning of Size Attribute
30838 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30839 the minimal number of bits required to hold values of the type.  For example,
30840 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30841 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
30842 some 32 in this situation.  This problem will usually show up as a compile
30843 time error, but not always.  It is a good idea to check all uses of the
30844 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
30845 Object_Size can provide a useful way of duplicating the behavior of
30846 some Ada 83 compiler systems.
30847
30848 @item Size of Access Types
30849 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30850 and that therefore it will be the same size as a System.Address value.  This
30851 assumption is true for GNAT in most cases with one exception.  For the case of
30852 a pointer to an unconstrained array type (where the bounds may vary from one
30853 value of the access type to another), the default is to use a ``fat pointer'',
30854 which is represented as two separate pointers, one to the bounds, and one to
30855 the array.  This representation has a number of advantages, including improved
30856 efficiency.  However, it may cause some difficulties in porting existing Ada 83
30857 code which makes the assumption that, for example, pointers fit in 32 bits on
30858 a machine with 32-bit addressing.
30859
30860 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30861 access types in this case (where the designated type is an unconstrained array
30862 type).  These thin pointers are indeed the same size as a System.Address value.
30863 To specify a thin pointer, use a size clause for the type, for example:
30864
30865 @smallexample @c ada
30866 type X is access all String;
30867 for X'Size use Standard'Address_Size;
30868 @end smallexample
30869
30870 @noindent
30871 which will cause the type X to be represented using a single pointer.
30872 When using this representation, the bounds are right behind the array.
30873 This representation is slightly less efficient, and does not allow quite
30874 such flexibility in the use of foreign pointers or in using the
30875 Unrestricted_Access attribute to create pointers to non-aliased objects.
30876 But for any standard portable use of the access type it will work in
30877 a functionally correct manner and allow porting of existing code.
30878 Note that another way of forcing a thin pointer representation
30879 is to use a component size clause for the element size in an array,
30880 or a record representation clause for an access field in a record.
30881 @end table
30882
30883 @ifclear vms
30884 @c This brief section is only in the non-VMS version
30885 @c The complete chapter on HP Ada is in the VMS version
30886 @node Compatibility with HP Ada 83
30887 @section Compatibility with HP Ada 83
30888
30889 @noindent
30890 The VMS version of GNAT fully implements all the pragmas and attributes
30891 provided by HP Ada 83, as well as providing the standard HP Ada 83
30892 libraries, including Starlet.  In addition, data layouts and parameter
30893 passing conventions are highly compatible.  This means that porting
30894 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30895 most other porting efforts.  The following are some of the most
30896 significant differences between GNAT and HP Ada 83.
30897
30898 @table @emph
30899 @item Default floating-point representation
30900 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30901 it is VMS format.  GNAT does implement the necessary pragmas
30902 (Long_Float, Float_Representation) for changing this default.
30903
30904 @item System
30905 The package System in GNAT exactly corresponds to the definition in the
30906 Ada 95 reference manual, which means that it excludes many of the
30907 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
30908 that contains the additional definitions, and a special pragma,
30909 Extend_System allows this package to be treated transparently as an
30910 extension of package System.
30911
30912 @item To_Address
30913 The definitions provided by Aux_DEC are exactly compatible with those
30914 in the HP Ada 83 version of System, with one exception.
30915 HP Ada provides the following declarations:
30916
30917 @smallexample @c ada
30918 TO_ADDRESS (INTEGER)
30919 TO_ADDRESS (UNSIGNED_LONGWORD)
30920 TO_ADDRESS (@i{universal_integer})
30921 @end smallexample
30922
30923 @noindent
30924 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30925 an extension to Ada 83 not strictly compatible with the reference manual.
30926 In GNAT, we are constrained to be exactly compatible with the standard,
30927 and this means we cannot provide this capability.  In HP Ada 83, the
30928 point of this definition is to deal with a call like:
30929
30930 @smallexample @c ada
30931 TO_ADDRESS (16#12777#);
30932 @end smallexample
30933
30934 @noindent
30935 Normally, according to the Ada 83 standard, one would expect this to be
30936 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30937 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
30938 definition using @i{universal_integer} takes precedence.
30939
30940 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30941 is not possible to be 100% compatible.  Since there are many programs using
30942 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30943 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30944 declarations provided in the GNAT version of AUX_Dec are:
30945
30946 @smallexample @c ada
30947 function To_Address (X : Integer) return Address;
30948 pragma Pure_Function (To_Address);
30949
30950 function To_Address_Long (X : Unsigned_Longword)
30951  return Address;
30952 pragma Pure_Function (To_Address_Long);
30953 @end smallexample
30954
30955 @noindent
30956 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30957 change the name to TO_ADDRESS_LONG@.
30958
30959 @item Task_Id values
30960 The Task_Id values assigned will be different in the two systems, and GNAT
30961 does not provide a specified value for the Task_Id of the environment task,
30962 which in GNAT is treated like any other declared task.
30963 @end table
30964
30965 @noindent
30966 For full details on these and other less significant compatibility issues,
30967 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30968 Overview and Comparison on HP Platforms}.
30969
30970 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30971 attributes are recognized, although only a subset of them can sensibly
30972 be implemented.  The description of pragmas in @ref{Implementation
30973 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30974 indicates whether or not they are applicable to non-VMS systems.
30975 @end ifclear
30976
30977 @ifset vms
30978 @node Transitioning to 64-Bit GNAT for OpenVMS
30979 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30980
30981 @noindent
30982 This section is meant to assist users of pre-2006 @value{EDITION}
30983 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30984 the version of the GNAT technology supplied in 2006 and later for
30985 OpenVMS on both Alpha and I64.
30986
30987 @menu
30988 * Introduction to transitioning::
30989 * Migration of 32 bit code::
30990 * Taking advantage of 64 bit addressing::
30991 * Technical details::
30992 @end menu
30993
30994 @node Introduction to transitioning
30995 @subsection Introduction
30996
30997 @noindent
30998 64-bit @value{EDITION} for Open VMS has been designed to meet
30999 three main goals:
31000
31001 @enumerate
31002 @item
31003 Providing a full conforming implementation of Ada 95 and Ada 2005
31004
31005 @item
31006 Allowing maximum backward compatibility, thus easing migration of existing
31007 Ada source code
31008
31009 @item
31010 Supplying a path for exploiting the full 64-bit address range
31011 @end enumerate
31012
31013 @noindent
31014 Ada's strong typing semantics has made it
31015 impractical to have different 32-bit and 64-bit modes. As soon as
31016 one object could possibly be outside the 32-bit address space, this
31017 would make it necessary for the @code{System.Address} type to be 64 bits.
31018 In particular, this would cause inconsistencies if 32-bit code is
31019 called from 64-bit code that raises an exception.
31020
31021 This issue has been resolved by always using 64-bit addressing
31022 at the system level, but allowing for automatic conversions between
31023 32-bit and 64-bit addresses where required. Thus users who
31024 do not currently require 64-bit addressing capabilities, can
31025 recompile their code with only minimal changes (and indeed
31026 if the code is written in portable Ada, with no assumptions about
31027 the size of the @code{Address} type, then no changes at all are necessary).
31028 At the same time,
31029 this approach provides a simple, gradual upgrade path to future
31030 use of larger memories than available for 32-bit systems.
31031 Also, newly written applications or libraries will by default
31032 be fully compatible with future systems exploiting 64-bit
31033 addressing capabilities.
31034
31035 @ref{Migration of 32 bit code}, will focus on porting applications
31036 that do not require more than 2 GB of
31037 addressable memory. This code will be referred to as
31038 @emph{32-bit code}.
31039 For applications intending to exploit the full 64-bit address space,
31040 @ref{Taking advantage of 64 bit addressing},
31041 will consider further changes that may be required.
31042 Such code will be referred to below as @emph{64-bit code}.
31043
31044 @node Migration of 32 bit code
31045 @subsection Migration of 32-bit code
31046
31047 @menu
31048 * Address types::
31049 * Access types::
31050 * Unchecked conversions::
31051 * Predefined constants::
31052 * Interfacing with C::
31053 * Experience with source compatibility::
31054 @end menu
31055
31056 @node Address types
31057 @subsubsection Address types
31058
31059 @noindent
31060 To solve the problem of mixing 64-bit and 32-bit addressing,
31061 while maintaining maximum backward compatibility, the following
31062 approach has been taken:
31063
31064 @itemize @bullet
31065 @item
31066 @code{System.Address} always has a size of 64 bits
31067
31068 @item
31069 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31070 @end itemize
31071
31072 @noindent
31073 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31074 a @code{Short_Address}
31075 may be used where an @code{Address} is required, and vice versa, without
31076 needing explicit type conversions.
31077 By virtue of the Open VMS parameter passing conventions,
31078 even imported
31079 and exported subprograms that have 32-bit address parameters are
31080 compatible with those that have 64-bit address parameters.
31081 (See @ref{Making code 64 bit clean} for details.)
31082
31083 The areas that may need attention are those where record types have
31084 been defined that contain components of the type @code{System.Address}, and
31085 where objects of this type are passed to code expecting a record layout with
31086 32-bit addresses.
31087
31088 Different compilers on different platforms cannot be
31089 expected to represent the same type in the same way,
31090 since alignment constraints
31091 and other system-dependent properties affect the compiler's decision.
31092 For that reason, Ada code
31093 generally uses representation clauses to specify the expected
31094 layout where required.
31095
31096 If such a representation clause uses 32 bits for a component having
31097 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31098 will detect that error and produce a specific diagnostic message.
31099 The developer should then determine whether the representation
31100 should be 64 bits or not and make either of two changes:
31101 change the size to 64 bits and leave the type as @code{System.Address}, or
31102 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31103 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31104 required in any code setting or accessing the field; the compiler will
31105 automatically perform any needed conversions between address
31106 formats.
31107
31108 @node Access types
31109 @subsubsection Access types
31110
31111 @noindent
31112 By default, objects designated by access values are always
31113 allocated in the 32-bit
31114 address space. Thus legacy code will never contain
31115 any objects that are not addressable with 32-bit addresses, and
31116 the compiler will never raise exceptions as result of mixing
31117 32-bit and 64-bit addresses.
31118
31119 However, the access values themselves are represented in 64 bits, for optimum
31120 performance and future compatibility with 64-bit code. As was
31121 the case with @code{System.Address}, the compiler will give an error message
31122 if an object or record component has a representation clause that
31123 requires the access value to fit in 32 bits. In such a situation,
31124 an explicit size clause for the access type, specifying 32 bits,
31125 will have the desired effect.
31126
31127 General access types (declared with @code{access all}) can never be
31128 32 bits, as values of such types must be able to refer to any object
31129 of the  designated type,
31130 including objects residing outside the 32-bit address range.
31131 Existing Ada 83 code will not contain such type definitions,
31132 however, since general access types were introduced in Ada 95.
31133
31134 @node Unchecked conversions
31135 @subsubsection Unchecked conversions
31136
31137 @noindent
31138 In the case of an @code{Unchecked_Conversion} where the source type is a
31139 64-bit access type or the type @code{System.Address}, and the target
31140 type is a 32-bit type, the compiler will generate a warning.
31141 Even though the generated code will still perform the required
31142 conversions, it is highly recommended in these cases to use
31143 respectively a 32-bit access type or @code{System.Short_Address}
31144 as the source type.
31145
31146 @node Predefined constants
31147 @subsubsection Predefined constants
31148
31149 @noindent
31150 The following table shows the correspondence between pre-2006 versions of
31151 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31152 (``New''):
31153
31154 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31155 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31156 @item   @code{System.Word_Size}          @tab 32      @tab 64
31157 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31158 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31159 @item   @code{System.Address_Size}       @tab 32      @tab 64
31160 @end multitable
31161
31162 @noindent
31163 If you need to refer to the specific
31164 memory size of a 32-bit implementation, instead of the
31165 actual memory size, use @code{System.Short_Memory_Size}
31166 rather than @code{System.Memory_Size}.
31167 Similarly, references to @code{System.Address_Size} may need
31168 to be replaced by @code{System.Short_Address'Size}.
31169 The program @command{gnatfind} may be useful for locating
31170 references to the above constants, so that you can verify that they
31171 are still correct.
31172
31173 @node Interfacing with C
31174 @subsubsection Interfacing with C
31175
31176 @noindent
31177 In order to minimize the impact of the transition to 64-bit addresses on
31178 legacy programs, some fundamental types in the @code{Interfaces.C}
31179 package hierarchy continue to be represented in 32 bits.
31180 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31181 This eases integration with the default HP C layout choices, for example
31182 as found in the system routines in @code{DECC$SHR.EXE}.
31183 Because of this implementation choice, the type fully compatible with
31184 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31185 Depending on the context the compiler will issue a
31186 warning or an error when type @code{Address} is used, alerting the user to a
31187 potential problem. Otherwise 32-bit programs that use
31188 @code{Interfaces.C} should normally not require code modifications
31189
31190 The other issue arising with C interfacing concerns pragma @code{Convention}.
31191 For VMS 64-bit systems, there is an issue of the appropriate default size
31192 of C convention pointers in the absence of an explicit size clause. The HP
31193 C compiler can choose either 32 or 64 bits depending on compiler options.
31194 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31195 clause is given. This proves a better choice for porting 32-bit legacy
31196 applications. In order to have a 64-bit representation, it is necessary to
31197 specify a size representation clause. For example:
31198
31199 @smallexample @c ada
31200 type int_star is access Interfaces.C.int;
31201 pragma Convention(C, int_star);
31202 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31203 @end smallexample
31204
31205 @node Experience with source compatibility
31206 @subsubsection Experience with source compatibility
31207
31208 @noindent
31209 The Security Server and STARLET on I64 provide an interesting ``test case''
31210 for source compatibility issues, since it is in such system code
31211 where assumptions about @code{Address} size might be expected to occur.
31212 Indeed, there were a small number of occasions in the Security Server
31213 file @file{jibdef.ads}
31214 where a representation clause for a record type specified
31215 32 bits for a component of type @code{Address}.
31216 All of these errors were detected by the compiler.
31217 The repair was obvious and immediate; to simply replace @code{Address} by
31218 @code{Short_Address}.
31219
31220 In the case of STARLET, there were several record types that should
31221 have had representation clauses but did not.  In these record types
31222 there was an implicit assumption that an @code{Address} value occupied
31223 32 bits.
31224 These compiled without error, but their usage resulted in run-time error
31225 returns from STARLET system calls.
31226 Future GNAT technology enhancements may include a tool that detects and flags
31227 these sorts of potential source code porting problems.
31228
31229 @c ****************************************
31230 @node Taking advantage of 64 bit addressing
31231 @subsection Taking advantage of 64-bit addressing
31232
31233 @menu
31234 * Making code 64 bit clean::
31235 * Allocating memory from the 64 bit storage pool::
31236 * Restrictions on use of 64 bit objects::
31237 * Using 64 bit storage pools by default::
31238 * General access types::
31239 * STARLET and other predefined libraries::
31240 @end menu
31241
31242 @node Making code 64 bit clean
31243 @subsubsection Making code 64-bit clean
31244
31245 @noindent
31246 In order to prevent problems that may occur when (parts of) a
31247 system start using memory outside the 32-bit address range,
31248 we recommend some additional guidelines:
31249
31250 @itemize @bullet
31251 @item
31252 For imported subprograms that take parameters of the
31253 type @code{System.Address}, ensure that these subprograms can
31254 indeed handle 64-bit addresses. If not, or when in doubt,
31255 change the subprogram declaration to specify
31256 @code{System.Short_Address} instead.
31257
31258 @item
31259 Resolve all warnings related to size mismatches in
31260 unchecked conversions. Failing to do so causes
31261 erroneous execution if the source object is outside
31262 the 32-bit address space.
31263
31264 @item
31265 (optional) Explicitly use the 32-bit storage pool
31266 for access types used in a 32-bit context, or use
31267 generic access types where possible
31268 (@pxref{Restrictions on use of 64 bit objects}).
31269 @end itemize
31270
31271 @noindent
31272 If these rules are followed, the compiler will automatically insert
31273 any necessary checks to ensure that no addresses or access values
31274 passed to 32-bit code ever refer to objects outside the 32-bit
31275 address range.
31276 Any attempt to do this will raise @code{Constraint_Error}.
31277
31278 @node Allocating memory from the 64 bit storage pool
31279 @subsubsection Allocating memory from the 64-bit storage pool
31280
31281 @noindent
31282 For any access type @code{T} that potentially requires memory allocations
31283 beyond the 32-bit address space,
31284 use the following representation clause:
31285
31286 @smallexample @c ada
31287    for T'Storage_Pool use System.Pool_64;
31288 @end smallexample
31289
31290 @node Restrictions on use of 64 bit objects
31291 @subsubsection Restrictions on use of 64-bit objects
31292
31293 @noindent
31294 Taking the address of an object allocated from a 64-bit storage pool,
31295 and then passing this address to a subprogram expecting
31296 @code{System.Short_Address},
31297 or assigning it to a variable of type @code{Short_Address}, will cause
31298 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31299 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31300 no exception is raised and execution
31301 will become erroneous.
31302
31303 @node Using 64 bit storage pools by default
31304 @subsubsection Using 64-bit storage pools by default
31305
31306 @noindent
31307 In some cases it may be desirable to have the compiler allocate
31308 from 64-bit storage pools by default. This may be the case for
31309 libraries that are 64-bit clean, but may be used in both 32-bit
31310 and 64-bit contexts. For these cases the following configuration
31311 pragma may be specified:
31312
31313 @smallexample @c ada
31314   pragma Pool_64_Default;
31315 @end smallexample
31316
31317 @noindent
31318 Any code compiled in the context of this pragma will by default
31319 use the @code{System.Pool_64} storage pool. This default may be overridden
31320 for a specific access type @code{T} by the representation clause:
31321
31322 @smallexample @c ada
31323    for T'Storage_Pool use System.Pool_32;
31324 @end smallexample
31325
31326 @noindent
31327 Any object whose address may be passed to a subprogram with a
31328 @code{Short_Address} argument, or assigned to a variable of type
31329 @code{Short_Address}, needs to be allocated from this pool.
31330
31331 @node General access types
31332 @subsubsection General access types
31333
31334 @noindent
31335 Objects designated by access values from a
31336 general access type (declared with @code{access all}) are never allocated
31337 from a 64-bit storage pool. Code that uses general access types will
31338 accept objects allocated in either 32-bit or 64-bit address spaces,
31339 but never allocate objects outside the 32-bit address space.
31340 Using general access types ensures maximum compatibility with both
31341 32-bit and 64-bit code.
31342
31343 @node STARLET and other predefined libraries
31344 @subsubsection STARLET and other predefined libraries
31345
31346 @noindent
31347 All code that comes as part of GNAT is 64-bit clean, but the
31348 restrictions given in @ref{Restrictions on use of 64 bit objects},
31349 still apply. Look at the package
31350 specs to see in which contexts objects allocated
31351 in 64-bit address space are acceptable.
31352
31353 @node Technical details
31354 @subsection Technical details
31355
31356 @noindent
31357 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31358 Ada standard with respect to the type of @code{System.Address}. Previous
31359 versions of GNAT Pro have defined this type as private and implemented it as a
31360 modular type.
31361
31362 In order to allow defining @code{System.Short_Address} as a proper subtype,
31363 and to match the implicit sign extension in parameter passing,
31364 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31365 visible (i.e., non-private) integer type.
31366 Standard operations on the type, such as the binary operators ``+'', ``-'',
31367 etc., that take @code{Address} operands and return an @code{Address} result,
31368 have been hidden by declaring these
31369 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31370 ambiguities that would otherwise result from overloading.
31371 (Note that, although @code{Address} is a visible integer type,
31372 good programming practice dictates against exploiting the type's
31373 integer properties such as literals, since this will compromise
31374 code portability.)
31375
31376 Defining @code{Address} as a visible integer type helps achieve
31377 maximum compatibility for existing Ada code,
31378 without sacrificing the capabilities of the 64-bit architecture.
31379 @end ifset
31380
31381 @c ************************************************
31382 @ifset unw
31383 @node Microsoft Windows Topics
31384 @appendix Microsoft Windows Topics
31385 @cindex Windows NT
31386 @cindex Windows 95
31387 @cindex Windows 98
31388
31389 @noindent
31390 This chapter describes topics that are specific to the Microsoft Windows
31391 platforms (NT, 2000, and XP Professional).
31392
31393 @menu
31394 * Using GNAT on Windows::
31395 * Using a network installation of GNAT::
31396 * CONSOLE and WINDOWS subsystems::
31397 * Temporary Files::
31398 * Mixed-Language Programming on Windows::
31399 * Windows Calling Conventions::
31400 * Introduction to Dynamic Link Libraries (DLLs)::
31401 * Using DLLs with GNAT::
31402 * Building DLLs with GNAT::
31403 * Building DLLs with GNAT Project files::
31404 * Building DLLs with gnatdll::
31405 * GNAT and Windows Resources::
31406 * Debugging a DLL::
31407 * Setting Stack Size from gnatlink::
31408 * Setting Heap Size from gnatlink::
31409 @end menu
31410
31411 @node Using GNAT on Windows
31412 @section Using GNAT on Windows
31413
31414 @noindent
31415 One of the strengths of the GNAT technology is that its tool set
31416 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31417 @code{gdb} debugger, etc.) is used in the same way regardless of the
31418 platform.
31419
31420 On Windows this tool set is complemented by a number of Microsoft-specific
31421 tools that have been provided to facilitate interoperability with Windows
31422 when this is required. With these tools:
31423
31424 @itemize @bullet
31425
31426 @item
31427 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31428 subsystems.
31429
31430 @item
31431 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31432 relocatable and non-relocatable DLLs are supported).
31433
31434 @item
31435 You can build Ada DLLs for use in other applications. These applications
31436 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31437 relocatable and non-relocatable Ada DLLs are supported.
31438
31439 @item
31440 You can include Windows resources in your Ada application.
31441
31442 @item
31443 You can use or create COM/DCOM objects.
31444 @end itemize
31445
31446 @noindent
31447 Immediately below are listed all known general GNAT-for-Windows restrictions.
31448 Other restrictions about specific features like Windows Resources and DLLs
31449 are listed in separate sections below.
31450
31451 @itemize @bullet
31452
31453 @item
31454 It is not possible to use @code{GetLastError} and @code{SetLastError}
31455 when tasking, protected records, or exceptions are used. In these
31456 cases, in order to implement Ada semantics, the GNAT run-time system
31457 calls certain Win32 routines that set the last error variable to 0 upon
31458 success. It should be possible to use @code{GetLastError} and
31459 @code{SetLastError} when tasking, protected record, and exception
31460 features are not used, but it is not guaranteed to work.
31461
31462 @item
31463 It is not possible to link against Microsoft libraries except for
31464 import libraries. The library must be built to be compatible with
31465 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31466 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31467 not be compatible with the GNAT runtime. Even if the library is
31468 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31469
31470 @item
31471 When the compilation environment is located on FAT32 drives, users may
31472 experience recompilations of the source files that have not changed if
31473 Daylight Saving Time (DST) state has changed since the last time files
31474 were compiled. NTFS drives do not have this problem.
31475
31476 @item
31477 No components of the GNAT toolset use any entries in the Windows
31478 registry. The only entries that can be created are file associations and
31479 PATH settings, provided the user has chosen to create them at installation
31480 time, as well as some minimal book-keeping information needed to correctly
31481 uninstall or integrate different GNAT products.
31482 @end itemize
31483
31484 @node Using a network installation of GNAT
31485 @section Using a network installation of GNAT
31486
31487 @noindent
31488 Make sure the system on which GNAT is installed is accessible from the
31489 current machine, i.e., the install location is shared over the network.
31490 Shared resources are accessed on Windows by means of UNC paths, which
31491 have the format @code{\\server\sharename\path}
31492
31493 In order to use such a network installation, simply add the UNC path of the
31494 @file{bin} directory of your GNAT installation in front of your PATH. For
31495 example, if GNAT is installed in @file{\GNAT} directory of a share location
31496 called @file{c-drive} on a machine @file{LOKI}, the following command will
31497 make it available:
31498
31499 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31500
31501 Be aware that every compilation using the network installation results in the
31502 transfer of large amounts of data across the network and will likely cause
31503 serious performance penalty.
31504
31505 @node CONSOLE and WINDOWS subsystems
31506 @section CONSOLE and WINDOWS subsystems
31507 @cindex CONSOLE Subsystem
31508 @cindex WINDOWS Subsystem
31509 @cindex -mwindows
31510
31511 @noindent
31512 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31513 (which is the default subsystem) will always create a console when
31514 launching the application. This is not something desirable when the
31515 application has a Windows GUI. To get rid of this console the
31516 application must be using the @code{WINDOWS} subsystem. To do so
31517 the @option{-mwindows} linker option must be specified.
31518
31519 @smallexample
31520 $ gnatmake winprog -largs -mwindows
31521 @end smallexample
31522
31523 @node Temporary Files
31524 @section Temporary Files
31525 @cindex Temporary files
31526
31527 @noindent
31528 It is possible to control where temporary files gets created by setting
31529 the @env{TMP} environment variable. The file will be created:
31530
31531 @itemize
31532 @item Under the directory pointed to by the @env{TMP} environment variable if
31533 this directory exists.
31534
31535 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31536 set (or not pointing to a directory) and if this directory exists.
31537
31538 @item Under the current working directory otherwise.
31539 @end itemize
31540
31541 @noindent
31542 This allows you to determine exactly where the temporary
31543 file will be created. This is particularly useful in networked
31544 environments where you may not have write access to some
31545 directories.
31546
31547 @node Mixed-Language Programming on Windows
31548 @section Mixed-Language Programming on Windows
31549
31550 @noindent
31551 Developing pure Ada applications on Windows is no different than on
31552 other GNAT-supported platforms. However, when developing or porting an
31553 application that contains a mix of Ada and C/C++, the choice of your
31554 Windows C/C++ development environment conditions your overall
31555 interoperability strategy.
31556
31557 If you use @command{gcc} to compile the non-Ada part of your application,
31558 there are no Windows-specific restrictions that affect the overall
31559 interoperability with your Ada code. If you plan to use
31560 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31561 the following limitations:
31562
31563 @itemize @bullet
31564 @item
31565 You cannot link your Ada code with an object or library generated with
31566 Microsoft tools if these use the @code{.tls} section (Thread Local
31567 Storage section) since the GNAT linker does not yet support this section.
31568
31569 @item
31570 You cannot link your Ada code with an object or library generated with
31571 Microsoft tools if these use I/O routines other than those provided in
31572 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31573 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31574 libraries can cause a conflict with @code{msvcrt.dll} services. For
31575 instance Visual C++ I/O stream routines conflict with those in
31576 @code{msvcrt.dll}.
31577 @end itemize
31578
31579 @noindent
31580 If you do want to use the Microsoft tools for your non-Ada code and hit one
31581 of the above limitations, you have two choices:
31582
31583 @enumerate
31584 @item
31585 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31586 application. In this case, use the Microsoft or whatever environment to
31587 build the DLL and use GNAT to build your executable
31588 (@pxref{Using DLLs with GNAT}).
31589
31590 @item
31591 Or you can encapsulate your Ada code in a DLL to be linked with the
31592 other part of your application. In this case, use GNAT to build the DLL
31593 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31594 environment to build your executable.
31595 @end enumerate
31596
31597 @node Windows Calling Conventions
31598 @section Windows Calling Conventions
31599 @findex Stdcall
31600 @findex APIENTRY
31601
31602 @menu
31603 * C Calling Convention::
31604 * Stdcall Calling Convention::
31605 * Win32 Calling Convention::
31606 * DLL Calling Convention::
31607 @end menu
31608
31609 @noindent
31610 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31611 (callee), there are several ways to push @code{G}'s parameters on the
31612 stack and there are several possible scenarios to clean up the stack
31613 upon @code{G}'s return. A calling convention is an agreed upon software
31614 protocol whereby the responsibilities between the caller (@code{F}) and
31615 the callee (@code{G}) are clearly defined. Several calling conventions
31616 are available for Windows:
31617
31618 @itemize @bullet
31619 @item
31620 @code{C} (Microsoft defined)
31621
31622 @item
31623 @code{Stdcall} (Microsoft defined)
31624
31625 @item
31626 @code{Win32} (GNAT specific)
31627
31628 @item
31629 @code{DLL} (GNAT specific)
31630 @end itemize
31631
31632 @node C Calling Convention
31633 @subsection @code{C} Calling Convention
31634
31635 @noindent
31636 This is the default calling convention used when interfacing to C/C++
31637 routines compiled with either @command{gcc} or Microsoft Visual C++.
31638
31639 In the @code{C} calling convention subprogram parameters are pushed on the
31640 stack by the caller from right to left. The caller itself is in charge of
31641 cleaning up the stack after the call. In addition, the name of a routine
31642 with @code{C} calling convention is mangled by adding a leading underscore.
31643
31644 The name to use on the Ada side when importing (or exporting) a routine
31645 with @code{C} calling convention is the name of the routine. For
31646 instance the C function:
31647
31648 @smallexample
31649 int get_val (long);
31650 @end smallexample
31651
31652 @noindent
31653 should be imported from Ada as follows:
31654
31655 @smallexample @c ada
31656 @group
31657 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31658 pragma Import (C, Get_Val, External_Name => "get_val");
31659 @end group
31660 @end smallexample
31661
31662 @noindent
31663 Note that in this particular case the @code{External_Name} parameter could
31664 have been omitted since, when missing, this parameter is taken to be the
31665 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31666 is missing, as in the above example, this parameter is set to be the
31667 @code{External_Name} with a leading underscore.
31668
31669 When importing a variable defined in C, you should always use the @code{C}
31670 calling convention unless the object containing the variable is part of a
31671 DLL (in which case you should use the @code{Stdcall} calling
31672 convention, @pxref{Stdcall Calling Convention}).
31673
31674 @node Stdcall Calling Convention
31675 @subsection @code{Stdcall} Calling Convention
31676
31677 @noindent
31678 This convention, which was the calling convention used for Pascal
31679 programs, is used by Microsoft for all the routines in the Win32 API for
31680 efficiency reasons. It must be used to import any routine for which this
31681 convention was specified.
31682
31683 In the @code{Stdcall} calling convention subprogram parameters are pushed
31684 on the stack by the caller from right to left. The callee (and not the
31685 caller) is in charge of cleaning the stack on routine exit. In addition,
31686 the name of a routine with @code{Stdcall} calling convention is mangled by
31687 adding a leading underscore (as for the @code{C} calling convention) and a
31688 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31689 bytes) of the parameters passed to the routine.
31690
31691 The name to use on the Ada side when importing a C routine with a
31692 @code{Stdcall} calling convention is the name of the C routine. The leading
31693 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31694 the compiler. For instance the Win32 function:
31695
31696 @smallexample
31697 @b{APIENTRY} int get_val (long);
31698 @end smallexample
31699
31700 @noindent
31701 should be imported from Ada as follows:
31702
31703 @smallexample @c ada
31704 @group
31705 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31706 pragma Import (Stdcall, Get_Val);
31707 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31708 @end group
31709 @end smallexample
31710
31711 @noindent
31712 As for the @code{C} calling convention, when the @code{External_Name}
31713 parameter is missing, it is taken to be the name of the Ada entity in lower
31714 case. If instead of writing the above import pragma you write:
31715
31716 @smallexample @c ada
31717 @group
31718 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31719 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31720 @end group
31721 @end smallexample
31722
31723 @noindent
31724 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31725 of specifying the @code{External_Name} parameter you specify the
31726 @code{Link_Name} as in the following example:
31727
31728 @smallexample @c ada
31729 @group
31730 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31731 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31732 @end group
31733 @end smallexample
31734
31735 @noindent
31736 then the imported routine is @code{retrieve_val}, that is, there is no
31737 decoration at all. No leading underscore and no Stdcall suffix
31738 @code{@@}@code{@var{nn}}.
31739
31740 @noindent
31741 This is especially important as in some special cases a DLL's entry
31742 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31743 name generated for a call has it.
31744
31745 @noindent
31746 It is also possible to import variables defined in a DLL by using an
31747 import pragma for a variable. As an example, if a DLL contains a
31748 variable defined as:
31749
31750 @smallexample
31751 int my_var;
31752 @end smallexample
31753
31754 @noindent
31755 then, to access this variable from Ada you should write:
31756
31757 @smallexample @c ada
31758 @group
31759 My_Var : Interfaces.C.int;
31760 pragma Import (Stdcall, My_Var);
31761 @end group
31762 @end smallexample
31763
31764 @noindent
31765 Note that to ease building cross-platform bindings this convention
31766 will be handled as a @code{C} calling convention on non-Windows platforms.
31767
31768 @node Win32 Calling Convention
31769 @subsection @code{Win32} Calling Convention
31770
31771 @noindent
31772 This convention, which is GNAT-specific is fully equivalent to the
31773 @code{Stdcall} calling convention described above.
31774
31775 @node DLL Calling Convention
31776 @subsection @code{DLL} Calling Convention
31777
31778 @noindent
31779 This convention, which is GNAT-specific is fully equivalent to the
31780 @code{Stdcall} calling convention described above.
31781
31782 @node Introduction to Dynamic Link Libraries (DLLs)
31783 @section Introduction to Dynamic Link Libraries (DLLs)
31784 @findex DLL
31785
31786 @noindent
31787 A Dynamically Linked Library (DLL) is a library that can be shared by
31788 several applications running under Windows. A DLL can contain any number of
31789 routines and variables.
31790
31791 One advantage of DLLs is that you can change and enhance them without
31792 forcing all the applications that depend on them to be relinked or
31793 recompiled. However, you should be aware than all calls to DLL routines are
31794 slower since, as you will understand below, such calls are indirect.
31795
31796 To illustrate the remainder of this section, suppose that an application
31797 wants to use the services of a DLL @file{API.dll}. To use the services
31798 provided by @file{API.dll} you must statically link against the DLL or
31799 an import library which contains a jump table with an entry for each
31800 routine and variable exported by the DLL. In the Microsoft world this
31801 import library is called @file{API.lib}. When using GNAT this import
31802 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31803 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31804
31805 After you have linked your application with the DLL or the import library
31806 and you run your application, here is what happens:
31807
31808 @enumerate
31809 @item
31810 Your application is loaded into memory.
31811
31812 @item
31813 The DLL @file{API.dll} is mapped into the address space of your
31814 application. This means that:
31815
31816 @itemize @bullet
31817 @item
31818 The DLL will use the stack of the calling thread.
31819
31820 @item
31821 The DLL will use the virtual address space of the calling process.
31822
31823 @item
31824 The DLL will allocate memory from the virtual address space of the calling
31825 process.
31826
31827 @item
31828 Handles (pointers) can be safely exchanged between routines in the DLL
31829 routines and routines in the application using the DLL.
31830 @end itemize
31831
31832 @item
31833 The entries in the jump table (from the import library @file{libAPI.dll.a}
31834 or @file{API.lib} or automatically created when linking against a DLL)
31835 which is part of your application are initialized with the addresses
31836 of the routines and variables in @file{API.dll}.
31837
31838 @item
31839 If present in @file{API.dll}, routines @code{DllMain} or
31840 @code{DllMainCRTStartup} are invoked. These routines typically contain
31841 the initialization code needed for the well-being of the routines and
31842 variables exported by the DLL.
31843 @end enumerate
31844
31845 @noindent
31846 There is an additional point which is worth mentioning. In the Windows
31847 world there are two kind of DLLs: relocatable and non-relocatable
31848 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31849 in the target application address space. If the addresses of two
31850 non-relocatable DLLs overlap and these happen to be used by the same
31851 application, a conflict will occur and the application will run
31852 incorrectly. Hence, when possible, it is always preferable to use and
31853 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31854 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31855 User's Guide) removes the debugging symbols from the DLL but the DLL can
31856 still be relocated.
31857
31858 As a side note, an interesting difference between Microsoft DLLs and
31859 Unix shared libraries, is the fact that on most Unix systems all public
31860 routines are exported by default in a Unix shared library, while under
31861 Windows it is possible (but not required) to list exported routines in
31862 a definition file (@pxref{The Definition File}).
31863
31864 @node Using DLLs with GNAT
31865 @section Using DLLs with GNAT
31866
31867 @menu
31868 * Creating an Ada Spec for the DLL Services::
31869 * Creating an Import Library::
31870 @end menu
31871
31872 @noindent
31873 To use the services of a DLL, say @file{API.dll}, in your Ada application
31874 you must have:
31875
31876 @enumerate
31877 @item
31878 The Ada spec for the routines and/or variables you want to access in
31879 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31880 header files provided with the DLL.
31881
31882 @item
31883 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31884 mentioned an import library is a statically linked library containing the
31885 import table which will be filled at load time to point to the actual
31886 @file{API.dll} routines. Sometimes you don't have an import library for the
31887 DLL you want to use. The following sections will explain how to build
31888 one. Note that this is optional.
31889
31890 @item
31891 The actual DLL, @file{API.dll}.
31892 @end enumerate
31893
31894 @noindent
31895 Once you have all the above, to compile an Ada application that uses the
31896 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31897 you simply issue the command
31898
31899 @smallexample
31900 $ gnatmake my_ada_app -largs -lAPI
31901 @end smallexample
31902
31903 @noindent
31904 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31905 tells the GNAT linker to look first for a library named @file{API.lib}
31906 (Microsoft-style name) and if not found for a libraries named
31907 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31908 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31909 contains the following pragma
31910
31911 @smallexample @c ada
31912 pragma Linker_Options ("-lAPI");
31913 @end smallexample
31914
31915 @noindent
31916 you do not have to add @option{-largs -lAPI} at the end of the
31917 @command{gnatmake} command.
31918
31919 If any one of the items above is missing you will have to create it
31920 yourself. The following sections explain how to do so using as an
31921 example a fictitious DLL called @file{API.dll}.
31922
31923 @node Creating an Ada Spec for the DLL Services
31924 @subsection Creating an Ada Spec for the DLL Services
31925
31926 @noindent
31927 A DLL typically comes with a C/C++ header file which provides the
31928 definitions of the routines and variables exported by the DLL. The Ada
31929 equivalent of this header file is a package spec that contains definitions
31930 for the imported entities. If the DLL you intend to use does not come with
31931 an Ada spec you have to generate one such spec yourself. For example if
31932 the header file of @file{API.dll} is a file @file{api.h} containing the
31933 following two definitions:
31934
31935 @smallexample
31936 @group
31937 @cartouche
31938 int some_var;
31939 int get (char *);
31940 @end cartouche
31941 @end group
31942 @end smallexample
31943
31944 @noindent
31945 then the equivalent Ada spec could be:
31946
31947 @smallexample @c ada
31948 @group
31949 @cartouche
31950 with Interfaces.C.Strings;
31951 package API is
31952    use Interfaces;
31953
31954    Some_Var : C.int;
31955    function Get (Str : C.Strings.Chars_Ptr) return C.int;
31956
31957 private
31958    pragma Import (C, Get);
31959    pragma Import (DLL, Some_Var);
31960 end API;
31961 @end cartouche
31962 @end group
31963 @end smallexample
31964
31965 @noindent
31966 Note that a variable is
31967 @strong{always imported with a Stdcall convention}. A function
31968 can have @code{C} or @code{Stdcall} convention.
31969 (@pxref{Windows Calling Conventions}).
31970
31971 @node Creating an Import Library
31972 @subsection Creating an Import Library
31973 @cindex Import library
31974
31975 @menu
31976 * The Definition File::
31977 * GNAT-Style Import Library::
31978 * Microsoft-Style Import Library::
31979 @end menu
31980
31981 @noindent
31982 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31983 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31984 with @file{API.dll} you can skip this section. You can also skip this
31985 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31986 as in this case it is possible to link directly against the
31987 DLL. Otherwise read on.
31988
31989 @node The Definition File
31990 @subsubsection The Definition File
31991 @cindex Definition file
31992 @findex .def
31993
31994 @noindent
31995 As previously mentioned, and unlike Unix systems, the list of symbols
31996 that are exported from a DLL must be provided explicitly in Windows.
31997 The main goal of a definition file is precisely that: list the symbols
31998 exported by a DLL. A definition file (usually a file with a @code{.def}
31999 suffix) has the following structure:
32000
32001 @smallexample
32002 @group
32003 @cartouche
32004 @r{[}LIBRARY @var{name}@r{]}
32005 @r{[}DESCRIPTION @var{string}@r{]}
32006 EXPORTS
32007    @var{symbol1}
32008    @var{symbol2}
32009    @dots{}
32010 @end cartouche
32011 @end group
32012 @end smallexample
32013
32014 @table @code
32015 @item LIBRARY @var{name}
32016 This section, which is optional, gives the name of the DLL.
32017
32018 @item DESCRIPTION @var{string}
32019 This section, which is optional, gives a description string that will be
32020 embedded in the import library.
32021
32022 @item EXPORTS
32023 This section gives the list of exported symbols (procedures, functions or
32024 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32025 section of @file{API.def} looks like:
32026
32027 @smallexample
32028 @group
32029 @cartouche
32030 EXPORTS
32031    some_var
32032    get
32033 @end cartouche
32034 @end group
32035 @end smallexample
32036 @end table
32037
32038 @noindent
32039 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32040 (@pxref{Windows Calling Conventions}) for a Stdcall
32041 calling convention function in the exported symbols list.
32042
32043 @noindent
32044 There can actually be other sections in a definition file, but these
32045 sections are not relevant to the discussion at hand.
32046
32047 @node GNAT-Style Import Library
32048 @subsubsection GNAT-Style Import Library
32049
32050 @noindent
32051 To create a static import library from @file{API.dll} with the GNAT tools
32052 you should proceed as follows:
32053
32054 @enumerate
32055 @item
32056 Create the definition file @file{API.def} (@pxref{The Definition File}).
32057 For that use the @code{dll2def} tool as follows:
32058
32059 @smallexample
32060 $ dll2def API.dll > API.def
32061 @end smallexample
32062
32063 @noindent
32064 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32065 to standard output the list of entry points in the DLL. Note that if
32066 some routines in the DLL have the @code{Stdcall} convention
32067 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32068 suffix then you'll have to edit @file{api.def} to add it, and specify
32069 @option{-k} to @command{gnatdll} when creating the import library.
32070
32071 @noindent
32072 Here are some hints to find the right @code{@@}@var{nn} suffix.
32073
32074 @enumerate
32075 @item
32076 If you have the Microsoft import library (.lib), it is possible to get
32077 the right symbols by using Microsoft @code{dumpbin} tool (see the
32078 corresponding Microsoft documentation for further details).
32079
32080 @smallexample
32081 $ dumpbin /exports api.lib
32082 @end smallexample
32083
32084 @item
32085 If you have a message about a missing symbol at link time the compiler
32086 tells you what symbol is expected. You just have to go back to the
32087 definition file and add the right suffix.
32088 @end enumerate
32089
32090 @item
32091 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32092 (@pxref{Using gnatdll}) as follows:
32093
32094 @smallexample
32095 $ gnatdll -e API.def -d API.dll
32096 @end smallexample
32097
32098 @noindent
32099 @code{gnatdll} takes as input a definition file @file{API.def} and the
32100 name of the DLL containing the services listed in the definition file
32101 @file{API.dll}. The name of the static import library generated is
32102 computed from the name of the definition file as follows: if the
32103 definition file name is @var{xyz}@code{.def}, the import library name will
32104 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32105 @option{-e} could have been removed because the name of the definition
32106 file (before the ``@code{.def}'' suffix) is the same as the name of the
32107 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32108 @end enumerate
32109
32110 @node Microsoft-Style Import Library
32111 @subsubsection Microsoft-Style Import Library
32112
32113 @noindent
32114 With GNAT you can either use a GNAT-style or Microsoft-style import
32115 library. A Microsoft import library is needed only if you plan to make an
32116 Ada DLL available to applications developed with Microsoft
32117 tools (@pxref{Mixed-Language Programming on Windows}).
32118
32119 To create a Microsoft-style import library for @file{API.dll} you
32120 should proceed as follows:
32121
32122 @enumerate
32123 @item
32124 Create the definition file @file{API.def} from the DLL. For this use either
32125 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32126 tool (see the corresponding Microsoft documentation for further details).
32127
32128 @item
32129 Build the actual import library using Microsoft's @code{lib} utility:
32130
32131 @smallexample
32132 $ lib -machine:IX86 -def:API.def -out:API.lib
32133 @end smallexample
32134
32135 @noindent
32136 If you use the above command the definition file @file{API.def} must
32137 contain a line giving the name of the DLL:
32138
32139 @smallexample
32140 LIBRARY      "API"
32141 @end smallexample
32142
32143 @noindent
32144 See the Microsoft documentation for further details about the usage of
32145 @code{lib}.
32146 @end enumerate
32147
32148 @node Building DLLs with GNAT
32149 @section Building DLLs with GNAT
32150 @cindex DLLs, building
32151
32152 @noindent
32153 This section explain how to build DLLs using the GNAT built-in DLL
32154 support. With the following procedure it is straight forward to build
32155 and use DLLs with GNAT.
32156
32157 @enumerate
32158
32159 @item building object files
32160
32161 The first step is to build all objects files that are to be included
32162 into the DLL. This is done by using the standard @command{gnatmake} tool.
32163
32164 @item building the DLL
32165
32166 To build the DLL you must use @command{gcc}'s @option{-shared}
32167 option. It is quite simple to use this method:
32168
32169 @smallexample
32170 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32171 @end smallexample
32172
32173 It is important to note that in this case all symbols found in the
32174 object files are automatically exported. It is possible to restrict
32175 the set of symbols to export by passing to @command{gcc} a definition
32176 file, @pxref{The Definition File}. For example:
32177
32178 @smallexample
32179 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32180 @end smallexample
32181
32182 If you use a definition file you must export the elaboration procedures
32183 for every package that required one. Elaboration procedures are named
32184 using the package name followed by "_E".
32185
32186 @item preparing DLL to be used
32187
32188 For the DLL to be used by client programs the bodies must be hidden
32189 from it and the .ali set with read-only attribute. This is very important
32190 otherwise GNAT will recompile all packages and will not actually use
32191 the code in the DLL. For example:
32192
32193 @smallexample
32194 $ mkdir apilib
32195 $ copy *.ads *.ali api.dll apilib
32196 $ attrib +R apilib\*.ali
32197 @end smallexample
32198
32199 @end enumerate
32200
32201 At this point it is possible to use the DLL by directly linking
32202 against it. Note that you must use the GNAT shared runtime when using
32203 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32204 option.
32205
32206 @smallexample
32207 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32208 @end smallexample
32209
32210 @node Building DLLs with GNAT Project files
32211 @section Building DLLs with GNAT Project files
32212 @cindex DLLs, building
32213
32214 @noindent
32215 There is nothing specific to Windows in the build process.
32216 @pxref{Library Projects}.
32217
32218 @noindent
32219 Due to a system limitation, it is not possible under Windows to create threads
32220 when inside the @code{DllMain} routine which is used for auto-initialization
32221 of shared libraries, so it is not possible to have library level tasks in SALs.
32222
32223 @node Building DLLs with gnatdll
32224 @section Building DLLs with gnatdll
32225 @cindex DLLs, building
32226
32227 @menu
32228 * Limitations When Using Ada DLLs from Ada::
32229 * Exporting Ada Entities::
32230 * Ada DLLs and Elaboration::
32231 * Ada DLLs and Finalization::
32232 * Creating a Spec for Ada DLLs::
32233 * Creating the Definition File::
32234 * Using gnatdll::
32235 @end menu
32236
32237 @noindent
32238 Note that it is preferred to use the built-in GNAT DLL support
32239 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32240 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32241
32242 This section explains how to build DLLs containing Ada code using
32243 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32244 remainder of this section.
32245
32246 The steps required to build an Ada DLL that is to be used by Ada as well as
32247 non-Ada applications are as follows:
32248
32249 @enumerate
32250 @item
32251 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32252 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32253 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32254 skip this step if you plan to use the Ada DLL only from Ada applications.
32255
32256 @item
32257 Your Ada code must export an initialization routine which calls the routine
32258 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32259 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32260 routine exported by the Ada DLL must be invoked by the clients of the DLL
32261 to initialize the DLL.
32262
32263 @item
32264 When useful, the DLL should also export a finalization routine which calls
32265 routine @code{adafinal} generated by @command{gnatbind} to perform the
32266 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32267 The finalization routine exported by the Ada DLL must be invoked by the
32268 clients of the DLL when the DLL services are no further needed.
32269
32270 @item
32271 You must provide a spec for the services exported by the Ada DLL in each
32272 of the programming languages to which you plan to make the DLL available.
32273
32274 @item
32275 You must provide a definition file listing the exported entities
32276 (@pxref{The Definition File}).
32277
32278 @item
32279 Finally you must use @code{gnatdll} to produce the DLL and the import
32280 library (@pxref{Using gnatdll}).
32281 @end enumerate
32282
32283 @noindent
32284 Note that a relocatable DLL stripped using the @code{strip}
32285 binutils tool will not be relocatable anymore. To build a DLL without
32286 debug information pass @code{-largs -s} to @code{gnatdll}. This
32287 restriction does not apply to a DLL built using a Library Project.
32288 @pxref{Library Projects}.
32289
32290 @node Limitations When Using Ada DLLs from Ada
32291 @subsection Limitations When Using Ada DLLs from Ada
32292
32293 @noindent
32294 When using Ada DLLs from Ada applications there is a limitation users
32295 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32296 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32297 each Ada DLL includes the services of the GNAT run time that are necessary
32298 to the Ada code inside the DLL. As a result, when an Ada program uses an
32299 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32300 one in the main program.
32301
32302 It is therefore not possible to exchange GNAT run-time objects between the
32303 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32304 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32305 types, etc.
32306
32307 It is completely safe to exchange plain elementary, array or record types,
32308 Windows object handles, etc.
32309
32310 @node Exporting Ada Entities
32311 @subsection Exporting Ada Entities
32312 @cindex Export table
32313
32314 @noindent
32315 Building a DLL is a way to encapsulate a set of services usable from any
32316 application. As a result, the Ada entities exported by a DLL should be
32317 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32318 any Ada name mangling. As an example here is an Ada package
32319 @code{API}, spec and body, exporting two procedures, a function, and a
32320 variable:
32321
32322 @smallexample @c ada
32323 @group
32324 @cartouche
32325 with Interfaces.C; use Interfaces;
32326 package API is
32327    Count : C.int := 0;
32328    function Factorial (Val : C.int) return C.int;
32329
32330    procedure Initialize_API;
32331    procedure Finalize_API;
32332    --  Initialization & Finalization routines. More in the next section.
32333 private
32334    pragma Export (C, Initialize_API);
32335    pragma Export (C, Finalize_API);
32336    pragma Export (C, Count);
32337    pragma Export (C, Factorial);
32338 end API;
32339 @end cartouche
32340 @end group
32341 @end smallexample
32342
32343 @smallexample @c ada
32344 @group
32345 @cartouche
32346 package body API is
32347    function Factorial (Val : C.int) return C.int is
32348       Fact : C.int := 1;
32349    begin
32350       Count := Count + 1;
32351       for K in 1 .. Val loop
32352          Fact := Fact * K;
32353       end loop;
32354       return Fact;
32355    end Factorial;
32356
32357    procedure Initialize_API is
32358       procedure Adainit;
32359       pragma Import (C, Adainit);
32360    begin
32361       Adainit;
32362    end Initialize_API;
32363
32364    procedure Finalize_API is
32365       procedure Adafinal;
32366       pragma Import (C, Adafinal);
32367    begin
32368       Adafinal;
32369    end Finalize_API;
32370 end API;
32371 @end cartouche
32372 @end group
32373 @end smallexample
32374
32375 @noindent
32376 If the Ada DLL you are building will only be used by Ada applications
32377 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32378 convention. As an example, the previous package could be written as
32379 follows:
32380
32381 @smallexample @c ada
32382 @group
32383 @cartouche
32384 package API is
32385    Count : Integer := 0;
32386    function Factorial (Val : Integer) return Integer;
32387
32388    procedure Initialize_API;
32389    procedure Finalize_API;
32390    --  Initialization and Finalization routines.
32391 end API;
32392 @end cartouche
32393 @end group
32394 @end smallexample
32395
32396 @smallexample @c ada
32397 @group
32398 @cartouche
32399 package body API is
32400    function Factorial (Val : Integer) return Integer is
32401       Fact : Integer := 1;
32402    begin
32403       Count := Count + 1;
32404       for K in 1 .. Val loop
32405          Fact := Fact * K;
32406       end loop;
32407       return Fact;
32408    end Factorial;
32409
32410    @dots{}
32411    --  The remainder of this package body is unchanged.
32412 end API;
32413 @end cartouche
32414 @end group
32415 @end smallexample
32416
32417 @noindent
32418 Note that if you do not export the Ada entities with a @code{C} or
32419 @code{Stdcall} convention you will have to provide the mangled Ada names
32420 in the definition file of the Ada DLL
32421 (@pxref{Creating the Definition File}).
32422
32423 @node Ada DLLs and Elaboration
32424 @subsection Ada DLLs and Elaboration
32425 @cindex DLLs and elaboration
32426
32427 @noindent
32428 The DLL that you are building contains your Ada code as well as all the
32429 routines in the Ada library that are needed by it. The first thing a
32430 user of your DLL must do is elaborate the Ada code
32431 (@pxref{Elaboration Order Handling in GNAT}).
32432
32433 To achieve this you must export an initialization routine
32434 (@code{Initialize_API} in the previous example), which must be invoked
32435 before using any of the DLL services. This elaboration routine must call
32436 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32437 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32438 @code{Initialize_Api} for an example. Note that the GNAT binder is
32439 automatically invoked during the DLL build process by the @code{gnatdll}
32440 tool (@pxref{Using gnatdll}).
32441
32442 When a DLL is loaded, Windows systematically invokes a routine called
32443 @code{DllMain}. It would therefore be possible to call @code{adainit}
32444 directly from @code{DllMain} without having to provide an explicit
32445 initialization routine. Unfortunately, it is not possible to call
32446 @code{adainit} from the @code{DllMain} if your program has library level
32447 tasks because access to the @code{DllMain} entry point is serialized by
32448 the system (that is, only a single thread can execute ``through'' it at a
32449 time), which means that the GNAT run time will deadlock waiting for the
32450 newly created task to complete its initialization.
32451
32452 @node Ada DLLs and Finalization
32453 @subsection Ada DLLs and Finalization
32454 @cindex DLLs and finalization
32455
32456 @noindent
32457 When the services of an Ada DLL are no longer needed, the client code should
32458 invoke the DLL finalization routine, if available. The DLL finalization
32459 routine is in charge of releasing all resources acquired by the DLL. In the
32460 case of the Ada code contained in the DLL, this is achieved by calling
32461 routine @code{adafinal} generated by the GNAT binder
32462 (@pxref{Binding with Non-Ada Main Programs}).
32463 See the body of @code{Finalize_Api} for an
32464 example. As already pointed out the GNAT binder is automatically invoked
32465 during the DLL build process by the @code{gnatdll} tool
32466 (@pxref{Using gnatdll}).
32467
32468 @node Creating a Spec for Ada DLLs
32469 @subsection Creating a Spec for Ada DLLs
32470
32471 @noindent
32472 To use the services exported by the Ada DLL from another programming
32473 language (e.g.@: C), you have to translate the specs of the exported Ada
32474 entities in that language. For instance in the case of @code{API.dll},
32475 the corresponding C header file could look like:
32476
32477 @smallexample
32478 @group
32479 @cartouche
32480 extern int *_imp__count;
32481 #define count (*_imp__count)
32482 int factorial (int);
32483 @end cartouche
32484 @end group
32485 @end smallexample
32486
32487 @noindent
32488 It is important to understand that when building an Ada DLL to be used by
32489 other Ada applications, you need two different specs for the packages
32490 contained in the DLL: one for building the DLL and the other for using
32491 the DLL. This is because the @code{DLL} calling convention is needed to
32492 use a variable defined in a DLL, but when building the DLL, the variable
32493 must have either the @code{Ada} or @code{C} calling convention. As an
32494 example consider a DLL comprising the following package @code{API}:
32495
32496 @smallexample @c ada
32497 @group
32498 @cartouche
32499 package API is
32500    Count : Integer := 0;
32501    @dots{}
32502    --  Remainder of the package omitted.
32503 end API;
32504 @end cartouche
32505 @end group
32506 @end smallexample
32507
32508 @noindent
32509 After producing a DLL containing package @code{API}, the spec that
32510 must be used to import @code{API.Count} from Ada code outside of the
32511 DLL is:
32512
32513 @smallexample @c ada
32514 @group
32515 @cartouche
32516 package API is
32517    Count : Integer;
32518    pragma Import (DLL, Count);
32519 end API;
32520 @end cartouche
32521 @end group
32522 @end smallexample
32523
32524 @node Creating the Definition File
32525 @subsection Creating the Definition File
32526
32527 @noindent
32528 The definition file is the last file needed to build the DLL. It lists
32529 the exported symbols. As an example, the definition file for a DLL
32530 containing only package @code{API} (where all the entities are exported
32531 with a @code{C} calling convention) is:
32532
32533 @smallexample
32534 @group
32535 @cartouche
32536 EXPORTS
32537     count
32538     factorial
32539     finalize_api
32540     initialize_api
32541 @end cartouche
32542 @end group
32543 @end smallexample
32544
32545 @noindent
32546 If the @code{C} calling convention is missing from package @code{API},
32547 then the definition file contains the mangled Ada names of the above
32548 entities, which in this case are:
32549
32550 @smallexample
32551 @group
32552 @cartouche
32553 EXPORTS
32554     api__count
32555     api__factorial
32556     api__finalize_api
32557     api__initialize_api
32558 @end cartouche
32559 @end group
32560 @end smallexample
32561
32562 @node Using gnatdll
32563 @subsection Using @code{gnatdll}
32564 @findex gnatdll
32565
32566 @menu
32567 * gnatdll Example::
32568 * gnatdll behind the Scenes::
32569 * Using dlltool::
32570 @end menu
32571
32572 @noindent
32573 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32574 and non-Ada sources that make up your DLL have been compiled.
32575 @code{gnatdll} is actually in charge of two distinct tasks: build the
32576 static import library for the DLL and the actual DLL. The form of the
32577 @code{gnatdll} command is
32578
32579 @smallexample
32580 @cartouche
32581 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32582 @end cartouche
32583 @end smallexample
32584
32585 @noindent
32586 where @var{list-of-files} is a list of ALI and object files. The object
32587 file list must be the exact list of objects corresponding to the non-Ada
32588 sources whose services are to be included in the DLL. The ALI file list
32589 must be the exact list of ALI files for the corresponding Ada sources
32590 whose services are to be included in the DLL. If @var{list-of-files} is
32591 missing, only the static import library is generated.
32592
32593 @noindent
32594 You may specify any of the following switches to @code{gnatdll}:
32595
32596 @table @code
32597 @item -a@ovar{address}
32598 @cindex @option{-a} (@code{gnatdll})
32599 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32600 specified the default address @var{0x11000000} will be used. By default,
32601 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32602 advise the reader to build relocatable DLL.
32603
32604 @item -b @var{address}
32605 @cindex @option{-b} (@code{gnatdll})
32606 Set the relocatable DLL base address. By default the address is
32607 @code{0x11000000}.
32608
32609 @item -bargs @var{opts}
32610 @cindex @option{-bargs} (@code{gnatdll})
32611 Binder options. Pass @var{opts} to the binder.
32612
32613 @item -d @var{dllfile}
32614 @cindex @option{-d} (@code{gnatdll})
32615 @var{dllfile} is the name of the DLL. This switch must be present for
32616 @code{gnatdll} to do anything. The name of the generated import library is
32617 obtained algorithmically from @var{dllfile} as shown in the following
32618 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32619 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32620 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32621 as shown in the following example:
32622 if @var{dllfile} is @code{xyz.dll}, the definition
32623 file used is @code{xyz.def}.
32624
32625 @item -e @var{deffile}
32626 @cindex @option{-e} (@code{gnatdll})
32627 @var{deffile} is the name of the definition file.
32628
32629 @item -g
32630 @cindex @option{-g} (@code{gnatdll})
32631 Generate debugging information. This information is stored in the object
32632 file and copied from there to the final DLL file by the linker,
32633 where it can be read by the debugger. You must use the
32634 @option{-g} switch if you plan on using the debugger or the symbolic
32635 stack traceback.
32636
32637 @item -h
32638 @cindex @option{-h} (@code{gnatdll})
32639 Help mode. Displays @code{gnatdll} switch usage information.
32640
32641 @item -Idir
32642 @cindex @option{-I} (@code{gnatdll})
32643 Direct @code{gnatdll} to search the @var{dir} directory for source and
32644 object files needed to build the DLL.
32645 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32646
32647 @item -k
32648 @cindex @option{-k} (@code{gnatdll})
32649 Removes the @code{@@}@var{nn} suffix from the import library's exported
32650 names, but keeps them for the link names. You must specify this
32651 option if you want to use a @code{Stdcall} function in a DLL for which
32652 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32653 of the Windows NT DLL for example. This option has no effect when
32654 @option{-n} option is specified.
32655
32656 @item -l @var{file}
32657 @cindex @option{-l} (@code{gnatdll})
32658 The list of ALI and object files used to build the DLL are listed in
32659 @var{file}, instead of being given in the command line. Each line in
32660 @var{file} contains the name of an ALI or object file.
32661
32662 @item -n
32663 @cindex @option{-n} (@code{gnatdll})
32664 No Import. Do not create the import library.
32665
32666 @item -q
32667 @cindex @option{-q} (@code{gnatdll})
32668 Quiet mode. Do not display unnecessary messages.
32669
32670 @item -v
32671 @cindex @option{-v} (@code{gnatdll})
32672 Verbose mode. Display extra information.
32673
32674 @item -largs @var{opts}
32675 @cindex @option{-largs} (@code{gnatdll})
32676 Linker options. Pass @var{opts} to the linker.
32677 @end table
32678
32679 @node gnatdll Example
32680 @subsubsection @code{gnatdll} Example
32681
32682 @noindent
32683 As an example the command to build a relocatable DLL from @file{api.adb}
32684 once @file{api.adb} has been compiled and @file{api.def} created is
32685
32686 @smallexample
32687 $ gnatdll -d api.dll api.ali
32688 @end smallexample
32689
32690 @noindent
32691 The above command creates two files: @file{libapi.dll.a} (the import
32692 library) and @file{api.dll} (the actual DLL). If you want to create
32693 only the DLL, just type:
32694
32695 @smallexample
32696 $ gnatdll -d api.dll -n api.ali
32697 @end smallexample
32698
32699 @noindent
32700 Alternatively if you want to create just the import library, type:
32701
32702 @smallexample
32703 $ gnatdll -d api.dll
32704 @end smallexample
32705
32706 @node gnatdll behind the Scenes
32707 @subsubsection @code{gnatdll} behind the Scenes
32708
32709 @noindent
32710 This section details the steps involved in creating a DLL. @code{gnatdll}
32711 does these steps for you. Unless you are interested in understanding what
32712 goes on behind the scenes, you should skip this section.
32713
32714 We use the previous example of a DLL containing the Ada package @code{API},
32715 to illustrate the steps necessary to build a DLL. The starting point is a
32716 set of objects that will make up the DLL and the corresponding ALI
32717 files. In the case of this example this means that @file{api.o} and
32718 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32719 the following:
32720
32721 @enumerate
32722 @item
32723 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32724 the information necessary to generate relocation information for the
32725 DLL.
32726
32727 @smallexample
32728 @group
32729 $ gnatbind -n api
32730 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32731 @end group
32732 @end smallexample
32733
32734 @noindent
32735 In addition to the base file, the @command{gnatlink} command generates an
32736 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32737 asks @command{gnatlink} to generate the routines @code{DllMain} and
32738 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32739 is loaded into memory.
32740
32741 @item
32742 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32743 export table (@file{api.exp}). The export table contains the relocation
32744 information in a form which can be used during the final link to ensure
32745 that the Windows loader is able to place the DLL anywhere in memory.
32746
32747 @smallexample
32748 @group
32749 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32750           --output-exp api.exp
32751 @end group
32752 @end smallexample
32753
32754 @item
32755 @code{gnatdll} builds the base file using the new export table. Note that
32756 @command{gnatbind} must be called once again since the binder generated file
32757 has been deleted during the previous call to @command{gnatlink}.
32758
32759 @smallexample
32760 @group
32761 $ gnatbind -n api
32762 $ gnatlink api -o api.jnk api.exp -mdll
32763       -Wl,--base-file,api.base
32764 @end group
32765 @end smallexample
32766
32767 @item
32768 @code{gnatdll} builds the new export table using the new base file and
32769 generates the DLL import library @file{libAPI.dll.a}.
32770
32771 @smallexample
32772 @group
32773 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32774           --output-exp api.exp --output-lib libAPI.a
32775 @end group
32776 @end smallexample
32777
32778 @item
32779 Finally @code{gnatdll} builds the relocatable DLL using the final export
32780 table.
32781
32782 @smallexample
32783 @group
32784 $ gnatbind -n api
32785 $ gnatlink api api.exp -o api.dll -mdll
32786 @end group
32787 @end smallexample
32788 @end enumerate
32789
32790 @node Using dlltool
32791 @subsubsection Using @code{dlltool}
32792
32793 @noindent
32794 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32795 DLLs and static import libraries. This section summarizes the most
32796 common @code{dlltool} switches. The form of the @code{dlltool} command
32797 is
32798
32799 @smallexample
32800 $ dlltool @ovar{switches}
32801 @end smallexample
32802
32803 @noindent
32804 @code{dlltool} switches include:
32805
32806 @table @option
32807 @item --base-file @var{basefile}
32808 @cindex @option{--base-file} (@command{dlltool})
32809 Read the base file @var{basefile} generated by the linker. This switch
32810 is used to create a relocatable DLL.
32811
32812 @item --def @var{deffile}
32813 @cindex @option{--def} (@command{dlltool})
32814 Read the definition file.
32815
32816 @item --dllname @var{name}
32817 @cindex @option{--dllname} (@command{dlltool})
32818 Gives the name of the DLL. This switch is used to embed the name of the
32819 DLL in the static import library generated by @code{dlltool} with switch
32820 @option{--output-lib}.
32821
32822 @item -k
32823 @cindex @option{-k} (@command{dlltool})
32824 Kill @code{@@}@var{nn} from exported names
32825 (@pxref{Windows Calling Conventions}
32826 for a discussion about @code{Stdcall}-style symbols.
32827
32828 @item --help
32829 @cindex @option{--help} (@command{dlltool})
32830 Prints the @code{dlltool} switches with a concise description.
32831
32832 @item --output-exp @var{exportfile}
32833 @cindex @option{--output-exp} (@command{dlltool})
32834 Generate an export file @var{exportfile}. The export file contains the
32835 export table (list of symbols in the DLL) and is used to create the DLL.
32836
32837 @item --output-lib @var{libfile}
32838 @cindex @option{--output-lib} (@command{dlltool})
32839 Generate a static import library @var{libfile}.
32840
32841 @item -v
32842 @cindex @option{-v} (@command{dlltool})
32843 Verbose mode.
32844
32845 @item --as @var{assembler-name}
32846 @cindex @option{--as} (@command{dlltool})
32847 Use @var{assembler-name} as the assembler. The default is @code{as}.
32848 @end table
32849
32850 @node GNAT and Windows Resources
32851 @section GNAT and Windows Resources
32852 @cindex Resources, windows
32853
32854 @menu
32855 * Building Resources::
32856 * Compiling Resources::
32857 * Using Resources::
32858 @end menu
32859
32860 @noindent
32861 Resources are an easy way to add Windows specific objects to your
32862 application. The objects that can be added as resources include:
32863
32864 @itemize @bullet
32865 @item
32866 menus
32867
32868 @item
32869 accelerators
32870
32871 @item
32872 dialog boxes
32873
32874 @item
32875 string tables
32876
32877 @item
32878 bitmaps
32879
32880 @item
32881 cursors
32882
32883 @item
32884 icons
32885
32886 @item
32887 fonts
32888 @end itemize
32889
32890 @noindent
32891 This section explains how to build, compile and use resources.
32892
32893 @node Building Resources
32894 @subsection Building Resources
32895 @cindex Resources, building
32896
32897 @noindent
32898 A resource file is an ASCII file. By convention resource files have an
32899 @file{.rc} extension.
32900 The easiest way to build a resource file is to use Microsoft tools
32901 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32902 @code{dlgedit.exe} to build dialogs.
32903 It is always possible to build an @file{.rc} file yourself by writing a
32904 resource script.
32905
32906 It is not our objective to explain how to write a resource file. A
32907 complete description of the resource script language can be found in the
32908 Microsoft documentation.
32909
32910 @node Compiling Resources
32911 @subsection Compiling Resources
32912 @findex rc
32913 @findex windres
32914 @cindex Resources, compiling
32915
32916 @noindent
32917 This section describes how to build a GNAT-compatible (COFF) object file
32918 containing the resources. This is done using the Resource Compiler
32919 @code{windres} as follows:
32920
32921 @smallexample
32922 $ windres -i myres.rc -o myres.o
32923 @end smallexample
32924
32925 @noindent
32926 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32927 file. You can specify an alternate preprocessor (usually named
32928 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32929 parameter. A list of all possible options may be obtained by entering
32930 the command @code{windres} @option{--help}.
32931
32932 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32933 to produce a @file{.res} file (binary resource file). See the
32934 corresponding Microsoft documentation for further details. In this case
32935 you need to use @code{windres} to translate the @file{.res} file to a
32936 GNAT-compatible object file as follows:
32937
32938 @smallexample
32939 $ windres -i myres.res -o myres.o
32940 @end smallexample
32941
32942 @node Using Resources
32943 @subsection Using Resources
32944 @cindex Resources, using
32945
32946 @noindent
32947 To include the resource file in your program just add the
32948 GNAT-compatible object file for the resource(s) to the linker
32949 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32950 option:
32951
32952 @smallexample
32953 $ gnatmake myprog -largs myres.o
32954 @end smallexample
32955
32956 @node Debugging a DLL
32957 @section Debugging a DLL
32958 @cindex DLL debugging
32959
32960 @menu
32961 * Program and DLL Both Built with GCC/GNAT::
32962 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32963 @end menu
32964
32965 @noindent
32966 Debugging a DLL is similar to debugging a standard program. But
32967 we have to deal with two different executable parts: the DLL and the
32968 program that uses it. We have the following four possibilities:
32969
32970 @enumerate 1
32971 @item
32972 The program and the DLL are built with @code{GCC/GNAT}.
32973 @item
32974 The program is built with foreign tools and the DLL is built with
32975 @code{GCC/GNAT}.
32976 @item
32977 The program is built with @code{GCC/GNAT} and the DLL is built with
32978 foreign tools.
32979 @item
32980 @end enumerate
32981
32982 @noindent
32983 In this section we address only cases one and two above.
32984 There is no point in trying to debug
32985 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32986 information in it. To do so you must use a debugger compatible with the
32987 tools suite used to build the DLL.
32988
32989 @node Program and DLL Both Built with GCC/GNAT
32990 @subsection Program and DLL Both Built with GCC/GNAT
32991
32992 @noindent
32993 This is the simplest case. Both the DLL and the program have @code{GDB}
32994 compatible debugging information. It is then possible to break anywhere in
32995 the process. Let's suppose here that the main procedure is named
32996 @code{ada_main} and that in the DLL there is an entry point named
32997 @code{ada_dll}.
32998
32999 @noindent
33000 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33001 program must have been built with the debugging information (see GNAT -g
33002 switch). Here are the step-by-step instructions for debugging it:
33003
33004 @enumerate 1
33005 @item Launch @code{GDB} on the main program.
33006
33007 @smallexample
33008 $ gdb -nw ada_main
33009 @end smallexample
33010
33011 @item Start the program and stop at the beginning of the main procedure
33012
33013 @smallexample
33014 (gdb) start
33015 @end smallexample
33016
33017 @noindent
33018 This step is required to be able to set a breakpoint inside the DLL. As long
33019 as the program is not run, the DLL is not loaded. This has the
33020 consequence that the DLL debugging information is also not loaded, so it is not
33021 possible to set a breakpoint in the DLL.
33022
33023 @item Set a breakpoint inside the DLL
33024
33025 @smallexample
33026 (gdb) break ada_dll
33027 (gdb) cont
33028 @end smallexample
33029
33030 @end enumerate
33031
33032 @noindent
33033 At this stage a breakpoint is set inside the DLL. From there on
33034 you can use the standard approach to debug the whole program
33035 (@pxref{Running and Debugging Ada Programs}).
33036
33037 @ignore
33038 @c This used to work, probably because the DLLs were non-relocatable
33039 @c keep this section around until the problem is sorted out.
33040
33041 To break on the @code{DllMain} routine it is not possible to follow
33042 the procedure above. At the time the program stop on @code{ada_main}
33043 the @code{DllMain} routine as already been called. Either you can use
33044 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33045
33046 @enumerate 1
33047 @item Launch @code{GDB} on the main program.
33048
33049 @smallexample
33050 $ gdb ada_main
33051 @end smallexample
33052
33053 @item Load DLL symbols
33054
33055 @smallexample
33056 (gdb) add-sym api.dll
33057 @end smallexample
33058
33059 @item Set a breakpoint inside the DLL
33060
33061 @smallexample
33062 (gdb) break ada_dll.adb:45
33063 @end smallexample
33064
33065 Note that at this point it is not possible to break using the routine symbol
33066 directly as the program is not yet running. The solution is to break
33067 on the proper line (break in @file{ada_dll.adb} line 45).
33068
33069 @item Start the program
33070
33071 @smallexample
33072 (gdb) run
33073 @end smallexample
33074
33075 @end enumerate
33076 @end ignore
33077
33078 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33079 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33080
33081 @menu
33082 * Debugging the DLL Directly::
33083 * Attaching to a Running Process::
33084 @end menu
33085
33086 @noindent
33087 In this case things are slightly more complex because it is not possible to
33088 start the main program and then break at the beginning to load the DLL and the
33089 associated DLL debugging information. It is not possible to break at the
33090 beginning of the program because there is no @code{GDB} debugging information,
33091 and therefore there is no direct way of getting initial control. This
33092 section addresses this issue by describing some methods that can be used
33093 to break somewhere in the DLL to debug it.
33094
33095 @noindent
33096 First suppose that the main procedure is named @code{main} (this is for
33097 example some C code built with Microsoft Visual C) and that there is a
33098 DLL named @code{test.dll} containing an Ada entry point named
33099 @code{ada_dll}.
33100
33101 @noindent
33102 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33103 been built with debugging information (see GNAT -g option).
33104
33105 @node Debugging the DLL Directly
33106 @subsubsection Debugging the DLL Directly
33107
33108 @enumerate 1
33109 @item
33110 Find out the executable starting address
33111
33112 @smallexample
33113 $ objdump --file-header main.exe
33114 @end smallexample
33115
33116 The starting address is reported on the last line. For example:
33117
33118 @smallexample
33119 main.exe:     file format pei-i386
33120 architecture: i386, flags 0x0000010a:
33121 EXEC_P, HAS_DEBUG, D_PAGED
33122 start address 0x00401010
33123 @end smallexample
33124
33125 @item
33126 Launch the debugger on the executable.
33127
33128 @smallexample
33129 $ gdb main.exe
33130 @end smallexample
33131
33132 @item
33133 Set a breakpoint at the starting address, and launch the program.
33134
33135 @smallexample
33136 $ (gdb) break *0x00401010
33137 $ (gdb) run
33138 @end smallexample
33139
33140 The program will stop at the given address.
33141
33142 @item
33143 Set a breakpoint on a DLL subroutine.
33144
33145 @smallexample
33146 (gdb) break ada_dll.adb:45
33147 @end smallexample
33148
33149 Or if you want to break using a symbol on the DLL, you need first to
33150 select the Ada language (language used by the DLL).
33151
33152 @smallexample
33153 (gdb) set language ada
33154 (gdb) break ada_dll
33155 @end smallexample
33156
33157 @item
33158 Continue the program.
33159
33160 @smallexample
33161 (gdb) cont
33162 @end smallexample
33163
33164 @noindent
33165 This will run the program until it reaches the breakpoint that has been
33166 set. From that point you can use the standard way to debug a program
33167 as described in (@pxref{Running and Debugging Ada Programs}).
33168
33169 @end enumerate
33170
33171 @noindent
33172 It is also possible to debug the DLL by attaching to a running process.
33173
33174 @node Attaching to a Running Process
33175 @subsubsection Attaching to a Running Process
33176 @cindex DLL debugging, attach to process
33177
33178 @noindent
33179 With @code{GDB} it is always possible to debug a running process by
33180 attaching to it. It is possible to debug a DLL this way. The limitation
33181 of this approach is that the DLL must run long enough to perform the
33182 attach operation. It may be useful for instance to insert a time wasting
33183 loop in the code of the DLL to meet this criterion.
33184
33185 @enumerate 1
33186
33187 @item Launch the main program @file{main.exe}.
33188
33189 @smallexample
33190 $ main
33191 @end smallexample
33192
33193 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33194 that the process PID for @file{main.exe} is 208.
33195
33196 @item Launch gdb.
33197
33198 @smallexample
33199 $ gdb
33200 @end smallexample
33201
33202 @item Attach to the running process to be debugged.
33203
33204 @smallexample
33205 (gdb) attach 208
33206 @end smallexample
33207
33208 @item Load the process debugging information.
33209
33210 @smallexample
33211 (gdb) symbol-file main.exe
33212 @end smallexample
33213
33214 @item Break somewhere in the DLL.
33215
33216 @smallexample
33217 (gdb) break ada_dll
33218 @end smallexample
33219
33220 @item Continue process execution.
33221
33222 @smallexample
33223 (gdb) cont
33224 @end smallexample
33225
33226 @end enumerate
33227
33228 @noindent
33229 This last step will resume the process execution, and stop at
33230 the breakpoint we have set. From there you can use the standard
33231 approach to debug a program as described in
33232 (@pxref{Running and Debugging Ada Programs}).
33233
33234 @node Setting Stack Size from gnatlink
33235 @section Setting Stack Size from @command{gnatlink}
33236
33237 @noindent
33238 It is possible to specify the program stack size at link time. On modern
33239 versions of Windows, starting with XP, this is mostly useful to set the size of
33240 the main stack (environment task). The other task stacks are set with pragma
33241 Storage_Size or with the @command{gnatbind -d} command.
33242
33243 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33244 reserve size of individual tasks, the link-time stack size applies to all
33245 tasks, and pragma Storage_Size has no effect.
33246 In particular, Stack Overflow checks are made against this
33247 link-time specified size.
33248
33249 This setting can be done with
33250 @command{gnatlink} using either:
33251
33252 @itemize @bullet
33253
33254 @item using @option{-Xlinker} linker option
33255
33256 @smallexample
33257 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33258 @end smallexample
33259
33260 This sets the stack reserve size to 0x10000 bytes and the stack commit
33261 size to 0x1000 bytes.
33262
33263 @item using @option{-Wl} linker option
33264
33265 @smallexample
33266 $ gnatlink hello -Wl,--stack=0x1000000
33267 @end smallexample
33268
33269 This sets the stack reserve size to 0x1000000 bytes. Note that with
33270 @option{-Wl} option it is not possible to set the stack commit size
33271 because the coma is a separator for this option.
33272
33273 @end itemize
33274
33275 @node Setting Heap Size from gnatlink
33276 @section Setting Heap Size from @command{gnatlink}
33277
33278 @noindent
33279 Under Windows systems, it is possible to specify the program heap size from
33280 @command{gnatlink} using either:
33281
33282 @itemize @bullet
33283
33284 @item using @option{-Xlinker} linker option
33285
33286 @smallexample
33287 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33288 @end smallexample
33289
33290 This sets the heap reserve size to 0x10000 bytes and the heap commit
33291 size to 0x1000 bytes.
33292
33293 @item using @option{-Wl} linker option
33294
33295 @smallexample
33296 $ gnatlink hello -Wl,--heap=0x1000000
33297 @end smallexample
33298
33299 This sets the heap reserve size to 0x1000000 bytes. Note that with
33300 @option{-Wl} option it is not possible to set the heap commit size
33301 because the coma is a separator for this option.
33302
33303 @end itemize
33304
33305 @end ifset
33306
33307 @c **********************************
33308 @c * GNU Free Documentation License *
33309 @c **********************************
33310 @include fdl.texi
33311 @c GNU Free Documentation License
33312
33313 @node Index,,GNU Free Documentation License, Top
33314 @unnumbered Index
33315
33316 @printindex cp
33317
33318 @contents
33319 @c Put table of contents at end, otherwise it precedes the "title page" in
33320 @c the .txt version
33321 @c Edit the pdf file to move the contents to the beginning, after the title
33322 @c page
33323
33324 @bye