OSDN Git Service

2010-09-09 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.3 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 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metric Tool gnatmetric::
183 * File Name Krunching Using gnatkr::
184 * Preprocessing Using gnatprep::
185 @ifset vms
186 * The GNAT Run-Time Library Builder gnatlbr::
187 @end ifset
188 * The GNAT Library Browser gnatls::
189 * Cleaning Up Using gnatclean::
190 @ifclear vms
191 * GNAT and Libraries::
192 * Using the GNU make Utility::
193 @end ifclear
194 * Memory Management Issues::
195 * Stack Related Facilities::
196 * Verifying Properties Using gnatcheck::
197 * Creating Sample Bodies Using gnatstub::
198 * Generating Ada Bindings for C and C++ headers::
199 * Other Utility Programs::
200 * Running and Debugging Ada Programs::
201 @ifclear vms
202 * Code Coverage and Profiling::
203 @end ifclear
204 @ifset vms
205 * Compatibility with HP Ada::
206 @end ifset
207 * Platform-Specific Information for the Run-Time Libraries::
208 * Example of Binder Output File::
209 * Elaboration Order Handling in GNAT::
210 * Conditional Compilation::
211 * Inline Assembler::
212 * Compatibility and Porting Guide::
213 @ifset unw
214 * Microsoft Windows Topics::
215 @end ifset
216 * GNU Free Documentation License::
217 * Index::
218
219  --- The Detailed Node Listing ---
220
221 About This Guide
222
223 * What This Guide Contains::
224 * What You Should Know before Reading This Guide::
225 * Related Information::
226 * Conventions::
227
228 Getting Started with GNAT
229
230 * Running GNAT::
231 * Running a Simple Ada Program::
232 * Running a Program with Multiple Units::
233 * Using the gnatmake Utility::
234 @ifset vms
235 * Editing with Emacs::
236 @end ifset
237 @ifclear vms
238 * Introduction to GPS::
239 @end ifclear
240
241 The GNAT Compilation Model
242
243 * Source Representation::
244 * Foreign Language Representation::
245 * File Naming Rules::
246 * Using Other File Names::
247 * Alternative File Naming Schemes::
248 * Generating Object Files::
249 * Source Dependencies::
250 * The Ada Library Information Files::
251 * Binding an Ada Program::
252 * Mixed Language Programming::
253 @ifclear vms
254 * Building Mixed Ada & C++ Programs::
255 * Comparison between GNAT and C/C++ Compilation Models::
256 @end ifclear
257 * Comparison between GNAT and Conventional Ada Library Models::
258 @ifset vms
259 * Placement of temporary files::
260 @end ifset
261
262 Foreign Language Representation
263
264 * Latin-1::
265 * Other 8-Bit Codes::
266 * Wide Character Encodings::
267
268 Compiling Ada Programs With gcc
269
270 * Compiling Programs::
271 * Switches for gcc::
272 * Search Paths and the Run-Time Library (RTL)::
273 * Order of Compilation Issues::
274 * Examples::
275
276 Switches for gcc
277
278 * Output and Error Message Control::
279 * Warning Message Control::
280 * Debugging and Assertion Control::
281 * Validity Checking::
282 * Style Checking::
283 * Run-Time Checks::
284 * Using gcc for Syntax Checking::
285 * Using gcc for Semantic Checking::
286 * Compiling Different Versions of Ada::
287 * Character Set Control::
288 * File Naming Control::
289 * Subprogram Inlining Control::
290 * Auxiliary Output Control::
291 * Debugging Control::
292 * Exception Handling Control::
293 * Units to Sources Mapping Files::
294 * Integrated Preprocessing::
295 @ifset vms
296 * Return Codes::
297 @end ifset
298
299 Binding Ada Programs With gnatbind
300
301 * Running gnatbind::
302 * Switches for gnatbind::
303 * Command-Line Access::
304 * Search Paths for gnatbind::
305 * Examples of gnatbind Usage::
306
307 Switches for gnatbind
308
309 * Consistency-Checking Modes::
310 * Binder Error Message Control::
311 * Elaboration Control::
312 * Output Control::
313 * Binding with Non-Ada Main Programs::
314 * Binding Programs with No Main Subprogram::
315
316 Linking Using gnatlink
317
318 * Running gnatlink::
319 * Switches for gnatlink::
320
321 The GNAT Make Program gnatmake
322
323 * Running gnatmake::
324 * Switches for gnatmake::
325 * Mode Switches for gnatmake::
326 * Notes on the Command Line::
327 * How gnatmake Works::
328 * Examples of gnatmake Usage::
329
330 Improving Performance
331 * Performance Considerations::
332 * Text_IO Suggestions::
333 * Reducing Size of Ada Executables with gnatelim::
334 * Reducing Size of Executables with unused subprogram/data elimination::
335
336 Performance Considerations
337 * Controlling Run-Time Checks::
338 * Use of Restrictions::
339 * Optimization Levels::
340 * Debugging Optimized Code::
341 * Inlining of Subprograms::
342 * Other Optimization Switches::
343 * Optimization and Strict Aliasing::
344 @ifset vms
345 * Coverage Analysis::
346 @end ifset
347
348 Reducing Size of Ada Executables with gnatelim
349 * About gnatelim::
350 * Running gnatelim::
351 * Processing Precompiled Libraries::
352 * Correcting the List of Eliminate Pragmas::
353 * Making Your Executables Smaller::
354 * Summary of the gnatelim Usage Cycle::
355
356 Reducing Size of Executables with unused subprogram/data elimination
357 * About unused subprogram/data elimination::
358 * Compilation options::
359
360 Renaming Files Using gnatchop
361
362 * Handling Files with Multiple Units::
363 * Operating gnatchop in Compilation Mode::
364 * Command Line for gnatchop::
365 * Switches for gnatchop::
366 * Examples of gnatchop Usage::
367
368 Configuration Pragmas
369
370 * Handling of Configuration Pragmas::
371 * The Configuration Pragmas Files::
372
373 Handling Arbitrary File Naming Conventions Using gnatname
374
375 * Arbitrary File Naming Conventions::
376 * Running gnatname::
377 * Switches for gnatname::
378 * Examples of gnatname Usage::
379
380 The Cross-Referencing Tools gnatxref and gnatfind
381
382 * Switches for gnatxref::
383 * Switches for gnatfind::
384 * Project Files for gnatxref and gnatfind::
385 * Regular Expressions in gnatfind and gnatxref::
386 * Examples of gnatxref Usage::
387 * Examples of gnatfind Usage::
388
389 The GNAT Pretty-Printer gnatpp
390
391 * Switches for gnatpp::
392 * Formatting Rules::
393
394 The GNAT Metrics Tool gnatmetric
395
396 * Switches for gnatmetric::
397
398 File Name Krunching Using gnatkr
399
400 * About gnatkr::
401 * Using gnatkr::
402 * Krunching Method::
403 * Examples of gnatkr Usage::
404
405 Preprocessing Using gnatprep
406 * Preprocessing Symbols::
407 * Using gnatprep::
408 * Switches for gnatprep::
409 * Form of Definitions File::
410 * Form of Input Text for gnatprep::
411
412 @ifset vms
413 The GNAT Run-Time Library Builder gnatlbr
414
415 * Running gnatlbr::
416 * Switches for gnatlbr::
417 * Examples of gnatlbr Usage::
418 @end ifset
419
420 The GNAT Library Browser gnatls
421
422 * Running gnatls::
423 * Switches for gnatls::
424 * Examples of gnatls Usage::
425
426 Cleaning Up Using gnatclean
427
428 * Running gnatclean::
429 * Switches for gnatclean::
430 @c * Examples of gnatclean Usage::
431
432 @ifclear vms
433
434 GNAT and Libraries
435
436 * Introduction to Libraries in GNAT::
437 * General Ada Libraries::
438 * Stand-alone Ada Libraries::
439 * Rebuilding the GNAT Run-Time Library::
440
441 Using the GNU make Utility
442
443 * Using gnatmake in a Makefile::
444 * Automatically Creating a List of Directories::
445 * Generating the Command Line Switches::
446 * Overcoming Command Line Length Limits::
447 @end ifclear
448
449 Memory Management Issues
450
451 * Some Useful Memory Pools::
452 * The GNAT Debug Pool Facility::
453 @ifclear vms
454 * The gnatmem Tool::
455 @end ifclear
456
457 Stack Related Facilities
458
459 * Stack Overflow Checking::
460 * Static Stack Usage Analysis::
461 * Dynamic Stack Usage Analysis::
462
463 Some Useful Memory Pools
464
465 The GNAT Debug Pool Facility
466
467 @ifclear vms
468 The gnatmem Tool
469
470 * Running gnatmem::
471 * Switches for gnatmem::
472 * Example of gnatmem Usage::
473 @end ifclear
474
475 Verifying Properties Using gnatcheck
476
477 * Format of the Report File::
478 * General gnatcheck Switches::
479 * gnatcheck Rule Options::
480 * Adding the Results of Compiler Checks to gnatcheck Output::
481 * Project-Wide Checks::
482 * Rule exemption::
483 * Predefined Rules::
484 * Example of gnatcheck Usage::
485
486 Sample Bodies Using gnatstub
487
488 * Running gnatstub::
489 * Switches for gnatstub::
490
491 Other Utility Programs
492
493 * Using Other Utility Programs with GNAT::
494 * The External Symbol Naming Scheme of GNAT::
495 * Converting Ada Files to html with gnathtml::
496
497 @ifclear vms
498 Code Coverage and Profiling
499
500 * Code Coverage of Ada Programs using gcov::
501 * Profiling an Ada Program using gprof::
502 @end ifclear
503
504 Running and Debugging Ada Programs
505
506 * The GNAT Debugger GDB::
507 * Running GDB::
508 * Introduction to GDB Commands::
509 * Using Ada Expressions::
510 * Calling User-Defined Subprograms::
511 * Using the Next Command in a Function::
512 * Ada Exceptions::
513 * Ada Tasks::
514 * Debugging Generic Units::
515 * Remote Debugging using gdbserver::
516 * GNAT Abnormal Termination or Failure to Terminate::
517 * Naming Conventions for GNAT Source Files::
518 * Getting Internal Debugging Information::
519 * Stack Traceback::
520
521 @ifset vms
522 * LSE::
523 @end ifset
524
525 @ifset vms
526 Compatibility with HP Ada
527
528 * Ada Language Compatibility::
529 * Differences in the Definition of Package System::
530 * Language-Related Features::
531 * The Package STANDARD::
532 * The Package SYSTEM::
533 * Tasking and Task-Related Features::
534 * Pragmas and Pragma-Related Features::
535 * Library of Predefined Units::
536 * Bindings::
537 * Main Program Definition::
538 * Implementation-Defined Attributes::
539 * Compiler and Run-Time Interfacing::
540 * Program Compilation and Library Management::
541 * Input-Output::
542 * Implementation Limits::
543 * Tools and Utilities::
544
545 Language-Related Features
546
547 * Integer Types and Representations::
548 * Floating-Point Types and Representations::
549 * Pragmas Float_Representation and Long_Float::
550 * Fixed-Point Types and Representations::
551 * Record and Array Component Alignment::
552 * Address Clauses::
553 * Other Representation Clauses::
554
555 Tasking and Task-Related Features
556
557 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
558 * Assigning Task IDs::
559 * Task IDs and Delays::
560 * Task-Related Pragmas::
561 * Scheduling and Task Priority::
562 * The Task Stack::
563 * External Interrupts::
564
565 Pragmas and Pragma-Related Features
566
567 * Restrictions on the Pragma INLINE::
568 * Restrictions on the Pragma INTERFACE::
569 * Restrictions on the Pragma SYSTEM_NAME::
570
571 Library of Predefined Units
572
573 * Changes to DECLIB::
574
575 Bindings
576
577 * Shared Libraries and Options Files::
578 * Interfaces to C::
579 @end ifset
580
581 Platform-Specific Information for the Run-Time Libraries
582
583 * Summary of Run-Time Configurations::
584 * Specifying a Run-Time Library::
585 * Choosing the Scheduling Policy::
586 * Solaris-Specific Considerations::
587 * Linux-Specific Considerations::
588 * AIX-Specific Considerations::
589 * Irix-Specific Considerations::
590 * RTX-Specific Considerations::
591 * HP-UX-Specific Considerations::
592
593 Example of Binder Output File
594
595 Elaboration Order Handling in GNAT
596
597 * Elaboration Code::
598 * Checking the Elaboration Order::
599 * Controlling the Elaboration Order::
600 * Controlling Elaboration in GNAT - Internal Calls::
601 * Controlling Elaboration in GNAT - External Calls::
602 * Default Behavior in GNAT - Ensuring Safety::
603 * Treatment of Pragma Elaborate::
604 * Elaboration Issues for Library Tasks::
605 * Mixing Elaboration Models::
606 * What to Do If the Default Elaboration Behavior Fails::
607 * Elaboration for Access-to-Subprogram Values::
608 * Summary of Procedures for Elaboration Control::
609 * Other Elaboration Order Considerations::
610
611 Conditional Compilation
612 * Use of Boolean Constants::
613 * Debugging - A Special Case::
614 * Conditionalizing Declarations::
615 * Use of Alternative Implementations::
616 * Preprocessing::
617
618 Inline Assembler
619
620 * Basic Assembler Syntax::
621 * A Simple Example of Inline Assembler::
622 * Output Variables in Inline Assembler::
623 * Input Variables in Inline Assembler::
624 * Inlining Inline Assembler Code::
625 * Other Asm Functionality::
626
627 Compatibility and Porting Guide
628
629 * Compatibility with Ada 83::
630 * Compatibility between Ada 95 and Ada 2005::
631 * Implementation-dependent characteristics::
632 @ifclear vms
633 @c This brief section is only in the non-VMS version
634 @c The complete chapter on HP Ada issues is in the VMS version
635 * Compatibility with HP Ada 83::
636 @end ifclear
637 * Compatibility with Other Ada Systems::
638 * Representation Clauses::
639 @ifset vms
640 * Transitioning to 64-Bit GNAT for OpenVMS::
641 @end ifset
642
643 @ifset unw
644 Microsoft Windows Topics
645
646 * Using GNAT on Windows::
647 * CONSOLE and WINDOWS subsystems::
648 * Temporary Files::
649 * Mixed-Language Programming on Windows::
650 * Windows Calling Conventions::
651 * Introduction to Dynamic Link Libraries (DLLs)::
652 * Using DLLs with GNAT::
653 * Building DLLs with GNAT::
654 * GNAT and Windows Resources::
655 * Debugging a DLL::
656 * Setting Stack Size from gnatlink::
657 * Setting Heap Size from gnatlink::
658 @end ifset
659
660 * Index::
661 @end menu
662 @end ifnottex
663
664 @node About This Guide
665 @unnumbered About This Guide
666
667 @noindent
668 @ifset vms
669 This guide describes the use of @value{EDITION},
670 a compiler and software development toolset for the full Ada
671 programming language, implemented on OpenVMS for HP's Alpha and
672 Integrity server (I64) platforms.
673 @end ifset
674 @ifclear vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development
677 toolset for the full Ada programming language.
678 @end ifclear
679 It documents the features of the compiler and tools, and explains
680 how to use them to build Ada applications.
681
682 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
683 Ada 83 compatibility mode.
684 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
685 but you can override with a compiler switch
686 (@pxref{Compiling Different Versions of Ada})
687 to explicitly specify the language version.
688 Throughout this manual, references to ``Ada'' without a year suffix
689 apply to both the Ada 95 and Ada 2005 versions of the language.
690
691
692 @ifclear FSFEDITION
693 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
694 ``GNAT'' in the remainder of this document.
695 @end ifclear
696
697
698
699
700 @menu
701 * What This Guide Contains::
702 * What You Should Know before Reading This Guide::
703 * Related Information::
704 * Conventions::
705 @end menu
706
707 @node What This Guide Contains
708 @unnumberedsec What This Guide Contains
709
710 @noindent
711 This guide contains the following chapters:
712 @itemize @bullet
713
714 @item
715 @ref{Getting Started with GNAT}, describes how to get started compiling
716 and running Ada programs with the GNAT Ada programming environment.
717 @item
718 @ref{The GNAT Compilation Model}, describes the compilation model used
719 by GNAT.
720
721 @item
722 @ref{Compiling Using gcc}, describes how to compile
723 Ada programs with @command{gcc}, the Ada compiler.
724
725 @item
726 @ref{Binding Using gnatbind}, describes how to
727 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
728 utility.
729
730 @item
731 @ref{Linking Using gnatlink},
732 describes @command{gnatlink}, a
733 program that provides for linking using the GNAT run-time library to
734 construct a program. @command{gnatlink} can also incorporate foreign language
735 object units into the executable.
736
737 @item
738 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
739 utility that automatically determines the set of sources
740 needed by an Ada compilation unit, and executes the necessary compilations
741 binding and link.
742
743 @item
744 @ref{Improving Performance}, shows various techniques for making your
745 Ada program run faster or take less space.
746 It discusses the effect of the compiler's optimization switch and
747 also describes the @command{gnatelim} tool and unused subprogram/data
748 elimination.
749
750 @item
751 @ref{Renaming Files Using gnatchop}, describes
752 @code{gnatchop}, a utility that allows you to preprocess a file that
753 contains Ada source code, and split it into one or more new files, one
754 for each compilation unit.
755
756 @item
757 @ref{Configuration Pragmas}, describes the configuration pragmas
758 handled by GNAT.
759
760 @item
761 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
762 shows how to override the default GNAT file naming conventions,
763 either for an individual unit or globally.
764
765 @item
766 @ref{GNAT Project Manager}, describes how to use project files
767 to organize large projects.
768
769 @item
770 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
771 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
772 way to navigate through sources.
773
774 @item
775 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
776 version of an Ada source file with control over casing, indentation,
777 comment placement, and other elements of program presentation style.
778
779 @item
780 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
781 metrics for an Ada source file, such as the number of types and subprograms,
782 and assorted complexity measures.
783
784 @item
785 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
786 file name krunching utility, used to handle shortened
787 file names on operating systems with a limit on the length of names.
788
789 @item
790 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
791 preprocessor utility that allows a single source file to be used to
792 generate multiple or parameterized source files by means of macro
793 substitution.
794
795 @ifset vms
796 @item
797 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
798 a tool for rebuilding the GNAT run time with user-supplied
799 configuration pragmas.
800 @end ifset
801
802 @item
803 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
804 utility that displays information about compiled units, including dependences
805 on the corresponding sources files, and consistency of compilations.
806
807 @item
808 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
809 to delete files that are produced by the compiler, binder and linker.
810
811 @ifclear vms
812 @item
813 @ref{GNAT and Libraries}, describes the process of creating and using
814 Libraries with GNAT. It also describes how to recompile the GNAT run-time
815 library.
816
817 @item
818 @ref{Using the GNU make Utility}, describes some techniques for using
819 the GNAT toolset in Makefiles.
820 @end ifclear
821
822 @item
823 @ref{Memory Management Issues}, describes some useful predefined storage pools
824 and in particular the GNAT Debug Pool facility, which helps detect incorrect
825 memory references.
826 @ifclear vms
827 It also describes @command{gnatmem}, a utility that monitors dynamic
828 allocation and deallocation and helps detect ``memory leaks''.
829 @end ifclear
830
831 @item
832 @ref{Stack Related Facilities}, describes some useful tools associated with
833 stack checking and analysis.
834
835 @item
836 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
837 a utility that checks Ada code against a set of rules.
838
839 @item
840 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
841 a utility that generates empty but compilable bodies for library units.
842
843 @item
844 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
845 generate automatically Ada bindings from C and C++ headers.
846
847 @item
848 @ref{Other Utility Programs}, discusses several other GNAT utilities,
849 including @code{gnathtml}.
850
851 @ifclear vms
852 @item
853 @ref{Code Coverage and Profiling}, describes how to perform a structural
854 coverage and profile the execution of Ada programs.
855 @end ifclear
856
857 @item
858 @ref{Running and Debugging Ada Programs}, describes how to run and debug
859 Ada programs.
860
861 @ifset vms
862 @item
863 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
864 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
865 developed by Digital Equipment Corporation and currently supported by HP.}
866 for OpenVMS Alpha. This product was formerly known as DEC Ada,
867 @cindex DEC Ada
868 and for
869 historical compatibility reasons, the relevant libraries still use the
870 DEC prefix.
871 @end ifset
872
873 @item
874 @ref{Platform-Specific Information for the Run-Time Libraries},
875 describes the various run-time
876 libraries supported by GNAT on various platforms and explains how to
877 choose a particular library.
878
879 @item
880 @ref{Example of Binder Output File}, shows the source code for the binder
881 output file for a sample program.
882
883 @item
884 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
885 you deal with elaboration order issues.
886
887 @item
888 @ref{Conditional Compilation}, describes how to model conditional compilation,
889 both with Ada in general and with GNAT facilities in particular.
890
891 @item
892 @ref{Inline Assembler}, shows how to use the inline assembly facility
893 in an Ada program.
894
895 @item
896 @ref{Compatibility and Porting Guide}, contains sections on compatibility
897 of GNAT with other Ada development environments (including Ada 83 systems),
898 to assist in porting code from those environments.
899
900 @ifset unw
901 @item
902 @ref{Microsoft Windows Topics}, presents information relevant to the
903 Microsoft Windows platform.
904 @end ifset
905 @end itemize
906
907 @c *************************************************
908 @node What You Should Know before Reading This Guide
909 @c *************************************************
910 @unnumberedsec What You Should Know before Reading This Guide
911
912 @cindex Ada 95 Language Reference Manual
913 @cindex Ada 2005 Language Reference Manual
914 @noindent
915 This guide assumes a basic familiarity with the Ada 95 language, as
916 described in the International Standard ANSI/ISO/IEC-8652:1995, January
917 1995.
918 It does not require knowledge of the new features introduced by Ada 2005,
919 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
920 and Amendment 1).
921 Both reference manuals are included in the GNAT documentation
922 package.
923
924 @node Related Information
925 @unnumberedsec Related Information
926
927 @noindent
928 For further information about related tools, refer to the following
929 documents:
930
931 @itemize @bullet
932 @item
933 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
934 Reference Manual}, which contains all reference material for the GNAT
935 implementation of Ada.
936
937 @ifset unw
938 @item
939 @cite{Using the GNAT Programming Studio}, which describes the GPS
940 Integrated Development Environment.
941
942 @item
943 @cite{GNAT Programming Studio Tutorial}, which introduces the
944 main GPS features through examples.
945 @end ifset
946
947 @item
948 @cite{Ada 95 Reference Manual}, which contains reference
949 material for the Ada 95 programming language.
950
951 @item
952 @cite{Ada 2005 Reference Manual}, which contains reference
953 material for the Ada 2005 programming language.
954
955 @item
956 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
957 @ifset vms
958 in the GNU:[DOCS] directory,
959 @end ifset
960 for all details on the use of the GNU source-level debugger.
961
962 @item
963 @xref{Top,, The extensible self-documenting text editor, emacs,
964 GNU Emacs Manual},
965 @ifset vms
966 located in the GNU:[DOCS] directory if the EMACS kit is installed,
967 @end ifset
968 for full information on the extensible editor and programming
969 environment Emacs.
970
971 @end itemize
972
973 @c **************
974 @node Conventions
975 @unnumberedsec Conventions
976 @cindex Conventions
977 @cindex Typographical conventions
978
979 @noindent
980 Following are examples of the typographical and graphic conventions used
981 in this guide:
982
983 @itemize @bullet
984 @item
985 @code{Functions}, @command{utility program names}, @code{standard names},
986 and @code{classes}.
987
988 @item
989 @option{Option flags}
990
991 @item
992 @file{File names}, @samp{button names}, and @samp{field names}.
993
994 @item
995 @code{Variables}, @env{environment variables}, and @var{metasyntactic
996 variables}.
997
998 @item
999 @emph{Emphasis}.
1000
1001 @item
1002 @r{[}optional information or parameters@r{]}
1003
1004 @item
1005 Examples are described by text
1006 @smallexample
1007 and then shown this way.
1008 @end smallexample
1009 @end itemize
1010
1011 @noindent
1012 Commands that are entered by the user are preceded in this manual by the
1013 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1014 uses this sequence as a prompt, then the commands will appear exactly as
1015 you see them in the manual. If your system uses some other prompt, then
1016 the command will appear with the @code{$} replaced by whatever prompt
1017 character you are using.
1018
1019 @ifset unw
1020 Full file names are shown with the ``@code{/}'' character
1021 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1022 If you are using GNAT on a Windows platform, please note that
1023 the ``@code{\}'' character should be used instead.
1024 @end ifset
1025
1026 @c ****************************
1027 @node Getting Started with GNAT
1028 @chapter Getting Started with GNAT
1029
1030 @noindent
1031 This chapter describes some simple ways of using GNAT to build
1032 executable Ada programs.
1033 @ifset unw
1034 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1035 show how to use the command line environment.
1036 @ref{Introduction to GPS}, provides a brief
1037 introduction to the GNAT Programming Studio, a visually-oriented
1038 Integrated Development Environment for GNAT.
1039 GPS offers a graphical ``look and feel'', support for development in
1040 other programming languages, comprehensive browsing features, and
1041 many other capabilities.
1042 For information on GPS please refer to
1043 @cite{Using the GNAT Programming Studio}.
1044 @end ifset
1045
1046 @menu
1047 * Running GNAT::
1048 * Running a Simple Ada Program::
1049 * Running a Program with Multiple Units::
1050 * Using the gnatmake Utility::
1051 @ifset vms
1052 * Editing with Emacs::
1053 @end ifset
1054 @ifclear vms
1055 * Introduction to GPS::
1056 @end ifclear
1057 @end menu
1058
1059 @node Running GNAT
1060 @section Running GNAT
1061
1062 @noindent
1063 Three steps are needed to create an executable file from an Ada source
1064 file:
1065
1066 @enumerate
1067 @item
1068 The source file(s) must be compiled.
1069 @item
1070 The file(s) must be bound using the GNAT binder.
1071 @item
1072 All appropriate object files must be linked to produce an executable.
1073 @end enumerate
1074
1075 @noindent
1076 All three steps are most commonly handled by using the @command{gnatmake}
1077 utility program that, given the name of the main program, automatically
1078 performs the necessary compilation, binding and linking steps.
1079
1080 @node Running a Simple Ada Program
1081 @section Running a Simple Ada Program
1082
1083 @noindent
1084 Any text editor may be used to prepare an Ada program.
1085 (If @code{Emacs} is
1086 used, the optional Ada mode may be helpful in laying out the program.)
1087 The
1088 program text is a normal text file. We will assume in our initial
1089 example that you have used your editor to prepare the following
1090 standard format text file:
1091
1092 @smallexample @c ada
1093 @cartouche
1094 with Ada.Text_IO; use Ada.Text_IO;
1095 procedure Hello is
1096 begin
1097    Put_Line ("Hello WORLD!");
1098 end Hello;
1099 @end cartouche
1100 @end smallexample
1101
1102 @noindent
1103 This file should be named @file{hello.adb}.
1104 With the normal default file naming conventions, GNAT requires
1105 that each file
1106 contain a single compilation unit whose file name is the
1107 unit name,
1108 with periods replaced by hyphens; the
1109 extension is @file{ads} for a
1110 spec and @file{adb} for a body.
1111 You can override this default file naming convention by use of the
1112 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1113 Alternatively, if you want to rename your files according to this default
1114 convention, which is probably more convenient if you will be using GNAT
1115 for all your compilations, then the @code{gnatchop} utility
1116 can be used to generate correctly-named source files
1117 (@pxref{Renaming Files Using gnatchop}).
1118
1119 You can compile the program using the following command (@code{$} is used
1120 as the command prompt in the examples in this document):
1121
1122 @smallexample
1123 $ gcc -c hello.adb
1124 @end smallexample
1125
1126 @noindent
1127 @command{gcc} is the command used to run the compiler. This compiler is
1128 capable of compiling programs in several languages, including Ada and
1129 C. It assumes that you have given it an Ada program if the file extension is
1130 either @file{.ads} or @file{.adb}, and it will then call
1131 the GNAT compiler to compile the specified file.
1132
1133 @ifclear vms
1134 The @option{-c} switch is required. It tells @command{gcc} to only do a
1135 compilation. (For C programs, @command{gcc} can also do linking, but this
1136 capability is not used directly for Ada programs, so the @option{-c}
1137 switch must always be present.)
1138 @end ifclear
1139
1140 This compile command generates a file
1141 @file{hello.o}, which is the object
1142 file corresponding to your Ada program. It also generates
1143 an ``Ada Library Information'' file @file{hello.ali},
1144 which contains additional information used to check
1145 that an Ada program is consistent.
1146 To build an executable file,
1147 use @code{gnatbind} to bind the program
1148 and @command{gnatlink} to link it. The
1149 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1150 @file{ALI} file, but the default extension of @file{.ali} can
1151 be omitted. This means that in the most common case, the argument
1152 is simply the name of the main program:
1153
1154 @smallexample
1155 $ gnatbind hello
1156 $ gnatlink hello
1157 @end smallexample
1158
1159 @noindent
1160 A simpler method of carrying out these steps is to use
1161 @command{gnatmake},
1162 a master program that invokes all the required
1163 compilation, binding and linking tools in the correct order. In particular,
1164 @command{gnatmake} automatically recompiles any sources that have been
1165 modified since they were last compiled, or sources that depend
1166 on such modified sources, so that ``version skew'' is avoided.
1167 @cindex Version skew (avoided by @command{gnatmake})
1168
1169 @smallexample
1170 $ gnatmake hello.adb
1171 @end smallexample
1172
1173 @noindent
1174 The result is an executable program called @file{hello}, which can be
1175 run by entering:
1176
1177 @smallexample
1178 $ ^hello^RUN HELLO^
1179 @end smallexample
1180
1181 @noindent
1182 assuming that the current directory is on the search path
1183 for executable programs.
1184
1185 @noindent
1186 and, if all has gone well, you will see
1187
1188 @smallexample
1189 Hello WORLD!
1190 @end smallexample
1191
1192 @noindent
1193 appear in response to this command.
1194
1195 @c ****************************************
1196 @node Running a Program with Multiple Units
1197 @section Running a Program with Multiple Units
1198
1199 @noindent
1200 Consider a slightly more complicated example that has three files: a
1201 main program, and the spec and body of a package:
1202
1203 @smallexample @c ada
1204 @cartouche
1205 @group
1206 package Greetings is
1207    procedure Hello;
1208    procedure Goodbye;
1209 end Greetings;
1210
1211 with Ada.Text_IO; use Ada.Text_IO;
1212 package body Greetings is
1213    procedure Hello is
1214    begin
1215       Put_Line ("Hello WORLD!");
1216    end Hello;
1217
1218    procedure Goodbye is
1219    begin
1220       Put_Line ("Goodbye WORLD!");
1221    end Goodbye;
1222 end Greetings;
1223 @end group
1224
1225 @group
1226 with Greetings;
1227 procedure Gmain is
1228 begin
1229    Greetings.Hello;
1230    Greetings.Goodbye;
1231 end Gmain;
1232 @end group
1233 @end cartouche
1234 @end smallexample
1235
1236 @noindent
1237 Following the one-unit-per-file rule, place this program in the
1238 following three separate files:
1239
1240 @table @file
1241 @item greetings.ads
1242 spec of package @code{Greetings}
1243
1244 @item greetings.adb
1245 body of package @code{Greetings}
1246
1247 @item gmain.adb
1248 body of main program
1249 @end table
1250
1251 @noindent
1252 To build an executable version of
1253 this program, we could use four separate steps to compile, bind, and link
1254 the program, as follows:
1255
1256 @smallexample
1257 $ gcc -c gmain.adb
1258 $ gcc -c greetings.adb
1259 $ gnatbind gmain
1260 $ gnatlink gmain
1261 @end smallexample
1262
1263 @noindent
1264 Note that there is no required order of compilation when using GNAT.
1265 In particular it is perfectly fine to compile the main program first.
1266 Also, it is not necessary to compile package specs in the case where
1267 there is an accompanying body; you only need to compile the body. If you want
1268 to submit these files to the compiler for semantic checking and not code
1269 generation, then use the
1270 @option{-gnatc} switch:
1271
1272 @smallexample
1273 $ gcc -c greetings.ads -gnatc
1274 @end smallexample
1275
1276 @noindent
1277 Although the compilation can be done in separate steps as in the
1278 above example, in practice it is almost always more convenient
1279 to use the @command{gnatmake} tool. All you need to know in this case
1280 is the name of the main program's source file. The effect of the above four
1281 commands can be achieved with a single one:
1282
1283 @smallexample
1284 $ gnatmake gmain.adb
1285 @end smallexample
1286
1287 @noindent
1288 In the next section we discuss the advantages of using @command{gnatmake} in
1289 more detail.
1290
1291 @c *****************************
1292 @node Using the gnatmake Utility
1293 @section Using the @command{gnatmake} Utility
1294
1295 @noindent
1296 If you work on a program by compiling single components at a time using
1297 @command{gcc}, you typically keep track of the units you modify. In order to
1298 build a consistent system, you compile not only these units, but also any
1299 units that depend on the units you have modified.
1300 For example, in the preceding case,
1301 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1302 you edit @file{greetings.ads}, you must recompile both
1303 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1304 units that depend on @file{greetings.ads}.
1305
1306 @code{gnatbind} will warn you if you forget one of these compilation
1307 steps, so that it is impossible to generate an inconsistent program as a
1308 result of forgetting to do a compilation. Nevertheless it is tedious and
1309 error-prone to keep track of dependencies among units.
1310 One approach to handle the dependency-bookkeeping is to use a
1311 makefile. However, makefiles present maintenance problems of their own:
1312 if the dependencies change as you change the program, you must make
1313 sure that the makefile is kept up-to-date manually, which is also an
1314 error-prone process.
1315
1316 The @command{gnatmake} utility takes care of these details automatically.
1317 Invoke it using either one of the following forms:
1318
1319 @smallexample
1320 $ gnatmake gmain.adb
1321 $ gnatmake ^gmain^GMAIN^
1322 @end smallexample
1323
1324 @noindent
1325 The argument is the name of the file containing the main program;
1326 you may omit the extension. @command{gnatmake}
1327 examines the environment, automatically recompiles any files that need
1328 recompiling, and binds and links the resulting set of object files,
1329 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1330 In a large program, it
1331 can be extremely helpful to use @command{gnatmake}, because working out by hand
1332 what needs to be recompiled can be difficult.
1333
1334 Note that @command{gnatmake}
1335 takes into account all the Ada rules that
1336 establish dependencies among units. These include dependencies that result
1337 from inlining subprogram bodies, and from
1338 generic instantiation. Unlike some other
1339 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1340 found by the compiler on a previous compilation, which may possibly
1341 be wrong when sources change. @command{gnatmake} determines the exact set of
1342 dependencies from scratch each time it is run.
1343
1344 @ifset vms
1345 @node Editing with Emacs
1346 @section Editing with Emacs
1347 @cindex Emacs
1348
1349 @noindent
1350 Emacs is an extensible self-documenting text editor that is available in a
1351 separate VMSINSTAL kit.
1352
1353 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1354 click on the Emacs Help menu and run the Emacs Tutorial.
1355 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1356 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1357
1358 Documentation on Emacs and other tools is available in Emacs under the
1359 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1360 use the middle mouse button to select a topic (e.g.@: Emacs).
1361
1362 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1363 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1364 get to the Emacs manual.
1365 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1366 prompt.
1367
1368 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1369 which is sufficiently extensible to provide for a complete programming
1370 environment and shell for the sophisticated user.
1371 @end ifset
1372
1373 @ifclear vms
1374 @node Introduction to GPS
1375 @section Introduction to GPS
1376 @cindex GPS (GNAT Programming Studio)
1377 @cindex GNAT Programming Studio (GPS)
1378 @noindent
1379 Although the command line interface (@command{gnatmake}, etc.) alone
1380 is sufficient, a graphical Interactive Development
1381 Environment can make it easier for you to compose, navigate, and debug
1382 programs.  This section describes the main features of GPS
1383 (``GNAT Programming Studio''), the GNAT graphical IDE.
1384 You will see how to use GPS to build and debug an executable, and
1385 you will also learn some of the basics of the GNAT ``project'' facility.
1386
1387 GPS enables you to do much more than is presented here;
1388 e.g., you can produce a call graph, interface to a third-party
1389 Version Control System, and inspect the generated assembly language
1390 for a program.
1391 Indeed, GPS also supports languages other than Ada.
1392 Such additional information, and an explanation of all of the GPS menu
1393 items. may be found in the on-line help, which includes
1394 a user's guide and a tutorial (these are also accessible from the GNAT
1395 startup menu).
1396
1397 @menu
1398 * Building a New Program with GPS::
1399 * Simple Debugging with GPS::
1400 @end menu
1401
1402 @node Building a New Program with GPS
1403 @subsection Building a New Program with GPS
1404 @noindent
1405 GPS invokes the GNAT compilation tools using information
1406 contained in a @emph{project} (also known as a @emph{project file}):
1407 a collection of properties such
1408 as source directories, identities of main subprograms, tool switches, etc.,
1409 and their associated values.
1410 See @ref{GNAT Project Manager} for details.
1411 In order to run GPS, you will need to either create a new project
1412 or else open an existing one.
1413
1414 This section will explain how you can use GPS to create a project,
1415 to associate Ada source files with a project, and to build and run
1416 programs.
1417
1418 @enumerate
1419 @item @emph{Creating a project}
1420
1421 Invoke GPS, either from the command line or the platform's IDE.
1422 After it starts, GPS will display a ``Welcome'' screen with three
1423 radio buttons:
1424
1425 @itemize @bullet
1426 @item
1427 @code{Start with default project in directory}
1428
1429 @item
1430 @code{Create new project with wizard}
1431
1432 @item
1433 @code{Open existing project}
1434 @end itemize
1435
1436 @noindent
1437 Select @code{Create new project with wizard} and press @code{OK}.
1438 A new window will appear.  In the text box labeled with
1439 @code{Enter the name of the project to create}, type @file{sample}
1440 as the project name.
1441 In the next box, browse to choose the directory in which you
1442 would like to create the project file.
1443 After selecting an appropriate directory, press @code{Forward}.
1444
1445 A window will appear with the title
1446 @code{Version Control System Configuration}.
1447 Simply press @code{Forward}.
1448
1449 A window will appear with the title
1450 @code{Please select the source directories for this project}.
1451 The directory that you specified for the project file will be selected
1452 by default as the one to use for sources; simply press @code{Forward}.
1453
1454 A window will appear with the title
1455 @code{Please select the build directory for this project}.
1456 The directory that you specified for the project file will be selected
1457 by default for object files and executables;
1458 simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the main units for this project}.
1462 You will supply this information later, after creating the source file.
1463 Simply press @code{Forward} for now.
1464
1465 A window will appear with the title
1466 @code{Please select the switches to build the project}.
1467 Press @code{Apply}.  This will create a project file named
1468 @file{sample.prj} in the directory that you had specified.
1469
1470 @item @emph{Creating and saving the source file}
1471
1472 After you create the new project, a GPS window will appear, which is
1473 partitioned into two main sections:
1474
1475 @itemize @bullet
1476 @item
1477 A @emph{Workspace area}, initially greyed out, which you will use for
1478 creating and editing source files
1479
1480 @item
1481 Directly below, a @emph{Messages area}, which initially displays a
1482 ``Welcome'' message.
1483 (If the Messages area is not visible, drag its border upward to expand it.)
1484 @end itemize
1485
1486 @noindent
1487 Select @code{File} on the menu bar, and then the @code{New} command.
1488 The Workspace area will become white, and you can now
1489 enter the source program explicitly.
1490 Type the following text
1491
1492 @smallexample @c ada
1493 @group
1494 with Ada.Text_IO; use Ada.Text_IO;
1495 procedure Hello is
1496 begin
1497   Put_Line("Hello from GPS!");
1498 end Hello;
1499 @end group
1500 @end smallexample
1501
1502 @noindent
1503 Select @code{File}, then @code{Save As}, and enter the source file name
1504 @file{hello.adb}.
1505 The file will be saved in the same directory you specified as the
1506 location of the default project file.
1507
1508 @item @emph{Updating the project file}
1509
1510 You need to add the new source file to the project.
1511 To do this, select
1512 the @code{Project} menu and then @code{Edit project properties}.
1513 Click the @code{Main files} tab on the left, and then the
1514 @code{Add} button.
1515 Choose @file{hello.adb} from the list, and press @code{Open}.
1516 The project settings window will reflect this action.
1517 Click @code{OK}.
1518
1519 @item @emph{Building and running the program}
1520
1521 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1522 and select @file{hello.adb}.
1523 The Messages window will display the resulting invocations of @command{gcc},
1524 @command{gnatbind}, and @command{gnatlink}
1525 (reflecting the default switch settings from the
1526 project file that you created) and then a ``successful compilation/build''
1527 message.
1528
1529 To run the program, choose the @code{Build} menu, then @code{Run}, and
1530 select @command{hello}.
1531 An @emph{Arguments Selection} window will appear.
1532 There are no command line arguments, so just click @code{OK}.
1533
1534 The Messages window will now display the program's output (the string
1535 @code{Hello from GPS}), and at the bottom of the GPS window a status
1536 update is displayed (@code{Run: hello}).
1537 Close the GPS window (or select @code{File}, then @code{Exit}) to
1538 terminate this GPS session.
1539 @end enumerate
1540
1541 @node Simple Debugging with GPS
1542 @subsection Simple Debugging with GPS
1543 @noindent
1544 This section illustrates basic debugging techniques (setting breakpoints,
1545 examining/modifying variables, single stepping).
1546
1547 @enumerate
1548 @item @emph{Opening a project}
1549
1550 Start GPS and select @code{Open existing project}; browse to
1551 specify the project file @file{sample.prj} that you had created in the
1552 earlier example.
1553
1554 @item @emph{Creating a source file}
1555
1556 Select @code{File}, then @code{New}, and type in the following program:
1557
1558 @smallexample @c ada
1559 @group
1560 with Ada.Text_IO; use Ada.Text_IO;
1561 procedure Example is
1562    Line : String (1..80);
1563    N    : Natural;
1564 begin
1565    Put_Line("Type a line of text at each prompt; an empty line to exit");
1566    loop
1567       Put(": ");
1568       Get_Line (Line, N);
1569       Put_Line (Line (1..N) );
1570       exit when N=0;
1571    end loop;
1572 end Example;
1573 @end group
1574 @end smallexample
1575
1576 @noindent
1577 Select @code{File}, then @code{Save as}, and enter the file name
1578 @file{example.adb}.
1579
1580 @item @emph{Updating the project file}
1581
1582 Add @code{Example} as a new main unit for the project:
1583 @enumerate a
1584 @item
1585 Select @code{Project}, then @code{Edit Project Properties}.
1586
1587 @item
1588 Select the @code{Main files} tab, click @code{Add}, then
1589 select the file @file{example.adb} from the list, and
1590 click @code{Open}.
1591 You will see the file name appear in the list of main units
1592
1593 @item
1594 Click @code{OK}
1595 @end enumerate
1596
1597 @item @emph{Building/running the executable}
1598
1599 To build the executable
1600 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1601
1602 Run the program to see its effect (in the Messages area).
1603 Each line that you enter is displayed; an empty line will
1604 cause the loop to exit and the program to terminate.
1605
1606 @item @emph{Debugging the program}
1607
1608 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1609 which are required for debugging, are on by default when you create
1610 a new project.
1611 Thus unless you intentionally remove these settings, you will be able
1612 to debug any program that you develop using GPS.
1613
1614 @enumerate a
1615 @item @emph{Initializing}
1616
1617 Select @code{Debug}, then @code{Initialize}, then @file{example}
1618
1619 @item @emph{Setting a breakpoint}
1620
1621 After performing the initialization step, you will observe a small
1622 icon to the right of each line number.
1623 This serves as a toggle for breakpoints; clicking the icon will
1624 set a breakpoint at the corresponding line (the icon will change to
1625 a red circle with an ``x''), and clicking it again
1626 will remove the breakpoint / reset the icon.
1627
1628 For purposes of this example, set a breakpoint at line 10 (the
1629 statement @code{Put_Line@ (Line@ (1..N));}
1630
1631 @item @emph{Starting program execution}
1632
1633 Select @code{Debug}, then @code{Run}.  When the
1634 @code{Program Arguments} window appears, click @code{OK}.
1635 A console window will appear; enter some line of text,
1636 e.g.@: @code{abcde}, at the prompt.
1637 The program will pause execution when it gets to the
1638 breakpoint, and the corresponding line is highlighted.
1639
1640 @item @emph{Examining a variable}
1641
1642 Move the mouse over one of the occurrences of the variable @code{N}.
1643 You will see the value (5) displayed, in ``tool tip'' fashion.
1644 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1645 You will see information about @code{N} appear in the @code{Debugger Data}
1646 pane, showing the value as 5.
1647
1648 @item @emph{Assigning a new value to a variable}
1649
1650 Right click on the @code{N} in the @code{Debugger Data} pane, and
1651 select @code{Set value of N}.
1652 When the input window appears, enter the value @code{4} and click
1653 @code{OK}.
1654 This value does not automatically appear in the @code{Debugger Data}
1655 pane; to see it, right click again on the @code{N} in the
1656 @code{Debugger Data} pane and select @code{Update value}.
1657 The new value, 4, will appear in red.
1658
1659 @item @emph{Single stepping}
1660
1661 Select @code{Debug}, then @code{Next}.
1662 This will cause the next statement to be executed, in this case the
1663 call of @code{Put_Line} with the string slice.
1664 Notice in the console window that the displayed string is simply
1665 @code{abcd} and not @code{abcde} which you had entered.
1666 This is because the upper bound of the slice is now 4 rather than 5.
1667
1668 @item @emph{Removing a breakpoint}
1669
1670 Toggle the breakpoint icon at line 10.
1671
1672 @item @emph{Resuming execution from a breakpoint}
1673
1674 Select @code{Debug}, then @code{Continue}.
1675 The program will reach the next iteration of the loop, and
1676 wait for input after displaying the prompt.
1677 This time, just hit the @kbd{Enter} key.
1678 The value of @code{N} will be 0, and the program will terminate.
1679 The console window will disappear.
1680 @end enumerate
1681 @end enumerate
1682 @end ifclear
1683
1684 @node The GNAT Compilation Model
1685 @chapter The GNAT Compilation Model
1686 @cindex GNAT compilation model
1687 @cindex Compilation model
1688
1689 @menu
1690 * Source Representation::
1691 * Foreign Language Representation::
1692 * File Naming Rules::
1693 * Using Other File Names::
1694 * Alternative File Naming Schemes::
1695 * Generating Object Files::
1696 * Source Dependencies::
1697 * The Ada Library Information Files::
1698 * Binding an Ada Program::
1699 * Mixed Language Programming::
1700 @ifclear vms
1701 * Building Mixed Ada & C++ Programs::
1702 * Comparison between GNAT and C/C++ Compilation Models::
1703 @end ifclear
1704 * Comparison between GNAT and Conventional Ada Library Models::
1705 @ifset vms
1706 * Placement of temporary files::
1707 @end ifset
1708 @end menu
1709
1710 @noindent
1711 This chapter describes the compilation model used by GNAT. Although
1712 similar to that used by other languages, such as C and C++, this model
1713 is substantially different from the traditional Ada compilation models,
1714 which are based on a library. The model is initially described without
1715 reference to the library-based model. If you have not previously used an
1716 Ada compiler, you need only read the first part of this chapter. The
1717 last section describes and discusses the differences between the GNAT
1718 model and the traditional Ada compiler models. If you have used other
1719 Ada compilers, this section will help you to understand those
1720 differences, and the advantages of the GNAT model.
1721
1722 @node Source Representation
1723 @section Source Representation
1724 @cindex Latin-1
1725
1726 @noindent
1727 Ada source programs are represented in standard text files, using
1728 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1729 7-bit ASCII set, plus additional characters used for
1730 representing foreign languages (@pxref{Foreign Language Representation}
1731 for support of non-USA character sets). The format effector characters
1732 are represented using their standard ASCII encodings, as follows:
1733
1734 @table @code
1735 @item VT
1736 @findex VT
1737 Vertical tab, @code{16#0B#}
1738
1739 @item HT
1740 @findex HT
1741 Horizontal tab, @code{16#09#}
1742
1743 @item CR
1744 @findex CR
1745 Carriage return, @code{16#0D#}
1746
1747 @item LF
1748 @findex LF
1749 Line feed, @code{16#0A#}
1750
1751 @item FF
1752 @findex FF
1753 Form feed, @code{16#0C#}
1754 @end table
1755
1756 @noindent
1757 Source files are in standard text file format. In addition, GNAT will
1758 recognize a wide variety of stream formats, in which the end of
1759 physical lines is marked by any of the following sequences:
1760 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1761 in accommodating files that are imported from other operating systems.
1762
1763 @cindex End of source file
1764 @cindex Source file, end
1765 @findex SUB
1766 The end of a source file is normally represented by the physical end of
1767 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1768 recognized as signalling the end of the source file. Again, this is
1769 provided for compatibility with other operating systems where this
1770 code is used to represent the end of file.
1771
1772 Each file contains a single Ada compilation unit, including any pragmas
1773 associated with the unit. For example, this means you must place a
1774 package declaration (a package @dfn{spec}) and the corresponding body in
1775 separate files. An Ada @dfn{compilation} (which is a sequence of
1776 compilation units) is represented using a sequence of files. Similarly,
1777 you will place each subunit or child unit in a separate file.
1778
1779 @node Foreign Language Representation
1780 @section Foreign Language Representation
1781
1782 @noindent
1783 GNAT supports the standard character sets defined in Ada as well as
1784 several other non-standard character sets for use in localized versions
1785 of the compiler (@pxref{Character Set Control}).
1786 @menu
1787 * Latin-1::
1788 * Other 8-Bit Codes::
1789 * Wide Character Encodings::
1790 @end menu
1791
1792 @node Latin-1
1793 @subsection Latin-1
1794 @cindex Latin-1
1795
1796 @noindent
1797 The basic character set is Latin-1. This character set is defined by ISO
1798 standard 8859, part 1. The lower half (character codes @code{16#00#}
1799 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1800 is used to represent additional characters. These include extended letters
1801 used by European languages, such as French accents, the vowels with umlauts
1802 used in German, and the extra letter A-ring used in Swedish.
1803
1804 @findex Ada.Characters.Latin_1
1805 For a complete list of Latin-1 codes and their encodings, see the source
1806 file of library unit @code{Ada.Characters.Latin_1} in file
1807 @file{a-chlat1.ads}.
1808 You may use any of these extended characters freely in character or
1809 string literals. In addition, the extended characters that represent
1810 letters can be used in identifiers.
1811
1812 @node Other 8-Bit Codes
1813 @subsection Other 8-Bit Codes
1814
1815 @noindent
1816 GNAT also supports several other 8-bit coding schemes:
1817
1818 @table @asis
1819 @item ISO 8859-2 (Latin-2)
1820 @cindex Latin-2
1821 @cindex ISO 8859-2
1822 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1823 equivalence.
1824
1825 @item ISO 8859-3 (Latin-3)
1826 @cindex Latin-3
1827 @cindex ISO 8859-3
1828 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-4 (Latin-4)
1832 @cindex Latin-4
1833 @cindex ISO 8859-4
1834 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-5 (Cyrillic)
1838 @cindex ISO 8859-5
1839 @cindex Cyrillic
1840 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1841 lowercase equivalence.
1842
1843 @item ISO 8859-15 (Latin-9)
1844 @cindex ISO 8859-15
1845 @cindex Latin-9
1846 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1847 lowercase equivalence
1848
1849 @item IBM PC (code page 437)
1850 @cindex code page 437
1851 This code page is the normal default for PCs in the U.S. It corresponds
1852 to the original IBM PC character set. This set has some, but not all, of
1853 the extended Latin-1 letters, but these letters do not have the same
1854 encoding as Latin-1. In this mode, these letters are allowed in
1855 identifiers with uppercase and lowercase equivalence.
1856
1857 @item IBM PC (code page 850)
1858 @cindex code page 850
1859 This code page is a modification of 437 extended to include all the
1860 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1861 mode, all these letters are allowed in identifiers with uppercase and
1862 lowercase equivalence.
1863
1864 @item Full Upper 8-bit
1865 Any character in the range 80-FF allowed in identifiers, and all are
1866 considered distinct. In other words, there are no uppercase and lowercase
1867 equivalences in this range. This is useful in conjunction with
1868 certain encoding schemes used for some foreign character sets (e.g.,
1869 the typical method of representing Chinese characters on the PC).
1870
1871 @item No Upper-Half
1872 No upper-half characters in the range 80-FF are allowed in identifiers.
1873 This gives Ada 83 compatibility for identifier names.
1874 @end table
1875
1876 @noindent
1877 For precise data on the encodings permitted, and the uppercase and lowercase
1878 equivalences that are recognized, see the file @file{csets.adb} in
1879 the GNAT compiler sources. You will need to obtain a full source release
1880 of GNAT to obtain this file.
1881
1882 @node Wide Character Encodings
1883 @subsection Wide Character Encodings
1884
1885 @noindent
1886 GNAT allows wide character codes to appear in character and string
1887 literals, and also optionally in identifiers, by means of the following
1888 possible encoding schemes:
1889
1890 @table @asis
1891
1892 @item Hex Coding
1893 In this encoding, a wide character is represented by the following five
1894 character sequence:
1895
1896 @smallexample
1897 ESC a b c d
1898 @end smallexample
1899
1900 @noindent
1901 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1902 characters (using uppercase letters) of the wide character code. For
1903 example, ESC A345 is used to represent the wide character with code
1904 @code{16#A345#}.
1905 This scheme is compatible with use of the full Wide_Character set.
1906
1907 @item Upper-Half Coding
1908 @cindex Upper-Half Coding
1909 The wide character with encoding @code{16#abcd#} where the upper bit is on
1910 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1911 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1912 character, but is not required to be in the upper half. This method can
1913 be also used for shift-JIS or EUC, where the internal coding matches the
1914 external coding.
1915
1916 @item Shift JIS Coding
1917 @cindex Shift JIS Coding
1918 A wide character is represented by a two-character sequence,
1919 @code{16#ab#} and
1920 @code{16#cd#}, with the restrictions described for upper-half encoding as
1921 described above. The internal character code is the corresponding JIS
1922 character according to the standard algorithm for Shift-JIS
1923 conversion. Only characters defined in the JIS code set table can be
1924 used with this encoding method.
1925
1926 @item EUC Coding
1927 @cindex EUC Coding
1928 A wide character is represented by a two-character sequence
1929 @code{16#ab#} and
1930 @code{16#cd#}, with both characters being in the upper half. The internal
1931 character code is the corresponding JIS character according to the EUC
1932 encoding algorithm. Only characters defined in the JIS code set table
1933 can be used with this encoding method.
1934
1935 @item UTF-8 Coding
1936 A wide character is represented using
1937 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1938 10646-1/Am.2. Depending on the character value, the representation
1939 is a one, two, or three byte sequence:
1940 @smallexample
1941 @iftex
1942 @leftskip=.7cm
1943 @end iftex
1944 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1945 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1946 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1947
1948 @end smallexample
1949
1950 @noindent
1951 where the @var{xxx} bits correspond to the left-padded bits of the
1952 16-bit character value. Note that all lower half ASCII characters
1953 are represented as ASCII bytes and all upper half characters and
1954 other wide characters are represented as sequences of upper-half
1955 (The full UTF-8 scheme allows for encoding 31-bit characters as
1956 6-byte sequences, but in this implementation, all UTF-8 sequences
1957 of four or more bytes length will be treated as illegal).
1958 @item Brackets Coding
1959 In this encoding, a wide character is represented by the following eight
1960 character sequence:
1961
1962 @smallexample
1963 [ " a b c d " ]
1964 @end smallexample
1965
1966 @noindent
1967 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1968 characters (using uppercase letters) of the wide character code. For
1969 example, [``A345''] is used to represent the wide character with code
1970 @code{16#A345#}. It is also possible (though not required) to use the
1971 Brackets coding for upper half characters. For example, the code
1972 @code{16#A3#} can be represented as @code{[``A3'']}.
1973
1974 This scheme is compatible with use of the full Wide_Character set,
1975 and is also the method used for wide character encoding in the standard
1976 ACVC (Ada Compiler Validation Capability) test suite distributions.
1977
1978 @end table
1979
1980 @noindent
1981 Note: Some of these coding schemes do not permit the full use of the
1982 Ada character set. For example, neither Shift JIS, nor EUC allow the
1983 use of the upper half of the Latin-1 set.
1984
1985 @node File Naming Rules
1986 @section File Naming Rules
1987
1988 @noindent
1989 The default file name is determined by the name of the unit that the
1990 file contains. The name is formed by taking the full expanded name of
1991 the unit and replacing the separating dots with hyphens and using
1992 ^lowercase^uppercase^ for all letters.
1993
1994 An exception arises if the file name generated by the above rules starts
1995 with one of the characters
1996 @ifset vms
1997 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1998 @end ifset
1999 @ifclear vms
2000 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2001 @end ifclear
2002 and the second character is a
2003 minus. In this case, the character ^tilde^dollar sign^ is used in place
2004 of the minus. The reason for this special rule is to avoid clashes with
2005 the standard names for child units of the packages System, Ada,
2006 Interfaces, and GNAT, which use the prefixes
2007 @ifset vms
2008 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2009 @end ifset
2010 @ifclear vms
2011 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2012 @end ifclear
2013 respectively.
2014
2015 The file extension is @file{.ads} for a spec and
2016 @file{.adb} for a body. The following list shows some
2017 examples of these rules.
2018
2019 @table @file
2020 @item main.ads
2021 Main (spec)
2022 @item main.adb
2023 Main (body)
2024 @item arith_functions.ads
2025 Arith_Functions (package spec)
2026 @item arith_functions.adb
2027 Arith_Functions (package body)
2028 @item func-spec.ads
2029 Func.Spec (child package spec)
2030 @item func-spec.adb
2031 Func.Spec (child package body)
2032 @item main-sub.adb
2033 Sub (subunit of Main)
2034 @item ^a~bad.adb^A$BAD.ADB^
2035 A.Bad (child package body)
2036 @end table
2037
2038 @noindent
2039 Following these rules can result in excessively long
2040 file names if corresponding
2041 unit names are long (for example, if child units or subunits are
2042 heavily nested). An option is available to shorten such long file names
2043 (called file name ``krunching''). This may be particularly useful when
2044 programs being developed with GNAT are to be used on operating systems
2045 with limited file name lengths. @xref{Using gnatkr}.
2046
2047 Of course, no file shortening algorithm can guarantee uniqueness over
2048 all possible unit names; if file name krunching is used, it is your
2049 responsibility to ensure no name clashes occur. Alternatively you
2050 can specify the exact file names that you want used, as described
2051 in the next section. Finally, if your Ada programs are migrating from a
2052 compiler with a different naming convention, you can use the gnatchop
2053 utility to produce source files that follow the GNAT naming conventions.
2054 (For details @pxref{Renaming Files Using gnatchop}.)
2055
2056 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2057 systems, case is not significant. So for example on @code{Windows XP}
2058 if the canonical name is @code{main-sub.adb}, you can use the file name
2059 @code{Main-Sub.adb} instead. However, case is significant for other
2060 operating systems, so for example, if you want to use other than
2061 canonically cased file names on a Unix system, you need to follow
2062 the procedures described in the next section.
2063
2064 @node Using Other File Names
2065 @section Using Other File Names
2066 @cindex File names
2067
2068 @noindent
2069 In the previous section, we have described the default rules used by
2070 GNAT to determine the file name in which a given unit resides. It is
2071 often convenient to follow these default rules, and if you follow them,
2072 the compiler knows without being explicitly told where to find all
2073 the files it needs.
2074
2075 However, in some cases, particularly when a program is imported from
2076 another Ada compiler environment, it may be more convenient for the
2077 programmer to specify which file names contain which units. GNAT allows
2078 arbitrary file names to be used by means of the Source_File_Name pragma.
2079 The form of this pragma is as shown in the following examples:
2080 @cindex Source_File_Name pragma
2081
2082 @smallexample @c ada
2083 @cartouche
2084 pragma Source_File_Name (My_Utilities.Stacks,
2085   Spec_File_Name => "myutilst_a.ada");
2086 pragma Source_File_name (My_Utilities.Stacks,
2087   Body_File_Name => "myutilst.ada");
2088 @end cartouche
2089 @end smallexample
2090
2091 @noindent
2092 As shown in this example, the first argument for the pragma is the unit
2093 name (in this example a child unit). The second argument has the form
2094 of a named association. The identifier
2095 indicates whether the file name is for a spec or a body;
2096 the file name itself is given by a string literal.
2097
2098 The source file name pragma is a configuration pragma, which means that
2099 normally it will be placed in the @file{gnat.adc}
2100 file used to hold configuration
2101 pragmas that apply to a complete compilation environment.
2102 For more details on how the @file{gnat.adc} file is created and used
2103 see @ref{Handling of Configuration Pragmas}.
2104 @cindex @file{gnat.adc}
2105
2106 @ifclear vms
2107 GNAT allows completely arbitrary file names to be specified using the
2108 source file name pragma. However, if the file name specified has an
2109 extension other than @file{.ads} or @file{.adb} it is necessary to use
2110 a special syntax when compiling the file. The name in this case must be
2111 preceded by the special sequence @option{-x} followed by a space and the name
2112 of the language, here @code{ada}, as in:
2113
2114 @smallexample
2115 $ gcc -c -x ada peculiar_file_name.sim
2116 @end smallexample
2117 @end ifclear
2118
2119 @noindent
2120 @command{gnatmake} handles non-standard file names in the usual manner (the
2121 non-standard file name for the main program is simply used as the
2122 argument to gnatmake). Note that if the extension is also non-standard,
2123 then it must be included in the @command{gnatmake} command, it may not
2124 be omitted.
2125
2126 @node Alternative File Naming Schemes
2127 @section Alternative File Naming Schemes
2128 @cindex File naming schemes, alternative
2129 @cindex File names
2130
2131 In the previous section, we described the use of the @code{Source_File_Name}
2132 pragma to allow arbitrary names to be assigned to individual source files.
2133 However, this approach requires one pragma for each file, and especially in
2134 large systems can result in very long @file{gnat.adc} files, and also create
2135 a maintenance problem.
2136
2137 GNAT also provides a facility for specifying systematic file naming schemes
2138 other than the standard default naming scheme previously described. An
2139 alternative scheme for naming is specified by the use of
2140 @code{Source_File_Name} pragmas having the following format:
2141 @cindex Source_File_Name pragma
2142
2143 @smallexample @c ada
2144 pragma Source_File_Name (
2145    Spec_File_Name  => FILE_NAME_PATTERN
2146  @r{[},Casing          => CASING_SPEC@r{]}
2147  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2148
2149 pragma Source_File_Name (
2150    Body_File_Name  => FILE_NAME_PATTERN
2151  @r{[},Casing          => CASING_SPEC@r{]}
2152  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2153
2154 pragma Source_File_Name (
2155    Subunit_File_Name  => FILE_NAME_PATTERN
2156  @r{[},Casing             => CASING_SPEC@r{]}
2157  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2158
2159 FILE_NAME_PATTERN ::= STRING_LITERAL
2160 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2161 @end smallexample
2162
2163 @noindent
2164 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2165 It contains a single asterisk character, and the unit name is substituted
2166 systematically for this asterisk. The optional parameter
2167 @code{Casing} indicates
2168 whether the unit name is to be all upper-case letters, all lower-case letters,
2169 or mixed-case. If no
2170 @code{Casing} parameter is used, then the default is all
2171 ^lower-case^upper-case^.
2172
2173 The optional @code{Dot_Replacement} string is used to replace any periods
2174 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2175 argument is used then separating dots appear unchanged in the resulting
2176 file name.
2177 Although the above syntax indicates that the
2178 @code{Casing} argument must appear
2179 before the @code{Dot_Replacement} argument, but it
2180 is also permissible to write these arguments in the opposite order.
2181
2182 As indicated, it is possible to specify different naming schemes for
2183 bodies, specs, and subunits. Quite often the rule for subunits is the
2184 same as the rule for bodies, in which case, there is no need to give
2185 a separate @code{Subunit_File_Name} rule, and in this case the
2186 @code{Body_File_name} rule is used for subunits as well.
2187
2188 The separate rule for subunits can also be used to implement the rather
2189 unusual case of a compilation environment (e.g.@: a single directory) which
2190 contains a subunit and a child unit with the same unit name. Although
2191 both units cannot appear in the same partition, the Ada Reference Manual
2192 allows (but does not require) the possibility of the two units coexisting
2193 in the same environment.
2194
2195 The file name translation works in the following steps:
2196
2197 @itemize @bullet
2198
2199 @item
2200 If there is a specific @code{Source_File_Name} pragma for the given unit,
2201 then this is always used, and any general pattern rules are ignored.
2202
2203 @item
2204 If there is a pattern type @code{Source_File_Name} pragma that applies to
2205 the unit, then the resulting file name will be used if the file exists. If
2206 more than one pattern matches, the latest one will be tried first, and the
2207 first attempt resulting in a reference to a file that exists will be used.
2208
2209 @item
2210 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2211 for which the corresponding file exists, then the standard GNAT default
2212 naming rules are used.
2213
2214 @end itemize
2215
2216 @noindent
2217 As an example of the use of this mechanism, consider a commonly used scheme
2218 in which file names are all lower case, with separating periods copied
2219 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2220 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2221 two pragmas appear:
2222
2223 @smallexample @c ada
2224 pragma Source_File_Name
2225   (Spec_File_Name => "*.1.ada");
2226 pragma Source_File_Name
2227   (Body_File_Name => "*.2.ada");
2228 @end smallexample
2229
2230 @noindent
2231 The default GNAT scheme is actually implemented by providing the following
2232 default pragmas internally:
2233
2234 @smallexample @c ada
2235 pragma Source_File_Name
2236   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2237 pragma Source_File_Name
2238   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2239 @end smallexample
2240
2241 @noindent
2242 Our final example implements a scheme typically used with one of the
2243 Ada 83 compilers, where the separator character for subunits was ``__''
2244 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2245 by adding @file{.ADA}, and subunits by
2246 adding @file{.SEP}. All file names were
2247 upper case. Child units were not present of course since this was an
2248 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2249 the same double underscore separator for child units.
2250
2251 @smallexample @c ada
2252 pragma Source_File_Name
2253   (Spec_File_Name => "*_.ADA",
2254    Dot_Replacement => "__",
2255    Casing = Uppercase);
2256 pragma Source_File_Name
2257   (Body_File_Name => "*.ADA",
2258    Dot_Replacement => "__",
2259    Casing = Uppercase);
2260 pragma Source_File_Name
2261   (Subunit_File_Name => "*.SEP",
2262    Dot_Replacement => "__",
2263    Casing = Uppercase);
2264 @end smallexample
2265
2266 @node Generating Object Files
2267 @section Generating Object Files
2268
2269 @noindent
2270 An Ada program consists of a set of source files, and the first step in
2271 compiling the program is to generate the corresponding object files.
2272 These are generated by compiling a subset of these source files.
2273 The files you need to compile are the following:
2274
2275 @itemize @bullet
2276 @item
2277 If a package spec has no body, compile the package spec to produce the
2278 object file for the package.
2279
2280 @item
2281 If a package has both a spec and a body, compile the body to produce the
2282 object file for the package. The source file for the package spec need
2283 not be compiled in this case because there is only one object file, which
2284 contains the code for both the spec and body of the package.
2285
2286 @item
2287 For a subprogram, compile the subprogram body to produce the object file
2288 for the subprogram. The spec, if one is present, is as usual in a
2289 separate file, and need not be compiled.
2290
2291 @item
2292 @cindex Subunits
2293 In the case of subunits, only compile the parent unit. A single object
2294 file is generated for the entire subunit tree, which includes all the
2295 subunits.
2296
2297 @item
2298 Compile child units independently of their parent units
2299 (though, of course, the spec of all the ancestor unit must be present in order
2300 to compile a child unit).
2301
2302 @item
2303 @cindex Generics
2304 Compile generic units in the same manner as any other units. The object
2305 files in this case are small dummy files that contain at most the
2306 flag used for elaboration checking. This is because GNAT always handles generic
2307 instantiation by means of macro expansion. However, it is still necessary to
2308 compile generic units, for dependency checking and elaboration purposes.
2309 @end itemize
2310
2311 @noindent
2312 The preceding rules describe the set of files that must be compiled to
2313 generate the object files for a program. Each object file has the same
2314 name as the corresponding source file, except that the extension is
2315 @file{.o} as usual.
2316
2317 You may wish to compile other files for the purpose of checking their
2318 syntactic and semantic correctness. For example, in the case where a
2319 package has a separate spec and body, you would not normally compile the
2320 spec. However, it is convenient in practice to compile the spec to make
2321 sure it is error-free before compiling clients of this spec, because such
2322 compilations will fail if there is an error in the spec.
2323
2324 GNAT provides an option for compiling such files purely for the
2325 purposes of checking correctness; such compilations are not required as
2326 part of the process of building a program. To compile a file in this
2327 checking mode, use the @option{-gnatc} switch.
2328
2329 @node Source Dependencies
2330 @section Source Dependencies
2331
2332 @noindent
2333 A given object file clearly depends on the source file which is compiled
2334 to produce it. Here we are using @dfn{depends} in the sense of a typical
2335 @code{make} utility; in other words, an object file depends on a source
2336 file if changes to the source file require the object file to be
2337 recompiled.
2338 In addition to this basic dependency, a given object may depend on
2339 additional source files as follows:
2340
2341 @itemize @bullet
2342 @item
2343 If a file being compiled @code{with}'s a unit @var{X}, the object file
2344 depends on the file containing the spec of unit @var{X}. This includes
2345 files that are @code{with}'ed implicitly either because they are parents
2346 of @code{with}'ed child units or they are run-time units required by the
2347 language constructs used in a particular unit.
2348
2349 @item
2350 If a file being compiled instantiates a library level generic unit, the
2351 object file depends on both the spec and body files for this generic
2352 unit.
2353
2354 @item
2355 If a file being compiled instantiates a generic unit defined within a
2356 package, the object file depends on the body file for the package as
2357 well as the spec file.
2358
2359 @item
2360 @findex Inline
2361 @cindex @option{-gnatn} switch
2362 If a file being compiled contains a call to a subprogram for which
2363 pragma @code{Inline} applies and inlining is activated with the
2364 @option{-gnatn} switch, the object file depends on the file containing the
2365 body of this subprogram as well as on the file containing the spec. Note
2366 that for inlining to actually occur as a result of the use of this switch,
2367 it is necessary to compile in optimizing mode.
2368
2369 @cindex @option{-gnatN} switch
2370 The use of @option{-gnatN} activates  inlining optimization
2371 that is performed by the front end of the compiler. This inlining does
2372 not require that the code generation be optimized. Like @option{-gnatn},
2373 the use of this switch generates additional dependencies.
2374
2375 When using a gcc-based back end (in practice this means using any version
2376 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2377 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2378 Historically front end inlining was more extensive than the gcc back end
2379 inlining, but that is no longer the case.
2380
2381 @item
2382 If an object file @file{O} depends on the proper body of a subunit through
2383 inlining or instantiation, it depends on the parent unit of the subunit.
2384 This means that any modification of the parent unit or one of its subunits
2385 affects the compilation of @file{O}.
2386
2387 @item
2388 The object file for a parent unit depends on all its subunit body files.
2389
2390 @item
2391 The previous two rules meant that for purposes of computing dependencies and
2392 recompilation, a body and all its subunits are treated as an indivisible whole.
2393
2394 @noindent
2395 These rules are applied transitively: if unit @code{A} @code{with}'s
2396 unit @code{B}, whose elaboration calls an inlined procedure in package
2397 @code{C}, the object file for unit @code{A} will depend on the body of
2398 @code{C}, in file @file{c.adb}.
2399
2400 The set of dependent files described by these rules includes all the
2401 files on which the unit is semantically dependent, as dictated by the
2402 Ada language standard. However, it is a superset of what the
2403 standard describes, because it includes generic, inline, and subunit
2404 dependencies.
2405
2406 An object file must be recreated by recompiling the corresponding source
2407 file if any of the source files on which it depends are modified. For
2408 example, if the @code{make} utility is used to control compilation,
2409 the rule for an Ada object file must mention all the source files on
2410 which the object file depends, according to the above definition.
2411 The determination of the necessary
2412 recompilations is done automatically when one uses @command{gnatmake}.
2413 @end itemize
2414
2415 @node The Ada Library Information Files
2416 @section The Ada Library Information Files
2417 @cindex Ada Library Information files
2418 @cindex @file{ALI} files
2419
2420 @noindent
2421 Each compilation actually generates two output files. The first of these
2422 is the normal object file that has a @file{.o} extension. The second is a
2423 text file containing full dependency information. It has the same
2424 name as the source file, but an @file{.ali} extension.
2425 This file is known as the Ada Library Information (@file{ALI}) file.
2426 The following information is contained in the @file{ALI} file.
2427
2428 @itemize @bullet
2429 @item
2430 Version information (indicates which version of GNAT was used to compile
2431 the unit(s) in question)
2432
2433 @item
2434 Main program information (including priority and time slice settings,
2435 as well as the wide character encoding used during compilation).
2436
2437 @item
2438 List of arguments used in the @command{gcc} command for the compilation
2439
2440 @item
2441 Attributes of the unit, including configuration pragmas used, an indication
2442 of whether the compilation was successful, exception model used etc.
2443
2444 @item
2445 A list of relevant restrictions applying to the unit (used for consistency)
2446 checking.
2447
2448 @item
2449 Categorization information (e.g.@: use of pragma @code{Pure}).
2450
2451 @item
2452 Information on all @code{with}'ed units, including presence of
2453 @code{Elaborate} or @code{Elaborate_All} pragmas.
2454
2455 @item
2456 Information from any @code{Linker_Options} pragmas used in the unit
2457
2458 @item
2459 Information on the use of @code{Body_Version} or @code{Version}
2460 attributes in the unit.
2461
2462 @item
2463 Dependency information. This is a list of files, together with
2464 time stamp and checksum information. These are files on which
2465 the unit depends in the sense that recompilation is required
2466 if any of these units are modified.
2467
2468 @item
2469 Cross-reference data. Contains information on all entities referenced
2470 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2471 provide cross-reference information.
2472
2473 @end itemize
2474
2475 @noindent
2476 For a full detailed description of the format of the @file{ALI} file,
2477 see the source of the body of unit @code{Lib.Writ}, contained in file
2478 @file{lib-writ.adb} in the GNAT compiler sources.
2479
2480 @node Binding an Ada Program
2481 @section Binding an Ada Program
2482
2483 @noindent
2484 When using languages such as C and C++, once the source files have been
2485 compiled the only remaining step in building an executable program
2486 is linking the object modules together. This means that it is possible to
2487 link an inconsistent version of a program, in which two units have
2488 included different versions of the same header.
2489
2490 The rules of Ada do not permit such an inconsistent program to be built.
2491 For example, if two clients have different versions of the same package,
2492 it is illegal to build a program containing these two clients.
2493 These rules are enforced by the GNAT binder, which also determines an
2494 elaboration order consistent with the Ada rules.
2495
2496 The GNAT binder is run after all the object files for a program have
2497 been created. It is given the name of the main program unit, and from
2498 this it determines the set of units required by the program, by reading the
2499 corresponding ALI files. It generates error messages if the program is
2500 inconsistent or if no valid order of elaboration exists.
2501
2502 If no errors are detected, the binder produces a main program, in Ada by
2503 default, that contains calls to the elaboration procedures of those
2504 compilation unit that require them, followed by
2505 a call to the main program. This Ada program is compiled to generate the
2506 object file for the main program. The name of
2507 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2508 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2509 main program unit.
2510
2511 Finally, the linker is used to build the resulting executable program,
2512 using the object from the main program from the bind step as well as the
2513 object files for the Ada units of the program.
2514
2515 @node Mixed Language Programming
2516 @section Mixed Language Programming
2517 @cindex Mixed Language Programming
2518
2519 @noindent
2520 This section describes how to develop a mixed-language program,
2521 specifically one that comprises units in both Ada and C.
2522
2523 @menu
2524 * Interfacing to C::
2525 * Calling Conventions::
2526 @end menu
2527
2528 @node Interfacing to C
2529 @subsection Interfacing to C
2530 @noindent
2531 Interfacing Ada with a foreign language such as C involves using
2532 compiler directives to import and/or export entity definitions in each
2533 language---using @code{extern} statements in C, for instance, and the
2534 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2535 A full treatment of these topics is provided in Appendix B, section 1
2536 of the Ada Reference Manual.
2537
2538 There are two ways to build a program using GNAT that contains some Ada
2539 sources and some foreign language sources, depending on whether or not
2540 the main subprogram is written in Ada.  Here is a source example with
2541 the main subprogram in Ada:
2542
2543 @smallexample
2544 /* file1.c */
2545 #include <stdio.h>
2546
2547 void print_num (int num)
2548 @{
2549   printf ("num is %d.\n", num);
2550   return;
2551 @}
2552
2553 /* file2.c */
2554
2555 /* num_from_Ada is declared in my_main.adb */
2556 extern int num_from_Ada;
2557
2558 int get_num (void)
2559 @{
2560   return num_from_Ada;
2561 @}
2562 @end smallexample
2563
2564 @smallexample @c ada
2565 --  my_main.adb
2566 procedure My_Main is
2567
2568    --  Declare then export an Integer entity called num_from_Ada
2569    My_Num : Integer := 10;
2570    pragma Export (C, My_Num, "num_from_Ada");
2571
2572    --  Declare an Ada function spec for Get_Num, then use
2573    --  C function get_num for the implementation.
2574    function Get_Num return Integer;
2575    pragma Import (C, Get_Num, "get_num");
2576
2577    --  Declare an Ada procedure spec for Print_Num, then use
2578    --  C function print_num for the implementation.
2579    procedure Print_Num (Num : Integer);
2580    pragma Import (C, Print_Num, "print_num");
2581
2582 begin
2583    Print_Num (Get_Num);
2584 end My_Main;
2585 @end smallexample
2586
2587 @enumerate
2588 @item
2589 To build this example, first compile the foreign language files to
2590 generate object files:
2591 @smallexample
2592 ^gcc -c file1.c^gcc -c FILE1.C^
2593 ^gcc -c file2.c^gcc -c FILE2.C^
2594 @end smallexample
2595
2596 @item
2597 Then, compile the Ada units to produce a set of object files and ALI
2598 files:
2599 @smallexample
2600 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2601 @end smallexample
2602
2603 @item
2604 Run the Ada binder on the Ada main program:
2605 @smallexample
2606 gnatbind my_main.ali
2607 @end smallexample
2608
2609 @item
2610 Link the Ada main program, the Ada objects and the other language
2611 objects:
2612 @smallexample
2613 gnatlink my_main.ali file1.o file2.o
2614 @end smallexample
2615 @end enumerate
2616
2617 The last three steps can be grouped in a single command:
2618 @smallexample
2619 gnatmake my_main.adb -largs file1.o file2.o
2620 @end smallexample
2621
2622 @cindex Binder output file
2623 @noindent
2624 If the main program is in a language other than Ada, then you may have
2625 more than one entry point into the Ada subsystem. You must use a special
2626 binder option to generate callable routines that initialize and
2627 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2628 Calls to the initialization and finalization routines must be inserted
2629 in the main program, or some other appropriate point in the code. The
2630 call to initialize the Ada units must occur before the first Ada
2631 subprogram is called, and the call to finalize the Ada units must occur
2632 after the last Ada subprogram returns. The binder will place the
2633 initialization and finalization subprograms into the
2634 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2635 sources.  To illustrate, we have the following example:
2636
2637 @smallexample
2638 /* main.c */
2639 extern void adainit (void);
2640 extern void adafinal (void);
2641 extern int add (int, int);
2642 extern int sub (int, int);
2643
2644 int main (int argc, char *argv[])
2645 @{
2646   int a = 21, b = 7;
2647
2648   adainit();
2649
2650   /* Should print "21 + 7 = 28" */
2651   printf ("%d + %d = %d\n", a, b, add (a, b));
2652   /* Should print "21 - 7 = 14" */
2653   printf ("%d - %d = %d\n", a, b, sub (a, b));
2654
2655   adafinal();
2656 @}
2657 @end smallexample
2658
2659 @smallexample @c ada
2660 --  unit1.ads
2661 package Unit1 is
2662    function Add (A, B : Integer) return Integer;
2663    pragma Export (C, Add, "add");
2664 end Unit1;
2665
2666 --  unit1.adb
2667 package body Unit1 is
2668    function Add (A, B : Integer) return Integer is
2669    begin
2670       return A + B;
2671    end Add;
2672 end Unit1;
2673
2674 --  unit2.ads
2675 package Unit2 is
2676    function Sub (A, B : Integer) return Integer;
2677    pragma Export (C, Sub, "sub");
2678 end Unit2;
2679
2680 --  unit2.adb
2681 package body Unit2 is
2682    function Sub (A, B : Integer) return Integer is
2683    begin
2684       return A - B;
2685    end Sub;
2686 end Unit2;
2687 @end smallexample
2688
2689 @enumerate
2690 @item
2691 The build procedure for this application is similar to the last
2692 example's.  First, compile the foreign language files to generate object
2693 files:
2694 @smallexample
2695 ^gcc -c main.c^gcc -c main.c^
2696 @end smallexample
2697
2698 @item
2699 Next, compile the Ada units to produce a set of object files and ALI
2700 files:
2701 @smallexample
2702 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2703 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2704 @end smallexample
2705
2706 @item
2707 Run the Ada binder on every generated ALI file.  Make sure to use the
2708 @option{-n} option to specify a foreign main program:
2709 @smallexample
2710 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2711 @end smallexample
2712
2713 @item
2714 Link the Ada main program, the Ada objects and the foreign language
2715 objects. You need only list the last ALI file here:
2716 @smallexample
2717 gnatlink unit2.ali main.o -o exec_file
2718 @end smallexample
2719
2720 This procedure yields a binary executable called @file{exec_file}.
2721 @end enumerate
2722
2723 @noindent
2724 Depending on the circumstances (for example when your non-Ada main object
2725 does not provide symbol @code{main}), you may also need to instruct the
2726 GNAT linker not to include the standard startup objects by passing the
2727 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2728
2729 @node Calling Conventions
2730 @subsection Calling Conventions
2731 @cindex Foreign Languages
2732 @cindex Calling Conventions
2733 GNAT follows standard calling sequence conventions and will thus interface
2734 to any other language that also follows these conventions. The following
2735 Convention identifiers are recognized by GNAT:
2736
2737 @table @code
2738 @cindex Interfacing to Ada
2739 @cindex Other Ada compilers
2740 @cindex Convention Ada
2741 @item Ada
2742 This indicates that the standard Ada calling sequence will be
2743 used and all Ada data items may be passed without any limitations in the
2744 case where GNAT is used to generate both the caller and callee. It is also
2745 possible to mix GNAT generated code and code generated by another Ada
2746 compiler. In this case, the data types should be restricted to simple
2747 cases, including primitive types. Whether complex data types can be passed
2748 depends on the situation. Probably it is safe to pass simple arrays, such
2749 as arrays of integers or floats. Records may or may not work, depending
2750 on whether both compilers lay them out identically. Complex structures
2751 involving variant records, access parameters, tasks, or protected types,
2752 are unlikely to be able to be passed.
2753
2754 Note that in the case of GNAT running
2755 on a platform that supports HP Ada 83, a higher degree of compatibility
2756 can be guaranteed, and in particular records are layed out in an identical
2757 manner in the two compilers. Note also that if output from two different
2758 compilers is mixed, the program is responsible for dealing with elaboration
2759 issues. Probably the safest approach is to write the main program in the
2760 version of Ada other than GNAT, so that it takes care of its own elaboration
2761 requirements, and then call the GNAT-generated adainit procedure to ensure
2762 elaboration of the GNAT components. Consult the documentation of the other
2763 Ada compiler for further details on elaboration.
2764
2765 However, it is not possible to mix the tasking run time of GNAT and
2766 HP Ada 83, All the tasking operations must either be entirely within
2767 GNAT compiled sections of the program, or entirely within HP Ada 83
2768 compiled sections of the program.
2769
2770 @cindex Interfacing to Assembly
2771 @cindex Convention Assembler
2772 @item Assembler
2773 Specifies assembler as the convention. In practice this has the
2774 same effect as convention Ada (but is not equivalent in the sense of being
2775 considered the same convention).
2776
2777 @cindex Convention Asm
2778 @findex Asm
2779 @item Asm
2780 Equivalent to Assembler.
2781
2782 @cindex Interfacing to COBOL
2783 @cindex Convention COBOL
2784 @findex COBOL
2785 @item COBOL
2786 Data will be passed according to the conventions described
2787 in section B.4 of the Ada Reference Manual.
2788
2789 @findex C
2790 @cindex Interfacing to C
2791 @cindex Convention C
2792 @item C
2793 Data will be passed according to the conventions described
2794 in section B.3 of the Ada Reference Manual.
2795
2796 A note on interfacing to a C ``varargs'' function:
2797 @findex C varargs function
2798 @cindex Interfacing to C varargs function
2799 @cindex varargs function interfaces
2800
2801 @itemize @bullet
2802 @item
2803 In C, @code{varargs} allows a function to take a variable number of
2804 arguments. There is no direct equivalent in this to Ada. One
2805 approach that can be used is to create a C wrapper for each
2806 different profile and then interface to this C wrapper. For
2807 example, to print an @code{int} value using @code{printf},
2808 create a C function @code{printfi} that takes two arguments, a
2809 pointer to a string and an int, and calls @code{printf}.
2810 Then in the Ada program, use pragma @code{Import} to
2811 interface to @code{printfi}.
2812
2813 @item
2814 It may work on some platforms to directly interface to
2815 a @code{varargs} function by providing a specific Ada profile
2816 for a particular call. However, this does not work on
2817 all platforms, since there is no guarantee that the
2818 calling sequence for a two argument normal C function
2819 is the same as for calling a @code{varargs} C function with
2820 the same two arguments.
2821 @end itemize
2822
2823 @cindex Convention Default
2824 @findex Default
2825 @item Default
2826 Equivalent to C.
2827
2828 @cindex Convention External
2829 @findex External
2830 @item External
2831 Equivalent to C.
2832
2833 @ifclear vms
2834 @findex C++
2835 @cindex Interfacing to C++
2836 @cindex Convention C++
2837 @item C_Plus_Plus (or CPP)
2838 This stands for C++. For most purposes this is identical to C.
2839 See the separate description of the specialized GNAT pragmas relating to
2840 C++ interfacing for further details.
2841 @end ifclear
2842
2843 @findex Fortran
2844 @cindex Interfacing to Fortran
2845 @cindex Convention Fortran
2846 @item Fortran
2847 Data will be passed according to the conventions described
2848 in section B.5 of the Ada Reference Manual.
2849
2850 @item Intrinsic
2851 This applies to an intrinsic operation, as defined in the Ada
2852 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2853 this means that the body of the subprogram is provided by the compiler itself,
2854 usually by means of an efficient code sequence, and that the user does not
2855 supply an explicit body for it. In an application program, the pragma may
2856 be applied to the following sets of names:
2857
2858 @itemize @bullet
2859 @item
2860 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2861 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2862 two formal parameters. The
2863 first one must be a signed integer type or a modular type with a binary
2864 modulus, and the second parameter must be of type Natural.
2865 The return type must be the same as the type of the first argument. The size
2866 of this type can only be 8, 16, 32, or 64.
2867
2868 @item
2869 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2870 The corresponding operator declaration must have parameters and result type
2871 that have the same root numeric type (for example, all three are long_float
2872 types). This simplifies the definition of operations that use type checking
2873 to perform dimensional checks:
2874
2875 @smallexample @c ada
2876 type Distance is new Long_Float;
2877 type Time     is new Long_Float;
2878 type Velocity is new Long_Float;
2879 function "/" (D : Distance; T : Time)
2880   return Velocity;
2881 pragma Import (Intrinsic, "/");
2882 @end smallexample
2883
2884 @noindent
2885 This common idiom is often programmed with a generic definition and an
2886 explicit body. The pragma makes it simpler to introduce such declarations.
2887 It incurs no overhead in compilation time or code size, because it is
2888 implemented as a single machine instruction.
2889
2890 @item
2891 General subprogram entities, to bind an Ada subprogram declaration to
2892 a compiler builtin by name with back-ends where such interfaces are
2893 available. A typical example is the set of ``__builtin'' functions
2894 exposed by the GCC back-end, as in the following example:
2895
2896 @smallexample @c ada
2897    function builtin_sqrt (F : Float) return Float;
2898    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2899 @end smallexample
2900
2901 Most of the GCC builtins are accessible this way, and as for other
2902 import conventions (e.g. C), it is the user's responsibility to ensure
2903 that the Ada subprogram profile matches the underlying builtin
2904 expectations.
2905 @end itemize
2906
2907 @noindent
2908
2909 @ifset unw
2910 @findex Stdcall
2911 @cindex Convention Stdcall
2912 @item Stdcall
2913 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2914 and specifies that the @code{Stdcall} calling sequence will be used,
2915 as defined by the NT API. Nevertheless, to ease building
2916 cross-platform bindings this convention will be handled as a @code{C} calling
2917 convention on non-Windows platforms.
2918
2919 @findex DLL
2920 @cindex Convention DLL
2921 @item DLL
2922 This is equivalent to @code{Stdcall}.
2923
2924 @findex Win32
2925 @cindex Convention Win32
2926 @item Win32
2927 This is equivalent to @code{Stdcall}.
2928 @end ifset
2929
2930 @findex Stubbed
2931 @cindex Convention Stubbed
2932 @item Stubbed
2933 This is a special convention that indicates that the compiler
2934 should provide a stub body that raises @code{Program_Error}.
2935 @end table
2936
2937 @noindent
2938 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2939 that can be used to parametrize conventions and allow additional synonyms
2940 to be specified. For example if you have legacy code in which the convention
2941 identifier Fortran77 was used for Fortran, you can use the configuration
2942 pragma:
2943
2944 @smallexample @c ada
2945 pragma Convention_Identifier (Fortran77, Fortran);
2946 @end smallexample
2947
2948 @noindent
2949 And from now on the identifier Fortran77 may be used as a convention
2950 identifier (for example in an @code{Import} pragma) with the same
2951 meaning as Fortran.
2952
2953 @ifclear vms
2954 @node Building Mixed Ada & C++ Programs
2955 @section Building Mixed Ada and C++ Programs
2956
2957 @noindent
2958 A programmer inexperienced with mixed-language development may find that
2959 building an application containing both Ada and C++ code can be a
2960 challenge.  This section gives a few
2961 hints that should make this task easier. The first section addresses
2962 the differences between interfacing with C and interfacing with C++.
2963 The second section
2964 looks into the delicate problem of linking the complete application from
2965 its Ada and C++ parts. The last section gives some hints on how the GNAT
2966 run-time library can be adapted in order to allow inter-language dispatching
2967 with a new C++ compiler.
2968
2969 @menu
2970 * Interfacing to C++::
2971 * Linking a Mixed C++ & Ada Program::
2972 * A Simple Example::
2973 * Interfacing with C++ constructors::
2974 * Interfacing with C++ at the Class Level::
2975 @end menu
2976
2977 @node Interfacing to C++
2978 @subsection Interfacing to C++
2979
2980 @noindent
2981 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2982 generating code that is compatible with the G++ Application Binary
2983 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2984
2985 @noindent
2986 Interfacing can be done at 3 levels: simple data, subprograms, and
2987 classes. In the first two cases, GNAT offers a specific @code{Convention
2988 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2989 Usually, C++ mangles the names of subprograms. To generate proper mangled
2990 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2991 This problem can also be addressed manually in two ways:
2992
2993 @itemize @bullet
2994 @item
2995 by modifying the C++ code in order to force a C convention using
2996 the @code{extern "C"} syntax.
2997
2998 @item
2999 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3000 Link_Name argument of the pragma import.
3001 @end itemize
3002
3003 @noindent
3004 Interfacing at the class level can be achieved by using the GNAT specific
3005 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3006 gnat_rm, GNAT Reference Manual}, for additional information.
3007
3008 @node Linking a Mixed C++ & Ada Program
3009 @subsection Linking a Mixed C++ & Ada Program
3010
3011 @noindent
3012 Usually the linker of the C++ development system must be used to link
3013 mixed applications because most C++ systems will resolve elaboration
3014 issues (such as calling constructors on global class instances)
3015 transparently during the link phase. GNAT has been adapted to ease the
3016 use of a foreign linker for the last phase. Three cases can be
3017 considered:
3018 @enumerate
3019
3020 @item
3021 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3022 The C++ linker can simply be called by using the C++ specific driver
3023 called @code{g++}.
3024
3025 Note that if the C++ code uses inline functions, you will need to
3026 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3027 order to provide an existing function implementation that the Ada code can
3028 link with.
3029
3030 @smallexample
3031 $ g++ -c -fkeep-inline-functions file1.C
3032 $ g++ -c -fkeep-inline-functions file2.C
3033 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3034 @end smallexample
3035
3036 @item
3037 Using GNAT and G++ from two different GCC installations: If both
3038 compilers are on the @env{PATH}, the previous method may be used. It is
3039 important to note that environment variables such as
3040 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3041 @env{GCC_ROOT} will affect both compilers
3042 at the same time and may make one of the two compilers operate
3043 improperly if set during invocation of the wrong compiler.  It is also
3044 very important that the linker uses the proper @file{libgcc.a} GCC
3045 library -- that is, the one from the C++ compiler installation. The
3046 implicit link command as suggested in the @command{gnatmake} command
3047 from the former example can be replaced by an explicit link command with
3048 the full-verbosity option in order to verify which library is used:
3049 @smallexample
3050 $ gnatbind ada_unit
3051 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3052 @end smallexample
3053 If there is a problem due to interfering environment variables, it can
3054 be worked around by using an intermediate script. The following example
3055 shows the proper script to use when GNAT has not been installed at its
3056 default location and g++ has been installed at its default location:
3057
3058 @smallexample
3059 $ cat ./my_script
3060 #!/bin/sh
3061 unset BINUTILS_ROOT
3062 unset GCC_ROOT
3063 c++ $*
3064 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3065 @end smallexample
3066
3067 @item
3068 Using a non-GNU C++ compiler: The commands previously described can be
3069 used to insure that the C++ linker is used. Nonetheless, you need to add
3070 a few more parameters to the link command line, depending on the exception
3071 mechanism used.
3072
3073 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3074 to the libgcc libraries are required:
3075
3076 @smallexample
3077 $ cat ./my_script
3078 #!/bin/sh
3079 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3080 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3081 @end smallexample
3082
3083 Where CC is the name of the non-GNU C++ compiler.
3084
3085 If the @code{zero cost} exception mechanism is used, and the platform
3086 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3087 paths to more objects are required:
3088
3089 @smallexample
3090 $ cat ./my_script
3091 #!/bin/sh
3092 CC `gcc -print-file-name=crtbegin.o` $* \
3093 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3094 `gcc -print-file-name=crtend.o`
3095 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3096 @end smallexample
3097
3098 If the @code{zero cost} exception mechanism is used, and the platform
3099 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3100 Tru64 or AIX), the simple approach described above will not work and
3101 a pre-linking phase using GNAT will be necessary.
3102
3103 @end enumerate
3104
3105 Another alternative is to use the @command{gprbuild} multi-language builder
3106 which has a large knowledge base and knows how to link Ada and C++ code
3107 together automatically in most cases.
3108
3109 @node A Simple Example
3110 @subsection  A Simple Example
3111 @noindent
3112 The following example, provided as part of the GNAT examples, shows how
3113 to achieve procedural interfacing between Ada and C++ in both
3114 directions. The C++ class A has two methods. The first method is exported
3115 to Ada by the means of an extern C wrapper function. The second method
3116 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3117 a limited record with a layout comparable to the C++ class. The Ada
3118 subprogram, in turn, calls the C++ method. So, starting from the C++
3119 main program, the process passes back and forth between the two
3120 languages.
3121
3122 @noindent
3123 Here are the compilation commands:
3124 @smallexample
3125 $ gnatmake -c simple_cpp_interface
3126 $ g++ -c cpp_main.C
3127 $ g++ -c ex7.C
3128 $ gnatbind -n simple_cpp_interface
3129 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3130       -lstdc++ ex7.o cpp_main.o
3131 @end smallexample
3132
3133 @noindent
3134 Here are the corresponding sources:
3135 @smallexample
3136
3137 //cpp_main.C
3138
3139 #include "ex7.h"
3140
3141 extern "C" @{
3142   void adainit (void);
3143   void adafinal (void);
3144   void method1 (A *t);
3145 @}
3146
3147 void method1 (A *t)
3148 @{
3149   t->method1 ();
3150 @}
3151
3152 int main ()
3153 @{
3154   A obj;
3155   adainit ();
3156   obj.method2 (3030);
3157   adafinal ();
3158 @}
3159
3160 //ex7.h
3161
3162 class Origin @{
3163  public:
3164   int o_value;
3165 @};
3166 class A : public Origin @{
3167  public:
3168   void method1 (void);
3169   void method2 (int v);
3170   A();
3171   int   a_value;
3172 @};
3173
3174 //ex7.C
3175
3176 #include "ex7.h"
3177 #include <stdio.h>
3178
3179 extern "C" @{ void ada_method2 (A *t, int v);@}
3180
3181 void A::method1 (void)
3182 @{
3183   a_value = 2020;
3184   printf ("in A::method1, a_value = %d \n",a_value);
3185
3186 @}
3187
3188 void A::method2 (int v)
3189 @{
3190    ada_method2 (this, v);
3191    printf ("in A::method2, a_value = %d \n",a_value);
3192
3193 @}
3194
3195 A::A(void)
3196 @{
3197    a_value = 1010;
3198   printf ("in A::A, a_value = %d \n",a_value);
3199 @}
3200 @end smallexample
3201
3202 @smallexample @c ada
3203 -- Ada sources
3204 package body Simple_Cpp_Interface is
3205
3206    procedure Ada_Method2 (This : in out A; V : Integer) is
3207    begin
3208       Method1 (This);
3209       This.A_Value := V;
3210    end Ada_Method2;
3211
3212 end Simple_Cpp_Interface;
3213
3214 with System;
3215 package Simple_Cpp_Interface is
3216    type A is limited
3217       record
3218          Vptr    : System.Address;
3219          O_Value : Integer;
3220          A_Value : Integer;
3221       end record;
3222    pragma Convention (C, A);
3223
3224    procedure Method1 (This : in out A);
3225    pragma Import (C, Method1);
3226
3227    procedure Ada_Method2 (This : in out A; V : Integer);
3228    pragma Export (C, Ada_Method2);
3229
3230 end Simple_Cpp_Interface;
3231 @end smallexample
3232
3233 @node Interfacing with C++ constructors
3234 @subsection Interfacing with C++ constructors
3235 @noindent
3236
3237 In order to interface with C++ constructors GNAT provides the
3238 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3239 gnat_rm, GNAT Reference Manual}, for additional information).
3240 In this section we present some common uses of C++ constructors
3241 in mixed-languages programs in GNAT.
3242
3243 Let us assume that we need to interface with the following
3244 C++ class:
3245
3246 @smallexample
3247 @b{class} Root @{
3248 @b{public}:
3249   int  a_value;
3250   int  b_value;
3251   @b{virtual} int Get_Value ();
3252   Root();              // Default constructor
3253   Root(int v);         // 1st non-default constructor
3254   Root(int v, int w);  // 2nd non-default constructor
3255 @};
3256 @end smallexample
3257
3258 For this purpose we can write the following package spec (further
3259 information on how to build this spec is available in
3260 @ref{Interfacing with C++ at the Class Level} and
3261 @ref{Generating Ada Bindings for C and C++ headers}).
3262
3263 @smallexample @c ada
3264 with Interfaces.C; use Interfaces.C;
3265 package Pkg_Root is
3266   type Root is tagged limited record
3267      A_Value : int;
3268      B_Value : int;
3269   end record;
3270   pragma Import (CPP, Root);
3271
3272   function Get_Value (Obj : Root) return int;
3273   pragma Import (CPP, Get_Value);
3274
3275   function Constructor return Root;
3276   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3277
3278   function Constructor (v : Integer) return Root;
3279   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3280
3281   function Constructor (v, w : Integer) return Root;
3282   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3283 end Pkg_Root;
3284 @end smallexample
3285
3286 On the Ada side the constructor is represented by a function (whose
3287 name is arbitrary) that returns the classwide type corresponding to
3288 the imported C++ class. Although the constructor is described as a
3289 function, it is typically a procedure with an extra implicit argument
3290 (the object being initialized) at the implementation level. GNAT
3291 issues the appropriate call, whatever it is, to get the object
3292 properly initialized.
3293
3294 Constructors can only appear in the following contexts:
3295
3296 @itemize @bullet
3297 @item
3298 On the right side of an initialization of an object of type @var{T}.
3299 @item
3300 On the right side of an initialization of a record component of type @var{T}.
3301 @item
3302 In an Ada 2005 limited aggregate.
3303 @item
3304 In an Ada 2005 nested limited aggregate.
3305 @item
3306 In an Ada 2005 limited aggregate that initializes an object built in
3307 place by an extended return statement.
3308 @end itemize
3309
3310 @noindent
3311 In a declaration of an object whose type is a class imported from C++,
3312 either the default C++ constructor is implicitly called by GNAT, or
3313 else the required C++ constructor must be explicitly called in the
3314 expression that initializes the object. For example:
3315
3316 @smallexample @c ada
3317   Obj1 : Root;
3318   Obj2 : Root := Constructor;
3319   Obj3 : Root := Constructor (v => 10);
3320   Obj4 : Root := Constructor (30, 40);
3321 @end smallexample
3322
3323 The first two declarations are equivalent: in both cases the default C++
3324 constructor is invoked (in the former case the call to the constructor is
3325 implicit, and in the latter case the call is explicit in the object
3326 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3327 that takes an integer argument, and @code{Obj4} is initialized by the
3328 non-default C++ constructor that takes two integers.
3329
3330 Let us derive the imported C++ class in the Ada side. For example:
3331
3332 @smallexample @c ada
3333   type DT is new Root with record
3334      C_Value : Natural := 2009;
3335   end record;
3336 @end smallexample
3337
3338 In this case the components DT inherited from the C++ side must be
3339 initialized by a C++ constructor, and the additional Ada components
3340 of type DT are initialized by GNAT. The initialization of such an
3341 object is done either by default, or by means of a function returning
3342 an aggregate of type DT, or by means of an extension aggregate.
3343
3344 @smallexample @c ada
3345   Obj5 : DT;
3346   Obj6 : DT := Function_Returning_DT (50);
3347   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3348 @end smallexample
3349
3350 The declaration of @code{Obj5} invokes the default constructors: the
3351 C++ default constructor of the parent type takes care of the initialization
3352 of the components inherited from Root, and GNAT takes care of the default
3353 initialization of the additional Ada components of type DT (that is,
3354 @code{C_Value} is initialized to value 2009). The order of invocation of
3355 the constructors is consistent with the order of elaboration required by
3356 Ada and C++. That is, the constructor of the parent type is always called
3357 before the constructor of the derived type.
3358
3359 Let us now consider a record that has components whose type is imported
3360 from C++. For example:
3361
3362 @smallexample @c ada
3363   type Rec1 is limited record
3364      Data1 : Root := Constructor (10);
3365      Value : Natural := 1000;
3366   end record;
3367
3368   type Rec2 (D : Integer := 20) is limited record
3369      Rec   : Rec1;
3370      Data2 : Root := Constructor (D, 30);
3371   end record;
3372 @end smallexample
3373
3374 The initialization of an object of type @code{Rec2} will call the
3375 non-default C++ constructors specified for the imported components.
3376 For example:
3377
3378 @smallexample @c ada
3379   Obj8 : Rec2 (40);
3380 @end smallexample
3381
3382 Using Ada 2005 we can use limited aggregates to initialize an object
3383 invoking C++ constructors that differ from those specified in the type
3384 declarations. For example:
3385
3386 @smallexample @c ada
3387   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3388                           others => <>),
3389                   others => <>);
3390 @end smallexample
3391
3392 The above declaration uses an Ada 2005 limited aggregate to
3393 initialize @code{Obj9}, and the C++ constructor that has two integer
3394 arguments is invoked to initialize the @code{Data1} component instead
3395 of the constructor specified in the declaration of type @code{Rec1}. In
3396 Ada 2005 the box in the aggregate indicates that unspecified components
3397 are initialized using the expression (if any) available in the component
3398 declaration. That is, in this case discriminant @code{D} is initialized
3399 to value @code{20}, @code{Value} is initialized to value 1000, and the
3400 non-default C++ constructor that handles two integers takes care of
3401 initializing component @code{Data2} with values @code{20,30}.
3402
3403 In Ada 2005 we can use the extended return statement to build the Ada
3404 equivalent to C++ non-default constructors. For example:
3405
3406 @smallexample @c ada
3407   function Constructor (V : Integer) return Rec2 is
3408   begin
3409      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3410                                    others => <>),
3411                            others => <>) do
3412         --  Further actions required for construction of
3413         --  objects of type Rec2
3414         ...
3415      end record;
3416   end Constructor;
3417 @end smallexample
3418
3419 In this example the extended return statement construct is used to
3420 build in place the returned object whose components are initialized
3421 by means of a limited aggregate. Any further action associated with
3422 the constructor can be placed inside the construct.
3423
3424 @node Interfacing with C++ at the Class Level
3425 @subsection Interfacing with C++ at the Class Level
3426 @noindent
3427 In this section we demonstrate the GNAT features for interfacing with
3428 C++ by means of an example making use of Ada 2005 abstract interface
3429 types. This example consists of a classification of animals; classes
3430 have been used to model our main classification of animals, and
3431 interfaces provide support for the management of secondary
3432 classifications. We first demonstrate a case in which the types and
3433 constructors are defined on the C++ side and imported from the Ada
3434 side, and latter the reverse case.
3435
3436 The root of our derivation will be the @code{Animal} class, with a
3437 single private attribute (the @code{Age} of the animal) and two public
3438 primitives to set and get the value of this attribute.
3439
3440 @smallexample
3441 @b{class} Animal @{
3442  @b{public}:
3443    @b{virtual} void Set_Age (int New_Age);
3444    @b{virtual} int Age ();
3445  @b{private}:
3446    int Age_Count;
3447 @};
3448 @end smallexample
3449
3450 Abstract interface types are defined in C++ by means of classes with pure
3451 virtual functions and no data members. In our example we will use two
3452 interfaces that provide support for the common management of @code{Carnivore}
3453 and @code{Domestic} animals:
3454
3455 @smallexample
3456 @b{class} Carnivore @{
3457 @b{public}:
3458    @b{virtual} int Number_Of_Teeth () = 0;
3459 @};
3460
3461 @b{class} Domestic @{
3462 @b{public}:
3463    @b{virtual void} Set_Owner (char* Name) = 0;
3464 @};
3465 @end smallexample
3466
3467 Using these declarations, we can now say that a @code{Dog} is an animal that is
3468 both Carnivore and Domestic, that is:
3469
3470 @smallexample
3471 @b{class} Dog : Animal, Carnivore, Domestic @{
3472  @b{public}:
3473    @b{virtual} int  Number_Of_Teeth ();
3474    @b{virtual} void Set_Owner (char* Name);
3475
3476    Dog(); // Constructor
3477  @b{private}:
3478    int  Tooth_Count;
3479    char *Owner;
3480 @};
3481 @end smallexample
3482
3483 In the following examples we will assume that the previous declarations are
3484 located in a file named @code{animals.h}. The following package demonstrates
3485 how to import these C++ declarations from the Ada side:
3486
3487 @smallexample @c ada
3488 with Interfaces.C.Strings; use Interfaces.C.Strings;
3489 package Animals is
3490   type Carnivore is interface;
3491   pragma Convention (C_Plus_Plus, Carnivore);
3492   function Number_Of_Teeth (X : Carnivore)
3493      return Natural is abstract;
3494
3495   type Domestic is interface;
3496   pragma Convention (C_Plus_Plus, Set_Owner);
3497   procedure Set_Owner
3498     (X    : in out Domestic;
3499      Name : Chars_Ptr) is abstract;
3500
3501   type Animal is tagged record
3502     Age : Natural := 0;
3503   end record;
3504   pragma Import (C_Plus_Plus, Animal);
3505
3506   procedure Set_Age (X : in out Animal; Age : Integer);
3507   pragma Import (C_Plus_Plus, Set_Age);
3508
3509   function Age (X : Animal) return Integer;
3510   pragma Import (C_Plus_Plus, Age);
3511
3512   type Dog is new Animal and Carnivore and Domestic with record
3513     Tooth_Count : Natural;
3514     Owner       : String (1 .. 30);
3515   end record;
3516   pragma Import (C_Plus_Plus, Dog);
3517
3518   function Number_Of_Teeth (A : Dog) return Integer;
3519   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3520
3521   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3522   pragma Import (C_Plus_Plus, Set_Owner);
3523
3524   function New_Dog return Dog;
3525   pragma CPP_Constructor (New_Dog);
3526   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3527 end Animals;
3528 @end smallexample
3529
3530 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3531 interfacing with these C++ classes is easy. The only requirement is that all
3532 the primitives and components must be declared exactly in the same order in
3533 the two languages.
3534
3535 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3536 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3537 the arguments to the called primitives will be the same as for C++. For the
3538 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3539 to indicate that they have been defined on the C++ side; this is required
3540 because the dispatch table associated with these tagged types will be built
3541 in the C++ side and therefore will not contain the predefined Ada primitives
3542 which Ada would otherwise expect.
3543
3544 As the reader can see there is no need to indicate the C++ mangled names
3545 associated with each subprogram because it is assumed that all the calls to
3546 these primitives will be dispatching calls. The only exception is the
3547 constructor, which must be registered with the compiler by means of
3548 @code{pragma CPP_Constructor} and needs to provide its associated C++
3549 mangled name because the Ada compiler generates direct calls to it.
3550
3551 With the above packages we can now declare objects of type Dog on the Ada side
3552 and dispatch calls to the corresponding subprograms on the C++ side. We can
3553 also extend the tagged type Dog with further fields and primitives, and
3554 override some of its C++ primitives on the Ada side. For example, here we have
3555 a type derivation defined on the Ada side that inherits all the dispatching
3556 primitives of the ancestor from the C++ side.
3557
3558 @smallexample
3559 @b{with} Animals; @b{use} Animals;
3560 @b{package} Vaccinated_Animals @b{is}
3561   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3562   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3563 @b{end} Vaccinated_Animals;
3564 @end smallexample
3565
3566 It is important to note that, because of the ABI compatibility, the programmer
3567 does not need to add any further information to indicate either the object
3568 layout or the dispatch table entry associated with each dispatching operation.
3569
3570 Now let us define all the types and constructors on the Ada side and export
3571 them to C++, using the same hierarchy of our previous example:
3572
3573 @smallexample @c ada
3574 with Interfaces.C.Strings;
3575 use Interfaces.C.Strings;
3576 package Animals is
3577   type Carnivore is interface;
3578   pragma Convention (C_Plus_Plus, Carnivore);
3579   function Number_Of_Teeth (X : Carnivore)
3580      return Natural is abstract;
3581
3582   type Domestic is interface;
3583   pragma Convention (C_Plus_Plus, Set_Owner);
3584   procedure Set_Owner
3585     (X    : in out Domestic;
3586      Name : Chars_Ptr) is abstract;
3587
3588   type Animal is tagged record
3589     Age : Natural := 0;
3590   end record;
3591   pragma Convention (C_Plus_Plus, Animal);
3592
3593   procedure Set_Age (X : in out Animal; Age : Integer);
3594   pragma Export (C_Plus_Plus, Set_Age);
3595
3596   function Age (X : Animal) return Integer;
3597   pragma Export (C_Plus_Plus, Age);
3598
3599   type Dog is new Animal and Carnivore and Domestic with record
3600     Tooth_Count : Natural;
3601     Owner       : String (1 .. 30);
3602   end record;
3603   pragma Convention (C_Plus_Plus, Dog);
3604
3605   function Number_Of_Teeth (A : Dog) return Integer;
3606   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3607
3608   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3609   pragma Export (C_Plus_Plus, Set_Owner);
3610
3611   function New_Dog return Dog'Class;
3612   pragma Export (C_Plus_Plus, New_Dog);
3613 end Animals;
3614 @end smallexample
3615
3616 Compared with our previous example the only difference is the use of
3617 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3618 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3619 nothing else to be done; as explained above, the only requirement is that all
3620 the primitives and components are declared in exactly the same order.
3621
3622 For completeness, let us see a brief C++ main program that uses the
3623 declarations available in @code{animals.h} (presented in our first example) to
3624 import and use the declarations from the Ada side, properly initializing and
3625 finalizing the Ada run-time system along the way:
3626
3627 @smallexample
3628 @b{#include} "animals.h"
3629 @b{#include} <iostream>
3630 @b{using namespace} std;
3631
3632 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3633 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3634 void Check_Animal (Animal *obj)       @{@dots{}@}
3635 void Check_Dog (Dog *obj)             @{@dots{}@}
3636
3637 @b{extern} "C" @{
3638   void adainit (void);
3639   void adafinal (void);
3640   Dog* new_dog ();
3641 @}
3642
3643 void test ()
3644 @{
3645   Dog *obj = new_dog();  // Ada constructor
3646   Check_Carnivore (obj); // Check secondary DT
3647   Check_Domestic (obj);  // Check secondary DT
3648   Check_Animal (obj);    // Check primary DT
3649   Check_Dog (obj);       // Check primary DT
3650 @}
3651
3652 int main ()
3653 @{
3654   adainit ();  test();  adafinal ();
3655   return 0;
3656 @}
3657 @end smallexample
3658
3659 @node Comparison between GNAT and C/C++ Compilation Models
3660 @section Comparison between GNAT and C/C++ Compilation Models
3661
3662 @noindent
3663 The GNAT model of compilation is close to the C and C++ models. You can
3664 think of Ada specs as corresponding to header files in C. As in C, you
3665 don't need to compile specs; they are compiled when they are used. The
3666 Ada @code{with} is similar in effect to the @code{#include} of a C
3667 header.
3668
3669 One notable difference is that, in Ada, you may compile specs separately
3670 to check them for semantic and syntactic accuracy. This is not always
3671 possible with C headers because they are fragments of programs that have
3672 less specific syntactic or semantic rules.
3673
3674 The other major difference is the requirement for running the binder,
3675 which performs two important functions. First, it checks for
3676 consistency. In C or C++, the only defense against assembling
3677 inconsistent programs lies outside the compiler, in a makefile, for
3678 example. The binder satisfies the Ada requirement that it be impossible
3679 to construct an inconsistent program when the compiler is used in normal
3680 mode.
3681
3682 @cindex Elaboration order control
3683 The other important function of the binder is to deal with elaboration
3684 issues. There are also elaboration issues in C++ that are handled
3685 automatically. This automatic handling has the advantage of being
3686 simpler to use, but the C++ programmer has no control over elaboration.
3687 Where @code{gnatbind} might complain there was no valid order of
3688 elaboration, a C++ compiler would simply construct a program that
3689 malfunctioned at run time.
3690 @end ifclear
3691
3692 @node Comparison between GNAT and Conventional Ada Library Models
3693 @section Comparison between GNAT and Conventional Ada Library Models
3694
3695 @noindent
3696 This section is intended for Ada programmers who have
3697 used an Ada compiler implementing the traditional Ada library
3698 model, as described in the Ada Reference Manual.
3699
3700 @cindex GNAT library
3701 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3702 source files themselves acts as the library. Compiling Ada programs does
3703 not generate any centralized information, but rather an object file and
3704 a ALI file, which are of interest only to the binder and linker.
3705 In a traditional system, the compiler reads information not only from
3706 the source file being compiled, but also from the centralized library.
3707 This means that the effect of a compilation depends on what has been
3708 previously compiled. In particular:
3709
3710 @itemize @bullet
3711 @item
3712 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3713 to the version of the unit most recently compiled into the library.
3714
3715 @item
3716 Inlining is effective only if the necessary body has already been
3717 compiled into the library.
3718
3719 @item
3720 Compiling a unit may obsolete other units in the library.
3721 @end itemize
3722
3723 @noindent
3724 In GNAT, compiling one unit never affects the compilation of any other
3725 units because the compiler reads only source files. Only changes to source
3726 files can affect the results of a compilation. In particular:
3727
3728 @itemize @bullet
3729 @item
3730 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3731 to the source version of the unit that is currently accessible to the
3732 compiler.
3733
3734 @item
3735 @cindex Inlining
3736 Inlining requires the appropriate source files for the package or
3737 subprogram bodies to be available to the compiler. Inlining is always
3738 effective, independent of the order in which units are complied.
3739
3740 @item
3741 Compiling a unit never affects any other compilations. The editing of
3742 sources may cause previous compilations to be out of date if they
3743 depended on the source file being modified.
3744 @end itemize
3745
3746 @noindent
3747 The most important result of these differences is that order of compilation
3748 is never significant in GNAT. There is no situation in which one is
3749 required to do one compilation before another. What shows up as order of
3750 compilation requirements in the traditional Ada library becomes, in
3751 GNAT, simple source dependencies; in other words, there is only a set
3752 of rules saying what source files must be present when a file is
3753 compiled.
3754
3755 @ifset vms
3756 @node Placement of temporary files
3757 @section Placement of temporary files
3758 @cindex Temporary files (user control over placement)
3759
3760 @noindent
3761 GNAT creates temporary files in the directory designated by the environment
3762 variable @env{TMPDIR}.
3763 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3764 for detailed information on how environment variables are resolved.
3765 For most users the easiest way to make use of this feature is to simply
3766 define @env{TMPDIR} as a job level logical name).
3767 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3768 for compiler temporary files, then you can include something like the
3769 following command in your @file{LOGIN.COM} file:
3770
3771 @smallexample
3772 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3773 @end smallexample
3774
3775 @noindent
3776 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3777 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3778 designated by @env{TEMP}.
3779 If none of these environment variables are defined then GNAT uses the
3780 directory designated by the logical name @code{SYS$SCRATCH:}
3781 (by default the user's home directory). If all else fails
3782 GNAT uses the current directory for temporary files.
3783 @end ifset
3784
3785 @c *************************
3786 @node Compiling Using gcc
3787 @chapter Compiling Using @command{gcc}
3788
3789 @noindent
3790 This chapter discusses how to compile Ada programs using the @command{gcc}
3791 command. It also describes the set of switches
3792 that can be used to control the behavior of the compiler.
3793 @menu
3794 * Compiling Programs::
3795 * Switches for gcc::
3796 * Search Paths and the Run-Time Library (RTL)::
3797 * Order of Compilation Issues::
3798 * Examples::
3799 @end menu
3800
3801 @node Compiling Programs
3802 @section Compiling Programs
3803
3804 @noindent
3805 The first step in creating an executable program is to compile the units
3806 of the program using the @command{gcc} command. You must compile the
3807 following files:
3808
3809 @itemize @bullet
3810 @item
3811 the body file (@file{.adb}) for a library level subprogram or generic
3812 subprogram
3813
3814 @item
3815 the spec file (@file{.ads}) for a library level package or generic
3816 package that has no body
3817
3818 @item
3819 the body file (@file{.adb}) for a library level package
3820 or generic package that has a body
3821
3822 @end itemize
3823
3824 @noindent
3825 You need @emph{not} compile the following files
3826
3827 @itemize @bullet
3828
3829 @item
3830 the spec of a library unit which has a body
3831
3832 @item
3833 subunits
3834 @end itemize
3835
3836 @noindent
3837 because they are compiled as part of compiling related units. GNAT
3838 package specs
3839 when the corresponding body is compiled, and subunits when the parent is
3840 compiled.
3841
3842 @cindex cannot generate code
3843 If you attempt to compile any of these files, you will get one of the
3844 following error messages (where @var{fff} is the name of the file you compiled):
3845
3846 @smallexample
3847 cannot generate code for file @var{fff} (package spec)
3848 to check package spec, use -gnatc
3849
3850 cannot generate code for file @var{fff} (missing subunits)
3851 to check parent unit, use -gnatc
3852
3853 cannot generate code for file @var{fff} (subprogram spec)
3854 to check subprogram spec, use -gnatc
3855
3856 cannot generate code for file @var{fff} (subunit)
3857 to check subunit, use -gnatc
3858 @end smallexample
3859
3860 @noindent
3861 As indicated by the above error messages, if you want to submit
3862 one of these files to the compiler to check for correct semantics
3863 without generating code, then use the @option{-gnatc} switch.
3864
3865 The basic command for compiling a file containing an Ada unit is
3866
3867 @smallexample
3868 @c $ gcc -c @ovar{switches} @file{file name}
3869 @c Expanding @ovar macro inline (explanation in macro def comments)
3870 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3871 @end smallexample
3872
3873 @noindent
3874 where @var{file name} is the name of the Ada file (usually
3875 having an extension
3876 @file{.ads} for a spec or @file{.adb} for a body).
3877 @ifclear vms
3878 You specify the
3879 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3880 @end ifclear
3881 The result of a successful compilation is an object file, which has the
3882 same name as the source file but an extension of @file{.o} and an Ada
3883 Library Information (ALI) file, which also has the same name as the
3884 source file, but with @file{.ali} as the extension. GNAT creates these
3885 two output files in the current directory, but you may specify a source
3886 file in any directory using an absolute or relative path specification
3887 containing the directory information.
3888
3889 @findex gnat1
3890 @command{gcc} is actually a driver program that looks at the extensions of
3891 the file arguments and loads the appropriate compiler. For example, the
3892 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3893 These programs are in directories known to the driver program (in some
3894 configurations via environment variables you set), but need not be in
3895 your path. The @command{gcc} driver also calls the assembler and any other
3896 utilities needed to complete the generation of the required object
3897 files.
3898
3899 It is possible to supply several file names on the same @command{gcc}
3900 command. This causes @command{gcc} to call the appropriate compiler for
3901 each file. For example, the following command lists three separate
3902 files to be compiled:
3903
3904 @smallexample
3905 $ gcc -c x.adb y.adb z.c
3906 @end smallexample
3907
3908 @noindent
3909 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3910 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3911 The compiler generates three object files @file{x.o}, @file{y.o} and
3912 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3913 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3914 @ifclear vms
3915 except for
3916 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3917 @end ifclear
3918
3919 @node Switches for gcc
3920 @section Switches for @command{gcc}
3921
3922 @noindent
3923 The @command{gcc} command accepts switches that control the
3924 compilation process. These switches are fully described in this section.
3925 First we briefly list all the switches, in alphabetical order, then we
3926 describe the switches in more detail in functionally grouped sections.
3927
3928 More switches exist for GCC than those documented here, especially
3929 for specific targets. However, their use is not recommended as
3930 they may change code generation in ways that are incompatible with
3931 the Ada run-time library, or can cause inconsistencies between
3932 compilation units.
3933
3934 @menu
3935 * Output and Error Message Control::
3936 * Warning Message Control::
3937 * Debugging and Assertion Control::
3938 * Validity Checking::
3939 * Style Checking::
3940 * Run-Time Checks::
3941 * Using gcc for Syntax Checking::
3942 * Using gcc for Semantic Checking::
3943 * Compiling Different Versions of Ada::
3944 * Character Set Control::
3945 * File Naming Control::
3946 * Subprogram Inlining Control::
3947 * Auxiliary Output Control::
3948 * Debugging Control::
3949 * Exception Handling Control::
3950 * Units to Sources Mapping Files::
3951 * Integrated Preprocessing::
3952 * Code Generation Control::
3953 @ifset vms
3954 * Return Codes::
3955 @end ifset
3956 @end menu
3957
3958 @table @option
3959 @c !sort!
3960 @ifclear vms
3961 @cindex @option{-b} (@command{gcc})
3962 @item -b @var{target}
3963 Compile your program to run on @var{target}, which is the name of a
3964 system configuration. You must have a GNAT cross-compiler built if
3965 @var{target} is not the same as your host system.
3966
3967 @item -B@var{dir}
3968 @cindex @option{-B} (@command{gcc})
3969 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3970 from @var{dir} instead of the default location. Only use this switch
3971 when multiple versions of the GNAT compiler are available.
3972 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3973 GNU Compiler Collection (GCC)}, for further details. You would normally
3974 use the @option{-b} or @option{-V} switch instead.
3975
3976 @item -c
3977 @cindex @option{-c} (@command{gcc})
3978 Compile. Always use this switch when compiling Ada programs.
3979
3980 Note: for some other languages when using @command{gcc}, notably in
3981 the case of C and C++, it is possible to use
3982 use @command{gcc} without a @option{-c} switch to
3983 compile and link in one step. In the case of GNAT, you
3984 cannot use this approach, because the binder must be run
3985 and @command{gcc} cannot be used to run the GNAT binder.
3986 @end ifclear
3987
3988 @item -fno-inline
3989 @cindex @option{-fno-inline} (@command{gcc})
3990 Suppresses all back-end inlining, even if other optimization or inlining
3991 switches are set.
3992 This includes suppression of inlining that results
3993 from the use of the pragma @code{Inline_Always}.
3994 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3995 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3996 effect if this switch is present.
3997
3998 @item -fno-inline-functions
3999 @cindex @option{-fno-inline-functions} (@command{gcc})
4000 Suppresses automatic inlining of simple subprograms, which is enabled
4001 if @option{-O3} is used.
4002
4003 @item -fno-inline-small-functions
4004 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4005 Suppresses automatic inlining of small subprograms, which is enabled
4006 if @option{-O2} is used.
4007
4008 @item -fno-inline-functions-called-once
4009 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4010 Suppresses inlining of subprograms local to the unit and called once
4011 from within it, which is enabled if @option{-O1} is used.
4012
4013 @item -fno-ivopts
4014 @cindex @option{-fno-ivopts} (@command{gcc})
4015 Suppresses high-level loop induction variable optimizations, which are
4016 enabled if @option{-O1} is used. These optimizations are generally
4017 profitable but, for some specific cases of loops with numerous uses
4018 of the iteration variable that follow a common pattern, they may end
4019 up destroying the regularity that could be exploited at a lower level
4020 and thus producing inferior code.
4021
4022 @item -fno-strict-aliasing
4023 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4024 Causes the compiler to avoid assumptions regarding non-aliasing
4025 of objects of different types. See
4026 @ref{Optimization and Strict Aliasing} for details.
4027
4028 @item -fstack-check
4029 @cindex @option{-fstack-check} (@command{gcc})
4030 Activates stack checking.
4031 See @ref{Stack Overflow Checking} for details.
4032
4033 @item -fstack-usage
4034 @cindex @option{-fstack-usage} (@command{gcc})
4035 Makes the compiler output stack usage information for the program, on a
4036 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4037
4038 @item -fcallgraph-info@r{[}=su@r{]}
4039 @cindex @option{-fcallgraph-info} (@command{gcc})
4040 Makes the compiler output callgraph information for the program, on a
4041 per-file basis.  The information is generated in the VCG format.  It can
4042 be decorated with stack-usage per-node information.
4043
4044 @item ^-g^/DEBUG^
4045 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4046 Generate debugging information. This information is stored in the object
4047 file and copied from there to the final executable file by the linker,
4048 where it can be read by the debugger. You must use the
4049 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4050
4051 @item -gnat83
4052 @cindex @option{-gnat83} (@command{gcc})
4053 Enforce Ada 83 restrictions.
4054
4055 @item -gnat95
4056 @cindex @option{-gnat95} (@command{gcc})
4057 Enforce Ada 95 restrictions.
4058
4059 @item -gnat05
4060 @cindex @option{-gnat05} (@command{gcc})
4061 Allow full Ada 2005 features.
4062
4063 @item -gnat2005
4064 @cindex @option{-gnat2005} (@command{gcc})
4065 Allow full Ada 2005 features (same as @option{-gnat05}
4066
4067 @item -gnat12
4068 @cindex @option{-gnat12} (@command{gcc})
4069
4070 @item -gnat2012
4071 @cindex @option{-gnat2012} (@command{gcc})
4072 Allow full Ada 2012 features (same as @option{-gnat12}
4073
4074 @item -gnata
4075 @cindex @option{-gnata} (@command{gcc})
4076 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4077 activated. Note that these pragmas can also be controlled using the
4078 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4079 It also activates pragmas @code{Check}, @code{Precondition}, and
4080 @code{Postcondition}. Note that these pragmas can also be controlled
4081 using the configuration pragma @code{Check_Policy}.
4082
4083 @item -gnatA
4084 @cindex @option{-gnatA} (@command{gcc})
4085 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4086 it will be ignored.
4087
4088 @item -gnatb
4089 @cindex @option{-gnatb} (@command{gcc})
4090 Generate brief messages to @file{stderr} even if verbose mode set.
4091
4092 @item -gnatB
4093 @cindex @option{-gnatB} (@command{gcc})
4094 Assume no invalid (bad) values except for 'Valid attribute use
4095 (@pxref{Validity Checking}).
4096
4097 @item -gnatc
4098 @cindex @option{-gnatc} (@command{gcc})
4099 Check syntax and semantics only (no code generation attempted).
4100
4101 @item -gnatC
4102 @cindex @option{-gnatC} (@command{gcc})
4103 Generate CodePeer information (no code generation attempted).
4104 This switch will generate an intermediate representation suitable for
4105 use by CodePeer (@file{.scil} files). This switch is not compatible with
4106 code generation (it will, among other things, disable some switches such
4107 as -gnatn, and enable others such as -gnata).
4108
4109 @item -gnatd
4110 @cindex @option{-gnatd} (@command{gcc})
4111 Specify debug options for the compiler. The string of characters after
4112 the @option{-gnatd} specify the specific debug options. The possible
4113 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4114 compiler source file @file{debug.adb} for details of the implemented
4115 debug options. Certain debug options are relevant to applications
4116 programmers, and these are documented at appropriate points in this
4117 users guide.
4118
4119 @ifclear vms
4120 @item -gnatD
4121 @cindex @option{-gnatD[nn]} (@command{gcc})
4122 @end ifclear
4123 @ifset vms
4124 @item /XDEBUG /LXDEBUG=nnn
4125 @end ifset
4126 Create expanded source files for source level debugging. This switch
4127 also suppress generation of cross-reference information
4128 (see @option{-gnatx}).
4129
4130 @item -gnatec=@var{path}
4131 @cindex @option{-gnatec} (@command{gcc})
4132 Specify a configuration pragma file
4133 @ifclear vms
4134 (the equal sign is optional)
4135 @end ifclear
4136 (@pxref{The Configuration Pragmas Files}).
4137
4138 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4139 @cindex @option{-gnateD} (@command{gcc})
4140 Defines a symbol, associated with @var{value}, for preprocessing.
4141 (@pxref{Integrated Preprocessing}).
4142
4143 @item -gnatef
4144 @cindex @option{-gnatef} (@command{gcc})
4145 Display full source path name in brief error messages.
4146
4147 @item -gnateG
4148 @cindex @option{-gnateG} (@command{gcc})
4149 Save result of preprocessing in a text file.
4150
4151 @item -gnatem=@var{path}
4152 @cindex @option{-gnatem} (@command{gcc})
4153 Specify a mapping file
4154 @ifclear vms
4155 (the equal sign is optional)
4156 @end ifclear
4157 (@pxref{Units to Sources Mapping Files}).
4158
4159 @item -gnatep=@var{file}
4160 @cindex @option{-gnatep} (@command{gcc})
4161 Specify a preprocessing data file
4162 @ifclear vms
4163 (the equal sign is optional)
4164 @end ifclear
4165 (@pxref{Integrated Preprocessing}).
4166
4167 @item -gnateS
4168 @cindex @option{-gnateS} (@command{gcc})
4169 Generate SCO (Source Coverage Obligation) information in the ALI
4170 file. This information is used by advanced coverage tools. See
4171 unit @file{SCOs} in the compiler sources for details in files
4172 @file{scos.ads} and @file{scos.adb}.
4173
4174 @item -gnatE
4175 @cindex @option{-gnatE} (@command{gcc})
4176 Full dynamic elaboration checks.
4177
4178 @item -gnatf
4179 @cindex @option{-gnatf} (@command{gcc})
4180 Full errors. Multiple errors per line, all undefined references, do not
4181 attempt to suppress cascaded errors.
4182
4183 @item -gnatF
4184 @cindex @option{-gnatF} (@command{gcc})
4185 Externals names are folded to all uppercase.
4186
4187 @item ^-gnatg^/GNAT_INTERNAL^
4188 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4189 Internal GNAT implementation mode. This should not be used for
4190 applications programs, it is intended only for use by the compiler
4191 and its run-time library. For documentation, see the GNAT sources.
4192 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4193 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4194 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4195 so that all standard warnings and all standard style options are turned on.
4196 All warnings and style messages are treated as errors.
4197
4198 @ifclear vms
4199 @item -gnatG=nn
4200 @cindex @option{-gnatG[nn]} (@command{gcc})
4201 @end ifclear
4202 @ifset vms
4203 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4204 @end ifset
4205 List generated expanded code in source form.
4206
4207 @item ^-gnath^/HELP^
4208 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4209 Output usage information. The output is written to @file{stdout}.
4210
4211 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4212 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4213 Identifier character set
4214 @ifclear vms
4215 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4216 @end ifclear
4217 For details of the possible selections for @var{c},
4218 see @ref{Character Set Control}.
4219
4220 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4221 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4222 Ignore representation clauses. When this switch is used,
4223 representation clauses are treated as comments. This is useful
4224 when initially porting code where you want to ignore rep clause
4225 problems, and also for compiling foreign code (particularly
4226 for use with ASIS). The representation clauses that are ignored
4227 are: enumeration_representation_clause, record_representation_clause,
4228 and attribute_definition_clause for the following attributes:
4229 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4230 Object_Size, Size, Small, Stream_Size, and Value_Size.
4231 Note that this option should be used only for compiling -- the
4232 code is likely to malfunction at run time.
4233
4234 @item -gnatjnn
4235 @cindex @option{-gnatjnn} (@command{gcc})
4236 Reformat error messages to fit on nn character lines
4237
4238 @item -gnatk=@var{n}
4239 @cindex @option{-gnatk} (@command{gcc})
4240 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4241
4242 @item -gnatl
4243 @cindex @option{-gnatl} (@command{gcc})
4244 Output full source listing with embedded error messages.
4245
4246 @item -gnatL
4247 @cindex @option{-gnatL} (@command{gcc})
4248 Used in conjunction with -gnatG or -gnatD to intersperse original
4249 source lines (as comment lines with line numbers) in the expanded
4250 source output.
4251
4252 @item -gnatm=@var{n}
4253 @cindex @option{-gnatm} (@command{gcc})
4254 Limit number of detected error or warning messages to @var{n}
4255 where @var{n} is in the range 1..999999. The default setting if
4256 no switch is given is 9999. If the number of warnings reaches this
4257 limit, then a message is output and further warnings are suppressed,
4258 but the compilation is continued. If the number of error messages
4259 reaches this limit, then a message is output and the compilation
4260 is abandoned. The equal sign here is optional. A value of zero
4261 means that no limit applies.
4262
4263 @item -gnatn
4264 @cindex @option{-gnatn} (@command{gcc})
4265 Activate inlining for subprograms for which
4266 pragma @code{inline} is specified. This inlining is performed
4267 by the GCC back-end.
4268
4269 @item -gnatN
4270 @cindex @option{-gnatN} (@command{gcc})
4271 Activate front end inlining for subprograms for which
4272 pragma @code{Inline} is specified. This inlining is performed
4273 by the front end and will be visible in the
4274 @option{-gnatG} output.
4275
4276 When using a gcc-based back end (in practice this means using any version
4277 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4278 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4279 Historically front end inlining was more extensive than the gcc back end
4280 inlining, but that is no longer the case.
4281
4282 @item -gnato
4283 @cindex @option{-gnato} (@command{gcc})
4284 Enable numeric overflow checking (which is not normally enabled by
4285 default). Note that division by zero is a separate check that is not
4286 controlled by this switch (division by zero checking is on by default).
4287
4288 @item -gnatp
4289 @cindex @option{-gnatp} (@command{gcc})
4290 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4291 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4292
4293 @item -gnat-p
4294 @cindex @option{-gnat-p} (@command{gcc})
4295 Cancel effect of previous @option{-gnatp} switch.
4296
4297 @item -gnatP
4298 @cindex @option{-gnatP} (@command{gcc})
4299 Enable polling. This is required on some systems (notably Windows NT) to
4300 obtain asynchronous abort and asynchronous transfer of control capability.
4301 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4302 details.
4303
4304 @item -gnatq
4305 @cindex @option{-gnatq} (@command{gcc})
4306 Don't quit. Try semantics, even if parse errors.
4307
4308 @item -gnatQ
4309 @cindex @option{-gnatQ} (@command{gcc})
4310 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4311
4312 @item -gnatr
4313 @cindex @option{-gnatr} (@command{gcc})
4314 Treat pragma Restrictions as Restriction_Warnings.
4315
4316 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4317 @cindex @option{-gnatR} (@command{gcc})
4318 Output representation information for declared types and objects.
4319
4320 @item -gnats
4321 @cindex @option{-gnats} (@command{gcc})
4322 Syntax check only.
4323
4324 @item -gnatS
4325 @cindex @option{-gnatS} (@command{gcc})
4326 Print package Standard.
4327
4328 @item -gnatt
4329 @cindex @option{-gnatt} (@command{gcc})
4330 Generate tree output file.
4331
4332 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4333 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4334 All compiler tables start at @var{nnn} times usual starting size.
4335
4336 @item -gnatu
4337 @cindex @option{-gnatu} (@command{gcc})
4338 List units for this compilation.
4339
4340 @item -gnatU
4341 @cindex @option{-gnatU} (@command{gcc})
4342 Tag all error messages with the unique string ``error:''
4343
4344 @item -gnatv
4345 @cindex @option{-gnatv} (@command{gcc})
4346 Verbose mode. Full error output with source lines to @file{stdout}.
4347
4348 @item -gnatV
4349 @cindex @option{-gnatV} (@command{gcc})
4350 Control level of validity checking (@pxref{Validity Checking}).
4351
4352 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4353 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4354 Warning mode where
4355 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4356 the exact warnings that
4357 are enabled or disabled (@pxref{Warning Message Control}).
4358
4359 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4360 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4361 Wide character encoding method
4362 @ifclear vms
4363 (@var{e}=n/h/u/s/e/8).
4364 @end ifclear
4365 @ifset vms
4366 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4367 @end ifset
4368
4369 @item -gnatx
4370 @cindex @option{-gnatx} (@command{gcc})
4371 Suppress generation of cross-reference information.
4372
4373 @item -gnatX
4374 @cindex @option{-gnatX} (@command{gcc})
4375 Enable GNAT implementation extensions and latest Ada version.
4376
4377 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4378 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4379 Enable built-in style checks (@pxref{Style Checking}).
4380
4381 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4382 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4383 Distribution stub generation and compilation
4384 @ifclear vms
4385 (@var{m}=r/c for receiver/caller stubs).
4386 @end ifclear
4387 @ifset vms
4388 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4389 to be generated and compiled).
4390 @end ifset
4391
4392 @item ^-I^/SEARCH=^@var{dir}
4393 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4394 @cindex RTL
4395 Direct GNAT to search the @var{dir} directory for source files needed by
4396 the current compilation
4397 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4398
4399 @item ^-I-^/NOCURRENT_DIRECTORY^
4400 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4401 @cindex RTL
4402 Except for the source file named in the command line, do not look for source
4403 files in the directory containing the source file named in the command line
4404 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4405
4406 @ifclear vms
4407 @item -mbig-switch
4408 @cindex @option{-mbig-switch} (@command{gcc})
4409 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4410 This standard gcc switch causes the compiler to use larger offsets in its
4411 jump table representation for @code{case} statements.
4412 This may result in less efficient code, but is sometimes necessary
4413 (for example on HP-UX targets)
4414 @cindex HP-UX and @option{-mbig-switch} option
4415 in order to compile large and/or nested @code{case} statements.
4416
4417 @item -o @var{file}
4418 @cindex @option{-o} (@command{gcc})
4419 This switch is used in @command{gcc} to redirect the generated object file
4420 and its associated ALI file. Beware of this switch with GNAT, because it may
4421 cause the object file and ALI file to have different names which in turn
4422 may confuse the binder and the linker.
4423 @end ifclear
4424
4425 @item -nostdinc
4426 @cindex @option{-nostdinc} (@command{gcc})
4427 Inhibit the search of the default location for the GNAT Run Time
4428 Library (RTL) source files.
4429
4430 @item -nostdlib
4431 @cindex @option{-nostdlib} (@command{gcc})
4432 Inhibit the search of the default location for the GNAT Run Time
4433 Library (RTL) ALI files.
4434
4435 @ifclear vms
4436 @c @item -O@ovar{n}
4437 @c Expanding @ovar macro inline (explanation in macro def comments)
4438 @item -O@r{[}@var{n}@r{]}
4439 @cindex @option{-O} (@command{gcc})
4440 @var{n} controls the optimization level.
4441
4442 @table @asis
4443 @item n = 0
4444 No optimization, the default setting if no @option{-O} appears
4445
4446 @item n = 1
4447 Normal optimization, the default if you specify @option{-O} without
4448 an operand. A good compromise between code quality and compilation
4449 time.
4450
4451 @item n = 2
4452 Extensive optimization, may improve execution time, possibly at the cost of
4453 substantially increased compilation time.
4454
4455 @item n = 3
4456 Same as @option{-O2}, and also includes inline expansion for small subprograms
4457 in the same unit.
4458
4459 @item n = s
4460 Optimize space usage
4461 @end table
4462
4463 @noindent
4464 See also @ref{Optimization Levels}.
4465 @end ifclear
4466
4467 @ifset vms
4468 @item  /NOOPTIMIZE
4469 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4470 Equivalent to @option{/OPTIMIZE=NONE}.
4471 This is the default behavior in the absence of an @option{/OPTIMIZE}
4472 qualifier.
4473
4474 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4475 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4476 Selects the level of optimization for your program. The supported
4477 keywords are as follows:
4478 @table @code
4479 @item   ALL
4480 Perform most optimizations, including those that
4481 are expensive.
4482 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4483 without keyword options.
4484
4485 @item   NONE
4486 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4487
4488 @item SOME
4489 Perform some optimizations, but omit ones that are costly.
4490
4491 @item   DEVELOPMENT
4492 Same as @code{SOME}.
4493
4494 @item INLINING
4495 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4496 automatic inlining of small subprograms within a unit
4497
4498 @item   UNROLL_LOOPS
4499 Try to unroll loops. This keyword may be specified together with
4500 any keyword above other than @code{NONE}. Loop unrolling
4501 usually, but not always, improves the performance of programs.
4502
4503 @item SPACE
4504 Optimize space usage
4505 @end table
4506
4507 @noindent
4508 See also @ref{Optimization Levels}.
4509 @end ifset
4510
4511 @ifclear vms
4512 @item -pass-exit-codes
4513 @cindex @option{-pass-exit-codes} (@command{gcc})
4514 Catch exit codes from the compiler and use the most meaningful as
4515 exit status.
4516 @end ifclear
4517
4518 @item --RTS=@var{rts-path}
4519 @cindex @option{--RTS} (@command{gcc})
4520 Specifies the default location of the runtime library. Same meaning as the
4521 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4522
4523 @item ^-S^/ASM^
4524 @cindex @option{^-S^/ASM^} (@command{gcc})
4525 ^Used in place of @option{-c} to^Used to^
4526 cause the assembler source file to be
4527 generated, using @file{^.s^.S^} as the extension,
4528 instead of the object file.
4529 This may be useful if you need to examine the generated assembly code.
4530
4531 @item ^-fverbose-asm^/VERBOSE_ASM^
4532 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4533 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4534 to cause the generated assembly code file to be annotated with variable
4535 names, making it significantly easier to follow.
4536
4537 @item ^-v^/VERBOSE^
4538 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4539 Show commands generated by the @command{gcc} driver. Normally used only for
4540 debugging purposes or if you need to be sure what version of the
4541 compiler you are executing.
4542
4543 @ifclear vms
4544 @item -V @var{ver}
4545 @cindex @option{-V} (@command{gcc})
4546 Execute @var{ver} version of the compiler. This is the @command{gcc}
4547 version, not the GNAT version.
4548 @end ifclear
4549
4550 @item ^-w^/NO_BACK_END_WARNINGS^
4551 @cindex @option{-w} (@command{gcc})
4552 Turn off warnings generated by the back end of the compiler. Use of
4553 this switch also causes the default for front end warnings to be set
4554 to suppress (as though @option{-gnatws} had appeared at the start of
4555 the options).
4556
4557 @end table
4558
4559 @ifclear vms
4560 @c Combining qualifiers does not work on VMS
4561 You may combine a sequence of GNAT switches into a single switch. For
4562 example, the combined switch
4563
4564 @cindex Combining GNAT switches
4565 @smallexample
4566 -gnatofi3
4567 @end smallexample
4568
4569 @noindent
4570 is equivalent to specifying the following sequence of switches:
4571
4572 @smallexample
4573 -gnato -gnatf -gnati3
4574 @end smallexample
4575 @end ifclear
4576
4577 @noindent
4578 The following restrictions apply to the combination of switches
4579 in this manner:
4580
4581 @itemize @bullet
4582 @item
4583 The switch @option{-gnatc} if combined with other switches must come
4584 first in the string.
4585
4586 @item
4587 The switch @option{-gnats} if combined with other switches must come
4588 first in the string.
4589
4590 @item
4591 The switches
4592 ^^@option{/DISTRIBUTION_STUBS=},^
4593 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4594 switches, and only one of them may appear in the command line.
4595
4596 @item
4597 The switch @option{-gnat-p} may not be combined with any other switch.
4598
4599 @ifclear vms
4600 @item
4601 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4602 switch), then all further characters in the switch are interpreted
4603 as style modifiers (see description of @option{-gnaty}).
4604
4605 @item
4606 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4607 switch), then all further characters in the switch are interpreted
4608 as debug flags (see description of @option{-gnatd}).
4609
4610 @item
4611 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4612 switch), then all further characters in the switch are interpreted
4613 as warning mode modifiers (see description of @option{-gnatw}).
4614
4615 @item
4616 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4617 switch), then all further characters in the switch are interpreted
4618 as validity checking options (@pxref{Validity Checking}).
4619
4620 @item
4621 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4622 a combined list of options.
4623 @end ifclear
4624 @end itemize
4625
4626 @node Output and Error Message Control
4627 @subsection Output and Error Message Control
4628 @findex stderr
4629
4630 @noindent
4631 The standard default format for error messages is called ``brief format''.
4632 Brief format messages are written to @file{stderr} (the standard error
4633 file) and have the following form:
4634
4635 @smallexample
4636 e.adb:3:04: Incorrect spelling of keyword "function"
4637 e.adb:4:20: ";" should be "is"
4638 @end smallexample
4639
4640 @noindent
4641 The first integer after the file name is the line number in the file,
4642 and the second integer is the column number within the line.
4643 @ifclear vms
4644 @code{GPS} can parse the error messages
4645 and point to the referenced character.
4646 @end ifclear
4647 The following switches provide control over the error message
4648 format:
4649
4650 @table @option
4651 @c !sort!
4652 @item -gnatv
4653 @cindex @option{-gnatv} (@command{gcc})
4654 @findex stdout
4655 @ifclear vms
4656 The v stands for verbose.
4657 @end ifclear
4658 The effect of this setting is to write long-format error
4659 messages to @file{stdout} (the standard output file.
4660 The same program compiled with the
4661 @option{-gnatv} switch would generate:
4662
4663 @smallexample
4664 @cartouche
4665 3. funcion X (Q : Integer)
4666    |
4667 >>> Incorrect spelling of keyword "function"
4668 4. return Integer;
4669                  |
4670 >>> ";" should be "is"
4671 @end cartouche
4672 @end smallexample
4673
4674 @noindent
4675 The vertical bar indicates the location of the error, and the @samp{>>>}
4676 prefix can be used to search for error messages. When this switch is
4677 used the only source lines output are those with errors.
4678
4679 @item -gnatl
4680 @cindex @option{-gnatl} (@command{gcc})
4681 @ifclear vms
4682 The @code{l} stands for list.
4683 @end ifclear
4684 This switch causes a full listing of
4685 the file to be generated. In the case where a body is
4686 compiled, the corresponding spec is also listed, along
4687 with any subunits. Typical output from compiling a package
4688 body @file{p.adb} might look like:
4689
4690 @smallexample @c ada
4691 @cartouche
4692  Compiling: p.adb
4693
4694      1. package body p is
4695      2.    procedure a;
4696      3.    procedure a is separate;
4697      4. begin
4698      5.    null
4699                |
4700         >>> missing ";"
4701
4702      6. end;
4703
4704 Compiling: p.ads
4705
4706      1. package p is
4707      2.    pragma Elaborate_Body
4708                                 |
4709         >>> missing ";"
4710
4711      3. end p;
4712
4713 Compiling: p-a.adb
4714
4715      1. separate p
4716                 |
4717         >>> missing "("
4718
4719      2. procedure a is
4720      3. begin
4721      4.    null
4722                |
4723         >>> missing ";"
4724
4725      5. end;
4726 @end cartouche
4727 @end smallexample
4728
4729 @noindent
4730 @findex stderr
4731 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4732 standard output is redirected, a brief summary is written to
4733 @file{stderr} (standard error) giving the number of error messages and
4734 warning messages generated.
4735
4736 @item -^gnatl^OUTPUT_FILE^=file
4737 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4738 This has the same effect as @option{-gnatl} except that the output is
4739 written to a file instead of to standard output. If the given name
4740 @file{fname} does not start with a period, then it is the full name
4741 of the file to be written. If @file{fname} is an extension, it is
4742 appended to the name of the file being compiled. For example, if
4743 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4744 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4745
4746 @item -gnatU
4747 @cindex @option{-gnatU} (@command{gcc})
4748 This switch forces all error messages to be preceded by the unique
4749 string ``error:''. This means that error messages take a few more
4750 characters in space, but allows easy searching for and identification
4751 of error messages.
4752
4753 @item -gnatb
4754 @cindex @option{-gnatb} (@command{gcc})
4755 @ifclear vms
4756 The @code{b} stands for brief.
4757 @end ifclear
4758 This switch causes GNAT to generate the
4759 brief format error messages to @file{stderr} (the standard error
4760 file) as well as the verbose
4761 format message or full listing (which as usual is written to
4762 @file{stdout} (the standard output file).
4763
4764 @item -gnatm=@var{n}
4765 @cindex @option{-gnatm} (@command{gcc})
4766 @ifclear vms
4767 The @code{m} stands for maximum.
4768 @end ifclear
4769 @var{n} is a decimal integer in the
4770 range of 1 to 999999 and limits the number of error or warning
4771 messages to be generated. For example, using
4772 @option{-gnatm2} might yield
4773
4774 @smallexample
4775 e.adb:3:04: Incorrect spelling of keyword "function"
4776 e.adb:5:35: missing ".."
4777 fatal error: maximum number of errors detected
4778 compilation abandoned
4779 @end smallexample
4780
4781 @noindent
4782 The default setting if
4783 no switch is given is 9999. If the number of warnings reaches this
4784 limit, then a message is output and further warnings are suppressed,
4785 but the compilation is continued. If the number of error messages
4786 reaches this limit, then a message is output and the compilation
4787 is abandoned. A value of zero means that no limit applies.
4788
4789 @noindent
4790 Note that the equal sign is optional, so the switches
4791 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4792
4793 @item -gnatf
4794 @cindex @option{-gnatf} (@command{gcc})
4795 @cindex Error messages, suppressing
4796 @ifclear vms
4797 The @code{f} stands for full.
4798 @end ifclear
4799 Normally, the compiler suppresses error messages that are likely to be
4800 redundant. This switch causes all error
4801 messages to be generated. In particular, in the case of
4802 references to undefined variables. If a given variable is referenced
4803 several times, the normal format of messages is
4804 @smallexample
4805 e.adb:7:07: "V" is undefined (more references follow)
4806 @end smallexample
4807
4808 @noindent
4809 where the parenthetical comment warns that there are additional
4810 references to the variable @code{V}. Compiling the same program with the
4811 @option{-gnatf} switch yields
4812
4813 @smallexample
4814 e.adb:7:07: "V" is undefined
4815 e.adb:8:07: "V" is undefined
4816 e.adb:8:12: "V" is undefined
4817 e.adb:8:16: "V" is undefined
4818 e.adb:9:07: "V" is undefined
4819 e.adb:9:12: "V" is undefined
4820 @end smallexample
4821
4822 @noindent
4823 The @option{-gnatf} switch also generates additional information for
4824 some error messages.  Some examples are:
4825
4826 @itemize @bullet
4827 @item
4828 Details on possibly non-portable unchecked conversion
4829 @item
4830 List possible interpretations for ambiguous calls
4831 @item
4832 Additional details on incorrect parameters
4833 @end itemize
4834
4835 @item -gnatjnn
4836 @cindex @option{-gnatjnn} (@command{gcc})
4837 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4838 with continuation lines are treated as though the continuation lines were
4839 separate messages (and so a warning with two continuation lines counts as
4840 three warnings, and is listed as three separate messages).
4841
4842 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4843 messages are output in a different manner. A message and all its continuation
4844 lines are treated as a unit, and count as only one warning or message in the
4845 statistics totals. Furthermore, the message is reformatted so that no line
4846 is longer than nn characters.
4847
4848 @item -gnatq
4849 @cindex @option{-gnatq} (@command{gcc})
4850 @ifclear vms
4851 The @code{q} stands for quit (really ``don't quit'').
4852 @end ifclear
4853 In normal operation mode, the compiler first parses the program and
4854 determines if there are any syntax errors. If there are, appropriate
4855 error messages are generated and compilation is immediately terminated.
4856 This switch tells
4857 GNAT to continue with semantic analysis even if syntax errors have been
4858 found. This may enable the detection of more errors in a single run. On
4859 the other hand, the semantic analyzer is more likely to encounter some
4860 internal fatal error when given a syntactically invalid tree.
4861
4862 @item -gnatQ
4863 @cindex @option{-gnatQ} (@command{gcc})
4864 In normal operation mode, the @file{ALI} file is not generated if any
4865 illegalities are detected in the program. The use of @option{-gnatQ} forces
4866 generation of the @file{ALI} file. This file is marked as being in
4867 error, so it cannot be used for binding purposes, but it does contain
4868 reasonably complete cross-reference information, and thus may be useful
4869 for use by tools (e.g., semantic browsing tools or integrated development
4870 environments) that are driven from the @file{ALI} file. This switch
4871 implies @option{-gnatq}, since the semantic phase must be run to get a
4872 meaningful ALI file.
4873
4874 In addition, if @option{-gnatt} is also specified, then the tree file is
4875 generated even if there are illegalities. It may be useful in this case
4876 to also specify @option{-gnatq} to ensure that full semantic processing
4877 occurs. The resulting tree file can be processed by ASIS, for the purpose
4878 of providing partial information about illegal units, but if the error
4879 causes the tree to be badly malformed, then ASIS may crash during the
4880 analysis.
4881
4882 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4883 being in error, @command{gnatmake} will attempt to recompile the source when it
4884 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4885
4886 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4887 since ALI files are never generated if @option{-gnats} is set.
4888
4889 @end table
4890
4891 @node Warning Message Control
4892 @subsection Warning Message Control
4893 @cindex Warning messages
4894 @noindent
4895 In addition to error messages, which correspond to illegalities as defined
4896 in the Ada Reference Manual, the compiler detects two kinds of warning
4897 situations.
4898
4899 First, the compiler considers some constructs suspicious and generates a
4900 warning message to alert you to a possible error. Second, if the
4901 compiler detects a situation that is sure to raise an exception at
4902 run time, it generates a warning message. The following shows an example
4903 of warning messages:
4904 @smallexample
4905 e.adb:4:24: warning: creation of object may raise Storage_Error
4906 e.adb:10:17: warning: static value out of range
4907 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4908 @end smallexample
4909
4910 @noindent
4911 GNAT considers a large number of situations as appropriate
4912 for the generation of warning messages. As always, warnings are not
4913 definite indications of errors. For example, if you do an out-of-range
4914 assignment with the deliberate intention of raising a
4915 @code{Constraint_Error} exception, then the warning that may be
4916 issued does not indicate an error. Some of the situations for which GNAT
4917 issues warnings (at least some of the time) are given in the following
4918 list. This list is not complete, and new warnings are often added to
4919 subsequent versions of GNAT. The list is intended to give a general idea
4920 of the kinds of warnings that are generated.
4921
4922 @itemize @bullet
4923 @item
4924 Possible infinitely recursive calls
4925
4926 @item
4927 Out-of-range values being assigned
4928
4929 @item
4930 Possible order of elaboration problems
4931
4932 @item
4933 Assertions (pragma Assert) that are sure to fail
4934
4935 @item
4936 Unreachable code
4937
4938 @item
4939 Address clauses with possibly unaligned values, or where an attempt is
4940 made to overlay a smaller variable with a larger one.
4941
4942 @item
4943 Fixed-point type declarations with a null range
4944
4945 @item
4946 Direct_IO or Sequential_IO instantiated with a type that has access values
4947
4948 @item
4949 Variables that are never assigned a value
4950
4951 @item
4952 Variables that are referenced before being initialized
4953
4954 @item
4955 Task entries with no corresponding @code{accept} statement
4956
4957 @item
4958 Duplicate accepts for the same task entry in a @code{select}
4959
4960 @item
4961 Objects that take too much storage
4962
4963 @item
4964 Unchecked conversion between types of differing sizes
4965
4966 @item
4967 Missing @code{return} statement along some execution path in a function
4968
4969 @item
4970 Incorrect (unrecognized) pragmas
4971
4972 @item
4973 Incorrect external names
4974
4975 @item
4976 Allocation from empty storage pool
4977
4978 @item
4979 Potentially blocking operation in protected type
4980
4981 @item
4982 Suspicious parenthesization of expressions
4983
4984 @item
4985 Mismatching bounds in an aggregate
4986
4987 @item
4988 Attempt to return local value by reference
4989
4990 @item
4991 Premature instantiation of a generic body
4992
4993 @item
4994 Attempt to pack aliased components
4995
4996 @item
4997 Out of bounds array subscripts
4998
4999 @item
5000 Wrong length on string assignment
5001
5002 @item
5003 Violations of style rules if style checking is enabled
5004
5005 @item
5006 Unused @code{with} clauses
5007
5008 @item
5009 @code{Bit_Order} usage that does not have any effect
5010
5011 @item
5012 @code{Standard.Duration} used to resolve universal fixed expression
5013
5014 @item
5015 Dereference of possibly null value
5016
5017 @item
5018 Declaration that is likely to cause storage error
5019
5020 @item
5021 Internal GNAT unit @code{with}'ed by application unit
5022
5023 @item
5024 Values known to be out of range at compile time
5025
5026 @item
5027 Unreferenced labels and variables
5028
5029 @item
5030 Address overlays that could clobber memory
5031
5032 @item
5033 Unexpected initialization when address clause present
5034
5035 @item
5036 Bad alignment for address clause
5037
5038 @item
5039 Useless type conversions
5040
5041 @item
5042 Redundant assignment statements and other redundant constructs
5043
5044 @item
5045 Useless exception handlers
5046
5047 @item
5048 Accidental hiding of name by child unit
5049
5050 @item
5051 Access before elaboration detected at compile time
5052
5053 @item
5054 A range in a @code{for} loop that is known to be null or might be null
5055
5056 @end itemize
5057
5058 @noindent
5059 The following section lists compiler switches that are available
5060 to control the handling of warning messages. It is also possible
5061 to exercise much finer control over what warnings are issued and
5062 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5063 gnat_rm, GNAT Reference manual}.
5064
5065 @table @option
5066 @c !sort!
5067 @item -gnatwa
5068 @emph{Activate all optional errors.}
5069 @cindex @option{-gnatwa} (@command{gcc})
5070 This switch activates most optional warning messages, see remaining list
5071 in this section for details on optional warning messages that can be
5072 individually controlled.  The warnings that are not turned on by this
5073 switch are
5074 @option{-gnatwd} (implicit dereferencing),
5075 @option{-gnatwh} (hiding),
5076 @option{-gnatwl} (elaboration warnings),
5077 @option{-gnatw.o} (warn on values set by out parameters ignored)
5078 and @option{-gnatwt} (tracking of deleted conditional code).
5079 All other optional warnings are turned on.
5080
5081 @item -gnatwA
5082 @emph{Suppress all optional errors.}
5083 @cindex @option{-gnatwA} (@command{gcc})
5084 This switch suppresses all optional warning messages, see remaining list
5085 in this section for details on optional warning messages that can be
5086 individually controlled.
5087
5088 @item -gnatw.a
5089 @emph{Activate warnings on failing assertions.}
5090 @cindex @option{-gnatw.a} (@command{gcc})
5091 @cindex Assert failures
5092 This switch activates warnings for assertions where the compiler can tell at
5093 compile time that the assertion will fail. Note that this warning is given
5094 even if assertions are disabled. The default is that such warnings are
5095 generated.
5096
5097 @item -gnatw.A
5098 @emph{Suppress warnings on failing assertions.}
5099 @cindex @option{-gnatw.A} (@command{gcc})
5100 @cindex Assert failures
5101 This switch suppresses warnings for assertions where the compiler can tell at
5102 compile time that the assertion will fail.
5103
5104 @item -gnatwb
5105 @emph{Activate warnings on bad fixed values.}
5106 @cindex @option{-gnatwb} (@command{gcc})
5107 @cindex Bad fixed values
5108 @cindex Fixed-point Small value
5109 @cindex Small value
5110 This switch activates warnings for static fixed-point expressions whose
5111 value is not an exact multiple of Small. Such values are implementation
5112 dependent, since an implementation is free to choose either of the multiples
5113 that surround the value. GNAT always chooses the closer one, but this is not
5114 required behavior, and it is better to specify a value that is an exact
5115 multiple, ensuring predictable execution. The default is that such warnings
5116 are not generated.
5117
5118 @item -gnatwB
5119 @emph{Suppress warnings on bad fixed values.}
5120 @cindex @option{-gnatwB} (@command{gcc})
5121 This switch suppresses warnings for static fixed-point expressions whose
5122 value is not an exact multiple of Small.
5123
5124 @item -gnatw.b
5125 @emph{Activate warnings on biased representation.}
5126 @cindex @option{-gnatw.b} (@command{gcc})
5127 @cindex Biased representation
5128 This switch activates warnings when a size clause, value size clause, component
5129 clause, or component size clause forces the use of biased representation for an
5130 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5131 to represent 10/11). The default is that such warnings are generated.
5132
5133 @item -gnatw.B
5134 @emph{Suppress warnings on biased representation.}
5135 @cindex @option{-gnatwB} (@command{gcc})
5136 This switch suppresses warnings for representation clauses that force the use
5137 of biased representation.
5138
5139 @item -gnatwc
5140 @emph{Activate warnings on conditionals.}
5141 @cindex @option{-gnatwc} (@command{gcc})
5142 @cindex Conditionals, constant
5143 This switch activates warnings for conditional expressions used in
5144 tests that are known to be True or False at compile time. The default
5145 is that such warnings are not generated.
5146 Note that this warning does
5147 not get issued for the use of boolean variables or constants whose
5148 values are known at compile time, since this is a standard technique
5149 for conditional compilation in Ada, and this would generate too many
5150 false positive warnings.
5151
5152 This warning option also activates a special test for comparisons using
5153 the operators ``>='' and`` <=''.
5154 If the compiler can tell that only the equality condition is possible,
5155 then it will warn that the ``>'' or ``<'' part of the test
5156 is useless and that the operator could be replaced by ``=''.
5157 An example would be comparing a @code{Natural} variable <= 0.
5158
5159 This warning option also generates warnings if
5160 one or both tests is optimized away in a membership test for integer
5161 values if the result can be determined at compile time. Range tests on
5162 enumeration types are not included, since it is common for such tests
5163 to include an end point.
5164
5165 This warning can also be turned on using @option{-gnatwa}.
5166
5167 @item -gnatwC
5168 @emph{Suppress warnings on conditionals.}
5169 @cindex @option{-gnatwC} (@command{gcc})
5170 This switch suppresses warnings for conditional expressions used in
5171 tests that are known to be True or False at compile time.
5172
5173 @item -gnatw.c
5174 @emph{Activate warnings on missing component clauses.}
5175 @cindex @option{-gnatw.c} (@command{gcc})
5176 @cindex Component clause, missing
5177 This switch activates warnings for record components where a record
5178 representation clause is present and has component clauses for the
5179 majority, but not all, of the components. A warning is given for each
5180 component for which no component clause is present.
5181
5182 This warning can also be turned on using @option{-gnatwa}.
5183
5184 @item -gnatw.C
5185 @emph{Suppress warnings on missing component clauses.}
5186 @cindex @option{-gnatwC} (@command{gcc})
5187 This switch suppresses warnings for record components that are
5188 missing a component clause in the situation described above.
5189
5190 @item -gnatwd
5191 @emph{Activate warnings on implicit dereferencing.}
5192 @cindex @option{-gnatwd} (@command{gcc})
5193 If this switch is set, then the use of a prefix of an access type
5194 in an indexed component, slice, or selected component without an
5195 explicit @code{.all} will generate a warning. With this warning
5196 enabled, access checks occur only at points where an explicit
5197 @code{.all} appears in the source code (assuming no warnings are
5198 generated as a result of this switch). The default is that such
5199 warnings are not generated.
5200 Note that @option{-gnatwa} does not affect the setting of
5201 this warning option.
5202
5203 @item -gnatwD
5204 @emph{Suppress warnings on implicit dereferencing.}
5205 @cindex @option{-gnatwD} (@command{gcc})
5206 @cindex Implicit dereferencing
5207 @cindex Dereferencing, implicit
5208 This switch suppresses warnings for implicit dereferences in
5209 indexed components, slices, and selected components.
5210
5211 @item -gnatwe
5212 @emph{Treat warnings and style checks as errors.}
5213 @cindex @option{-gnatwe} (@command{gcc})
5214 @cindex Warnings, treat as error
5215 This switch causes warning messages and style check messages to be
5216 treated as errors.
5217 The warning string still appears, but the warning messages are counted
5218 as errors, and prevent the generation of an object file. Note that this
5219 is the only -gnatw switch that affects the handling of style check messages.
5220
5221 @item -gnatw.e
5222 @emph{Activate every optional warning}
5223 @cindex @option{-gnatw.e} (@command{gcc})
5224 @cindex Warnings, activate every optional warning
5225 This switch activates all optional warnings, including those which
5226 are not activated by @code{-gnatwa}.
5227
5228 @item -gnatwf
5229 @emph{Activate warnings on unreferenced formals.}
5230 @cindex @option{-gnatwf} (@command{gcc})
5231 @cindex Formals, unreferenced
5232 This switch causes a warning to be generated if a formal parameter
5233 is not referenced in the body of the subprogram. This warning can
5234 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5235 default is that these warnings are not generated.
5236
5237 @item -gnatwF
5238 @emph{Suppress warnings on unreferenced formals.}
5239 @cindex @option{-gnatwF} (@command{gcc})
5240 This switch suppresses warnings for unreferenced formal
5241 parameters. Note that the
5242 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5243 effect of warning on unreferenced entities other than subprogram
5244 formals.
5245
5246 @item -gnatwg
5247 @emph{Activate warnings on unrecognized pragmas.}
5248 @cindex @option{-gnatwg} (@command{gcc})
5249 @cindex Pragmas, unrecognized
5250 This switch causes a warning to be generated if an unrecognized
5251 pragma is encountered. Apart from issuing this warning, the
5252 pragma is ignored and has no effect. This warning can
5253 also be turned on using @option{-gnatwa}. The default
5254 is that such warnings are issued (satisfying the Ada Reference
5255 Manual requirement that such warnings appear).
5256
5257 @item -gnatwG
5258 @emph{Suppress warnings on unrecognized pragmas.}
5259 @cindex @option{-gnatwG} (@command{gcc})
5260 This switch suppresses warnings for unrecognized pragmas.
5261
5262 @item -gnatwh
5263 @emph{Activate warnings on hiding.}
5264 @cindex @option{-gnatwh} (@command{gcc})
5265 @cindex Hiding of Declarations
5266 This switch activates warnings on hiding declarations.
5267 A declaration is considered hiding
5268 if it is for a non-overloadable entity, and it declares an entity with the
5269 same name as some other entity that is directly or use-visible. The default
5270 is that such warnings are not generated.
5271 Note that @option{-gnatwa} does not affect the setting of this warning option.
5272
5273 @item -gnatwH
5274 @emph{Suppress warnings on hiding.}
5275 @cindex @option{-gnatwH} (@command{gcc})
5276 This switch suppresses warnings on hiding declarations.
5277
5278 @item -gnatwi
5279 @emph{Activate warnings on implementation units.}
5280 @cindex @option{-gnatwi} (@command{gcc})
5281 This switch activates warnings for a @code{with} of an internal GNAT
5282 implementation unit, defined as any unit from the @code{Ada},
5283 @code{Interfaces}, @code{GNAT},
5284 ^^@code{DEC},^ or @code{System}
5285 hierarchies that is not
5286 documented in either the Ada Reference Manual or the GNAT
5287 Programmer's Reference Manual. Such units are intended only
5288 for internal implementation purposes and should not be @code{with}'ed
5289 by user programs. The default is that such warnings are generated
5290 This warning can also be turned on using @option{-gnatwa}.
5291
5292 @item -gnatwI
5293 @emph{Disable warnings on implementation units.}
5294 @cindex @option{-gnatwI} (@command{gcc})
5295 This switch disables warnings for a @code{with} of an internal GNAT
5296 implementation unit.
5297
5298 @item -gnatw.i
5299 @emph{Activate warnings on overlapping actuals.}
5300 @cindex @option{-gnatw.i} (@command{gcc})
5301 This switch enables a warning on statically detectable overlapping actuals in
5302 a subprogram call, when one of the actuals is an in-out parameter, and the
5303 types of the actuals are not by-copy types. The warning is off by default,
5304 and is not included under -gnatwa.
5305
5306 @item -gnatw.I
5307 @emph{Disable warnings on overlapping actuals.}
5308 @cindex @option{-gnatw.I} (@command{gcc})
5309 This switch disables warnings on overlapping actuals in a call..
5310
5311 @item -gnatwj
5312 @emph{Activate warnings on obsolescent features (Annex J).}
5313 @cindex @option{-gnatwj} (@command{gcc})
5314 @cindex Features, obsolescent
5315 @cindex Obsolescent features
5316 If this warning option is activated, then warnings are generated for
5317 calls to subprograms marked with @code{pragma Obsolescent} and
5318 for use of features in Annex J of the Ada Reference Manual. In the
5319 case of Annex J, not all features are flagged. In particular use
5320 of the renamed packages (like @code{Text_IO}) and use of package
5321 @code{ASCII} are not flagged, since these are very common and
5322 would generate many annoying positive warnings. The default is that
5323 such warnings are not generated. This warning is also turned on by
5324 the use of @option{-gnatwa}.
5325
5326 In addition to the above cases, warnings are also generated for
5327 GNAT features that have been provided in past versions but which
5328 have been superseded (typically by features in the new Ada standard).
5329 For example, @code{pragma Ravenscar} will be flagged since its
5330 function is replaced by @code{pragma Profile(Ravenscar)}.
5331
5332 Note that this warning option functions differently from the
5333 restriction @code{No_Obsolescent_Features} in two respects.
5334 First, the restriction applies only to annex J features.
5335 Second, the restriction does flag uses of package @code{ASCII}.
5336
5337 @item -gnatwJ
5338 @emph{Suppress warnings on obsolescent features (Annex J).}
5339 @cindex @option{-gnatwJ} (@command{gcc})
5340 This switch disables warnings on use of obsolescent features.
5341
5342 @item -gnatwk
5343 @emph{Activate warnings on variables that could be constants.}
5344 @cindex @option{-gnatwk} (@command{gcc})
5345 This switch activates warnings for variables that are initialized but
5346 never modified, and then could be declared constants. The default is that
5347 such warnings are not given.
5348 This warning can also be turned on using @option{-gnatwa}.
5349
5350 @item -gnatwK
5351 @emph{Suppress warnings on variables that could be constants.}
5352 @cindex @option{-gnatwK} (@command{gcc})
5353 This switch disables warnings on variables that could be declared constants.
5354
5355 @item -gnatwl
5356 @emph{Activate warnings for elaboration pragmas.}
5357 @cindex @option{-gnatwl} (@command{gcc})
5358 @cindex Elaboration, warnings
5359 This switch activates warnings on missing
5360 @code{Elaborate_All} and @code{Elaborate} pragmas.
5361 See the section in this guide on elaboration checking for details on
5362 when such pragmas should be used. In dynamic elaboration mode, this switch
5363 generations warnings about the need to add elaboration pragmas. Note however,
5364 that if you blindly follow these warnings, and add @code{Elaborate_All}
5365 warnings wherever they are recommended, you basically end up with the
5366 equivalent of the static elaboration model, which may not be what you want for
5367 legacy code for which the static model does not work.
5368
5369 For the static model, the messages generated are labeled "info:" (for
5370 information messages). They are not warnings to add elaboration pragmas,
5371 merely informational messages showing what implicit elaboration pragmas
5372 have been added, for use in analyzing elaboration circularity problems.
5373
5374 Warnings are also generated if you
5375 are using the static mode of elaboration, and a @code{pragma Elaborate}
5376 is encountered. The default is that such warnings
5377 are not generated.
5378 This warning is not automatically turned on by the use of @option{-gnatwa}.
5379
5380 @item -gnatwL
5381 @emph{Suppress warnings for elaboration pragmas.}
5382 @cindex @option{-gnatwL} (@command{gcc})
5383 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5384 See the section in this guide on elaboration checking for details on
5385 when such pragmas should be used.
5386
5387 @item -gnatwm
5388 @emph{Activate warnings on modified but unreferenced variables.}
5389 @cindex @option{-gnatwm} (@command{gcc})
5390 This switch activates warnings for variables that are assigned (using
5391 an initialization value or with one or more assignment statements) but
5392 whose value is never read. The warning is suppressed for volatile
5393 variables and also for variables that are renamings of other variables
5394 or for which an address clause is given.
5395 This warning can also be turned on using @option{-gnatwa}.
5396 The default is that these warnings are not given.
5397
5398 @item -gnatwM
5399 @emph{Disable warnings on modified but unreferenced variables.}
5400 @cindex @option{-gnatwM} (@command{gcc})
5401 This switch disables warnings for variables that are assigned or
5402 initialized, but never read.
5403
5404 @item -gnatw.m
5405 @emph{Activate warnings on suspicious modulus values.}
5406 @cindex @option{-gnatw.m} (@command{gcc})
5407 This switch activates warnings for modulus values that seem suspicious.
5408 The cases caught are where the size is the same as the modulus (e.g.
5409 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5410 with no size clause. The guess in both cases is that 2**x was intended
5411 rather than x. The default is that these warnings are given.
5412
5413 @item -gnatw.M
5414 @emph{Disable warnings on suspicious modulus values.}
5415 @cindex @option{-gnatw.M} (@command{gcc})
5416 This switch disables warnings for suspicious modulus values.
5417
5418 @item -gnatwn
5419 @emph{Set normal warnings mode.}
5420 @cindex @option{-gnatwn} (@command{gcc})
5421 This switch sets normal warning mode, in which enabled warnings are
5422 issued and treated as warnings rather than errors. This is the default
5423 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5424 an explicit @option{-gnatws} or
5425 @option{-gnatwe}. It also cancels the effect of the
5426 implicit @option{-gnatwe} that is activated by the
5427 use of @option{-gnatg}.
5428
5429 @item -gnatwo
5430 @emph{Activate warnings on address clause overlays.}
5431 @cindex @option{-gnatwo} (@command{gcc})
5432 @cindex Address Clauses, warnings
5433 This switch activates warnings for possibly unintended initialization
5434 effects of defining address clauses that cause one variable to overlap
5435 another. The default is that such warnings are generated.
5436 This warning can also be turned on using @option{-gnatwa}.
5437
5438 @item -gnatwO
5439 @emph{Suppress warnings on address clause overlays.}
5440 @cindex @option{-gnatwO} (@command{gcc})
5441 This switch suppresses warnings on possibly unintended initialization
5442 effects of defining address clauses that cause one variable to overlap
5443 another.
5444
5445 @item -gnatw.o
5446 @emph{Activate warnings on modified but unreferenced out parameters.}
5447 @cindex @option{-gnatw.o} (@command{gcc})
5448 This switch activates warnings for variables that are modified by using
5449 them as actuals for a call to a procedure with an out mode formal, where
5450 the resulting assigned value is never read. It is applicable in the case
5451 where there is more than one out mode formal. If there is only one out
5452 mode formal, the warning is issued by default (controlled by -gnatwu).
5453 The warning is suppressed for volatile
5454 variables and also for variables that are renamings of other variables
5455 or for which an address clause is given.
5456 The default is that these warnings are not given. Note that this warning
5457 is not included in -gnatwa, it must be activated explicitly.
5458
5459 @item -gnatw.O
5460 @emph{Disable warnings on modified but unreferenced out parameters.}
5461 @cindex @option{-gnatw.O} (@command{gcc})
5462 This switch suppresses warnings for variables that are modified by using
5463 them as actuals for a call to a procedure with an out mode formal, where
5464 the resulting assigned value is never read.
5465
5466 @item -gnatwp
5467 @emph{Activate warnings on ineffective pragma Inlines.}
5468 @cindex @option{-gnatwp} (@command{gcc})
5469 @cindex Inlining, warnings
5470 This switch activates warnings for failure of front end inlining
5471 (activated by @option{-gnatN}) to inline a particular call. There are
5472 many reasons for not being able to inline a call, including most
5473 commonly that the call is too complex to inline. The default is
5474 that such warnings are not given.
5475 This warning can also be turned on using @option{-gnatwa}.
5476 Warnings on ineffective inlining by the gcc back-end can be activated
5477 separately, using the gcc switch -Winline.
5478
5479 @item -gnatwP
5480 @emph{Suppress warnings on ineffective pragma Inlines.}
5481 @cindex @option{-gnatwP} (@command{gcc})
5482 This switch suppresses warnings on ineffective pragma Inlines. If the
5483 inlining mechanism cannot inline a call, it will simply ignore the
5484 request silently.
5485
5486 @item -gnatw.p
5487 @emph{Activate warnings on parameter ordering.}
5488 @cindex @option{-gnatw.p} (@command{gcc})
5489 @cindex Parameter order, warnings
5490 This switch activates warnings for cases of suspicious parameter
5491 ordering when the list of arguments are all simple identifiers that
5492 match the names of the formals, but are in a different order. The
5493 warning is suppressed if any use of named parameter notation is used,
5494 so this is the appropriate way to suppress a false positive (and
5495 serves to emphasize that the "misordering" is deliberate). The
5496 default is
5497 that such warnings are not given.
5498 This warning can also be turned on using @option{-gnatwa}.
5499
5500 @item -gnatw.P
5501 @emph{Suppress warnings on parameter ordering.}
5502 @cindex @option{-gnatw.P} (@command{gcc})
5503 This switch suppresses warnings on cases of suspicious parameter
5504 ordering.
5505
5506 @item -gnatwq
5507 @emph{Activate warnings on questionable missing parentheses.}
5508 @cindex @option{-gnatwq} (@command{gcc})
5509 @cindex Parentheses, warnings
5510 This switch activates warnings for cases where parentheses are not used and
5511 the result is potential ambiguity from a readers point of view. For example
5512 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5513 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5514 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5515 follow the rule of always parenthesizing to make the association clear, and
5516 this warning switch warns if such parentheses are not present. The default
5517 is that these warnings are given.
5518 This warning can also be turned on using @option{-gnatwa}.
5519
5520 @item -gnatwQ
5521 @emph{Suppress warnings on questionable missing parentheses.}
5522 @cindex @option{-gnatwQ} (@command{gcc})
5523 This switch suppresses warnings for cases where the association is not
5524 clear and the use of parentheses is preferred.
5525
5526 @item -gnatwr
5527 @emph{Activate warnings on redundant constructs.}
5528 @cindex @option{-gnatwr} (@command{gcc})
5529 This switch activates warnings for redundant constructs. The following
5530 is the current list of constructs regarded as redundant:
5531
5532 @itemize @bullet
5533 @item
5534 Assignment of an item to itself.
5535 @item
5536 Type conversion that converts an expression to its own type.
5537 @item
5538 Use of the attribute @code{Base} where @code{typ'Base} is the same
5539 as @code{typ}.
5540 @item
5541 Use of pragma @code{Pack} when all components are placed by a record
5542 representation clause.
5543 @item
5544 Exception handler containing only a reraise statement (raise with no
5545 operand) which has no effect.
5546 @item
5547 Use of the operator abs on an operand that is known at compile time
5548 to be non-negative
5549 @item
5550 Comparison of boolean expressions to an explicit True value.
5551 @end itemize
5552
5553 This warning can also be turned on using @option{-gnatwa}.
5554 The default is that warnings for redundant constructs are not given.
5555
5556 @item -gnatwR
5557 @emph{Suppress warnings on redundant constructs.}
5558 @cindex @option{-gnatwR} (@command{gcc})
5559 This switch suppresses warnings for redundant constructs.
5560
5561 @item -gnatw.r
5562 @emph{Activate warnings for object renaming function.}
5563 @cindex @option{-gnatw.r} (@command{gcc})
5564 This switch activates warnings for an object renaming that renames a
5565 function call, which is equivalent to a constant declaration (as
5566 opposed to renaming the function itself).  The default is that these
5567 warnings are given.  This warning can also be turned on using
5568 @option{-gnatwa}.
5569
5570 @item -gnatw.R
5571 @emph{Suppress warnings for object renaming function.}
5572 @cindex @option{-gnatwT} (@command{gcc})
5573 This switch suppresses warnings for object renaming function.
5574
5575 @item -gnatws
5576 @emph{Suppress all warnings.}
5577 @cindex @option{-gnatws} (@command{gcc})
5578 This switch completely suppresses the
5579 output of all warning messages from the GNAT front end.
5580 Note that it does not suppress warnings from the @command{gcc} back end.
5581 To suppress these back end warnings as well, use the switch @option{-w}
5582 in addition to @option{-gnatws}. Also this switch has no effect on the
5583 handling of style check messages.
5584
5585 @item -gnatwt
5586 @emph{Activate warnings for tracking of deleted conditional code.}
5587 @cindex @option{-gnatwt} (@command{gcc})
5588 @cindex Deactivated code, warnings
5589 @cindex Deleted code, warnings
5590 This switch activates warnings for tracking of code in conditionals (IF and
5591 CASE statements) that is detected to be dead code which cannot be executed, and
5592 which is removed by the front end. This warning is off by default, and is not
5593 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5594 useful for detecting deactivated code in certified applications.
5595
5596 @item -gnatwT
5597 @emph{Suppress warnings for tracking of deleted conditional code.}
5598 @cindex @option{-gnatwT} (@command{gcc})
5599 This switch suppresses warnings for tracking of deleted conditional code.
5600
5601 @item -gnatwu
5602 @emph{Activate warnings on unused entities.}
5603 @cindex @option{-gnatwu} (@command{gcc})
5604 This switch activates warnings to be generated for entities that
5605 are declared but not referenced, and for units that are @code{with}'ed
5606 and not
5607 referenced. In the case of packages, a warning is also generated if
5608 no entities in the package are referenced. This means that if the package
5609 is referenced but the only references are in @code{use}
5610 clauses or @code{renames}
5611 declarations, a warning is still generated. A warning is also generated
5612 for a generic package that is @code{with}'ed but never instantiated.
5613 In the case where a package or subprogram body is compiled, and there
5614 is a @code{with} on the corresponding spec
5615 that is only referenced in the body,
5616 a warning is also generated, noting that the
5617 @code{with} can be moved to the body. The default is that
5618 such warnings are not generated.
5619 This switch also activates warnings on unreferenced formals
5620 (it includes the effect of @option{-gnatwf}).
5621 This warning can also be turned on using @option{-gnatwa}.
5622
5623 @item -gnatwU
5624 @emph{Suppress warnings on unused entities.}
5625 @cindex @option{-gnatwU} (@command{gcc})
5626 This switch suppresses warnings for unused entities and packages.
5627 It also turns off warnings on unreferenced formals (and thus includes
5628 the effect of @option{-gnatwF}).
5629
5630 @item -gnatwv
5631 @emph{Activate warnings on unassigned variables.}
5632 @cindex @option{-gnatwv} (@command{gcc})
5633 @cindex Unassigned variable warnings
5634 This switch activates warnings for access to variables which
5635 may not be properly initialized. The default is that
5636 such warnings are generated.
5637 This warning can also be turned on using @option{-gnatwa}.
5638
5639 @item -gnatwV
5640 @emph{Suppress warnings on unassigned variables.}
5641 @cindex @option{-gnatwV} (@command{gcc})
5642 This switch suppresses warnings for access to variables which
5643 may not be properly initialized.
5644 For variables of a composite type, the warning can also be suppressed in
5645 Ada 2005 by using a default initialization with a box. For example, if
5646 Table is an array of records whose components are only partially uninitialized,
5647 then the following code:
5648
5649 @smallexample @c ada
5650    Tab : Table := (others => <>);
5651 @end smallexample
5652
5653 will suppress warnings on subsequent statements that access components
5654 of variable Tab.
5655
5656 @item -gnatww
5657 @emph{Activate warnings on wrong low bound assumption.}
5658 @cindex @option{-gnatww} (@command{gcc})
5659 @cindex String indexing warnings
5660 This switch activates warnings for indexing an unconstrained string parameter
5661 with a literal or S'Length. This is a case where the code is assuming that the
5662 low bound is one, which is in general not true (for example when a slice is
5663 passed). The default is that such warnings are generated.
5664 This warning can also be turned on using @option{-gnatwa}.
5665
5666 @item -gnatwW
5667 @emph{Suppress warnings on wrong low bound assumption.}
5668 @cindex @option{-gnatwW} (@command{gcc})
5669 This switch suppresses warnings for indexing an unconstrained string parameter
5670 with a literal or S'Length. Note that this warning can also be suppressed
5671 in a particular case by adding an
5672 assertion that the lower bound is 1,
5673 as shown in the following example.
5674
5675 @smallexample @c ada
5676    procedure K (S : String) is
5677       pragma Assert (S'First = 1);
5678       @dots{}
5679 @end smallexample
5680
5681 @item -gnatw.w
5682 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5683 @cindex @option{-gnatw.w} (@command{gcc})
5684 @cindex Warnings Off control
5685 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5686 where either the pragma is entirely useless (because it suppresses no
5687 warnings), or it could be replaced by @code{pragma Unreferenced} or
5688 @code{pragma Unmodified}.The default is that these warnings are not given.
5689 Note that this warning is not included in -gnatwa, it must be
5690 activated explicitly.
5691
5692 @item -gnatw.W
5693 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5694 @cindex @option{-gnatw.W} (@command{gcc})
5695 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5696
5697 @item -gnatwx
5698 @emph{Activate warnings on Export/Import pragmas.}
5699 @cindex @option{-gnatwx} (@command{gcc})
5700 @cindex Export/Import pragma warnings
5701 This switch activates warnings on Export/Import pragmas when
5702 the compiler detects a possible conflict between the Ada and
5703 foreign language calling sequences. For example, the use of
5704 default parameters in a convention C procedure is dubious
5705 because the C compiler cannot supply the proper default, so
5706 a warning is issued. The default is that such warnings are
5707 generated.
5708 This warning can also be turned on using @option{-gnatwa}.
5709
5710 @item -gnatwX
5711 @emph{Suppress warnings on Export/Import pragmas.}
5712 @cindex @option{-gnatwX} (@command{gcc})
5713 This switch suppresses warnings on Export/Import pragmas.
5714 The sense of this is that you are telling the compiler that
5715 you know what you are doing in writing the pragma, and it
5716 should not complain at you.
5717
5718 @item -gnatw.x
5719 @emph{Activate warnings for No_Exception_Propagation mode.}
5720 @cindex @option{-gnatwm} (@command{gcc})
5721 This switch activates warnings for exception usage when pragma Restrictions
5722 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5723 explicit exception raises which are not covered by a local handler, and for
5724 exception handlers which do not cover a local raise. The default is that these
5725 warnings are not given.
5726
5727 @item -gnatw.X
5728 @emph{Disable warnings for No_Exception_Propagation mode.}
5729 This switch disables warnings for exception usage when pragma Restrictions
5730 (No_Exception_Propagation) is in effect.
5731
5732 @item -gnatwy
5733 @emph{Activate warnings for Ada 2005 compatibility issues.}
5734 @cindex @option{-gnatwy} (@command{gcc})
5735 @cindex Ada 2005 compatibility issues warnings
5736 For the most part Ada 2005 is upwards compatible with Ada 95,
5737 but there are some exceptions (for example the fact that
5738 @code{interface} is now a reserved word in Ada 2005). This
5739 switch activates several warnings to help in identifying
5740 and correcting such incompatibilities. The default is that
5741 these warnings are generated. Note that at one point Ada 2005
5742 was called Ada 0Y, hence the choice of character.
5743 This warning can also be turned on using @option{-gnatwa}.
5744
5745 @item -gnatwY
5746 @emph{Disable warnings for Ada 2005 compatibility issues.}
5747 @cindex @option{-gnatwY} (@command{gcc})
5748 @cindex Ada 2005 compatibility issues warnings
5749 This switch suppresses several warnings intended to help in identifying
5750 incompatibilities between Ada 95 and Ada 2005.
5751
5752 @item -gnatwz
5753 @emph{Activate warnings on unchecked conversions.}
5754 @cindex @option{-gnatwz} (@command{gcc})
5755 @cindex Unchecked_Conversion warnings
5756 This switch activates warnings for unchecked conversions
5757 where the types are known at compile time to have different
5758 sizes. The default
5759 is that such warnings are generated. Warnings are also
5760 generated for subprogram pointers with different conventions,
5761 and, on VMS only, for data pointers with different conventions.
5762 This warning can also be turned on using @option{-gnatwa}.
5763
5764 @item -gnatwZ
5765 @emph{Suppress warnings on unchecked conversions.}
5766 @cindex @option{-gnatwZ} (@command{gcc})
5767 This switch suppresses warnings for unchecked conversions
5768 where the types are known at compile time to have different
5769 sizes or conventions.
5770
5771 @item ^-Wunused^WARNINGS=UNUSED^
5772 @cindex @option{-Wunused}
5773 The warnings controlled by the @option{-gnatw} switch are generated by
5774 the front end of the compiler. The @option{GCC} back end can provide
5775 additional warnings and they are controlled by the @option{-W} switch.
5776 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5777 warnings for entities that are declared but not referenced.
5778
5779 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5780 @cindex @option{-Wuninitialized}
5781 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5782 the back end warning for uninitialized variables. This switch must be
5783 used in conjunction with an optimization level greater than zero.
5784
5785 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5786 @cindex @option{-Wall}
5787 This switch enables all the above warnings from the @option{GCC} back end.
5788 The code generator detects a number of warning situations that are missed
5789 by the @option{GNAT} front end, and this switch can be used to activate them.
5790 The use of this switch also sets the default front end warning mode to
5791 @option{-gnatwa}, that is, most front end warnings activated as well.
5792
5793 @item ^-w^/NO_BACK_END_WARNINGS^
5794 @cindex @option{-w}
5795 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5796 The use of this switch also sets the default front end warning mode to
5797 @option{-gnatws}, that is, front end warnings suppressed as well.
5798
5799 @end table
5800
5801 @noindent
5802 @ifclear vms
5803 A string of warning parameters can be used in the same parameter. For example:
5804
5805 @smallexample
5806 -gnatwaLe
5807 @end smallexample
5808
5809 @noindent
5810 will turn on all optional warnings except for elaboration pragma warnings,
5811 and also specify that warnings should be treated as errors.
5812 @end ifclear
5813 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5814
5815 @table @option
5816 @c !sort!
5817 @item -gnatwC
5818 @item -gnatwD
5819 @item -gnatwF
5820 @item -gnatwg
5821 @item -gnatwH
5822 @item -gnatwi
5823 @item -gnatwJ
5824 @item -gnatwK
5825 @item -gnatwL
5826 @item -gnatwM
5827 @item -gnatwn
5828 @item -gnatwo
5829 @item -gnatwP
5830 @item -gnatwR
5831 @item -gnatwU
5832 @item -gnatwv
5833 @item -gnatwz
5834 @item -gnatwx
5835
5836 @end table
5837
5838 @node Debugging and Assertion Control
5839 @subsection Debugging and Assertion Control
5840
5841 @table @option
5842 @item -gnata
5843 @cindex @option{-gnata} (@command{gcc})
5844 @findex Assert
5845 @findex Debug
5846 @cindex Assertions
5847
5848 @noindent
5849 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5850 are ignored. This switch, where @samp{a} stands for assert, causes
5851 @code{Assert} and @code{Debug} pragmas to be activated.
5852
5853 The pragmas have the form:
5854
5855 @smallexample
5856 @cartouche
5857    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5858                       @var{static-string-expression}@r{]})
5859    @b{pragma} Debug (@var{procedure call})
5860 @end cartouche
5861 @end smallexample
5862
5863 @noindent
5864 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5865 If the result is @code{True}, the pragma has no effect (other than
5866 possible side effects from evaluating the expression). If the result is
5867 @code{False}, the exception @code{Assert_Failure} declared in the package
5868 @code{System.Assertions} is
5869 raised (passing @var{static-string-expression}, if present, as the
5870 message associated with the exception). If no string expression is
5871 given the default is a string giving the file name and line number
5872 of the pragma.
5873
5874 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5875 @code{pragma Debug} may appear within a declaration sequence, allowing
5876 debugging procedures to be called between declarations.
5877
5878 @ifset vms
5879 @item /DEBUG@r{[}=debug-level@r{]}
5880 @itemx  /NODEBUG
5881 Specifies how much debugging information is to be included in
5882 the resulting object file where 'debug-level' is one of the following:
5883 @table @code
5884 @item   TRACEBACK
5885 Include both debugger symbol records and traceback
5886 the object file.
5887 This is the default setting.
5888 @item   ALL
5889 Include both debugger symbol records and traceback in
5890 object file.
5891 @item   NONE
5892 Excludes both debugger symbol records and traceback
5893 the object file. Same as /NODEBUG.
5894 @item   SYMBOLS
5895 Includes only debugger symbol records in the object
5896 file. Note that this doesn't include traceback information.
5897 @end table
5898 @end ifset
5899 @end table
5900
5901 @node Validity Checking
5902 @subsection Validity Checking
5903 @findex Validity Checking
5904
5905 @noindent
5906 The Ada Reference Manual defines the concept of invalid values (see
5907 RM 13.9.1). The primary source of invalid values is uninitialized
5908 variables. A scalar variable that is left uninitialized may contain
5909 an invalid value; the concept of invalid does not apply to access or
5910 composite types.
5911
5912 It is an error to read an invalid value, but the RM does not require
5913 run-time checks to detect such errors, except for some minimal
5914 checking to prevent erroneous execution (i.e. unpredictable
5915 behavior). This corresponds to the @option{-gnatVd} switch below,
5916 which is the default. For example, by default, if the expression of a
5917 case statement is invalid, it will raise Constraint_Error rather than
5918 causing a wild jump, and if an array index on the left-hand side of an
5919 assignment is invalid, it will raise Constraint_Error rather than
5920 overwriting an arbitrary memory location.
5921
5922 The @option{-gnatVa} may be used to enable additional validity checks,
5923 which are not required by the RM. These checks are often very
5924 expensive (which is why the RM does not require them). These checks
5925 are useful in tracking down uninitialized variables, but they are
5926 not usually recommended for production builds.
5927
5928 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5929 control; you can enable whichever validity checks you desire. However,
5930 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5931 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5932 sufficient for non-debugging use.
5933
5934 The @option{-gnatB} switch tells the compiler to assume that all
5935 values are valid (that is, within their declared subtype range)
5936 except in the context of a use of the Valid attribute. This means
5937 the compiler can generate more efficient code, since the range
5938 of values is better known at compile time. However, an uninitialized
5939 variable can cause wild jumps and memory corruption in this mode.
5940
5941 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5942 checking mode as described below.
5943 @ifclear vms
5944 The @code{x} argument is a string of letters that
5945 indicate validity checks that are performed or not performed in addition
5946 to the default checks required by Ada as described above.
5947 @end ifclear
5948 @ifset vms
5949 The options allowed for this qualifier
5950 indicate validity checks that are performed or not performed in addition
5951 to the default checks required by Ada as described above.
5952 @end ifset
5953
5954 @table @option
5955 @c !sort!
5956 @item -gnatVa
5957 @emph{All validity checks.}
5958 @cindex @option{-gnatVa} (@command{gcc})
5959 All validity checks are turned on.
5960 @ifclear vms
5961 That is, @option{-gnatVa} is
5962 equivalent to @option{gnatVcdfimorst}.
5963 @end ifclear
5964
5965 @item -gnatVc
5966 @emph{Validity checks for copies.}
5967 @cindex @option{-gnatVc} (@command{gcc})
5968 The right hand side of assignments, and the initializing values of
5969 object declarations are validity checked.
5970
5971 @item -gnatVd
5972 @emph{Default (RM) validity checks.}
5973 @cindex @option{-gnatVd} (@command{gcc})
5974 Some validity checks are done by default following normal Ada semantics
5975 (RM 13.9.1 (9-11)).
5976 A check is done in case statements that the expression is within the range
5977 of the subtype. If it is not, Constraint_Error is raised.
5978 For assignments to array components, a check is done that the expression used
5979 as index is within the range. If it is not, Constraint_Error is raised.
5980 Both these validity checks may be turned off using switch @option{-gnatVD}.
5981 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5982 switch @option{-gnatVd} will leave the checks turned on.
5983 Switch @option{-gnatVD} should be used only if you are sure that all such
5984 expressions have valid values. If you use this switch and invalid values
5985 are present, then the program is erroneous, and wild jumps or memory
5986 overwriting may occur.
5987
5988 @item -gnatVe
5989 @emph{Validity checks for elementary components.}
5990 @cindex @option{-gnatVe} (@command{gcc})
5991 In the absence of this switch, assignments to record or array components are
5992 not validity checked, even if validity checks for assignments generally
5993 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5994 require valid data, but assignment of individual components does. So for
5995 example, there is a difference between copying the elements of an array with a
5996 slice assignment, compared to assigning element by element in a loop. This
5997 switch allows you to turn off validity checking for components, even when they
5998 are assigned component by component.
5999
6000 @item -gnatVf
6001 @emph{Validity checks for floating-point values.}
6002 @cindex @option{-gnatVf} (@command{gcc})
6003 In the absence of this switch, validity checking occurs only for discrete
6004 values. If @option{-gnatVf} is specified, then validity checking also applies
6005 for floating-point values, and NaNs and infinities are considered invalid,
6006 as well as out of range values for constrained types. Note that this means
6007 that standard IEEE infinity mode is not allowed. The exact contexts
6008 in which floating-point values are checked depends on the setting of other
6009 options. For example,
6010 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6011 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6012 (the order does not matter) specifies that floating-point parameters of mode
6013 @code{in} should be validity checked.
6014
6015 @item -gnatVi
6016 @emph{Validity checks for @code{in} mode parameters}
6017 @cindex @option{-gnatVi} (@command{gcc})
6018 Arguments for parameters of mode @code{in} are validity checked in function
6019 and procedure calls at the point of call.
6020
6021 @item -gnatVm
6022 @emph{Validity checks for @code{in out} mode parameters.}
6023 @cindex @option{-gnatVm} (@command{gcc})
6024 Arguments for parameters of mode @code{in out} are validity checked in
6025 procedure calls at the point of call. The @code{'m'} here stands for
6026 modify, since this concerns parameters that can be modified by the call.
6027 Note that there is no specific option to test @code{out} parameters,
6028 but any reference within the subprogram will be tested in the usual
6029 manner, and if an invalid value is copied back, any reference to it
6030 will be subject to validity checking.
6031
6032 @item -gnatVn
6033 @emph{No validity checks.}
6034 @cindex @option{-gnatVn} (@command{gcc})
6035 This switch turns off all validity checking, including the default checking
6036 for case statements and left hand side subscripts. Note that the use of
6037 the switch @option{-gnatp} suppresses all run-time checks, including
6038 validity checks, and thus implies @option{-gnatVn}. When this switch
6039 is used, it cancels any other @option{-gnatV} previously issued.
6040
6041 @item -gnatVo
6042 @emph{Validity checks for operator and attribute operands.}
6043 @cindex @option{-gnatVo} (@command{gcc})
6044 Arguments for predefined operators and attributes are validity checked.
6045 This includes all operators in package @code{Standard},
6046 the shift operators defined as intrinsic in package @code{Interfaces}
6047 and operands for attributes such as @code{Pos}. Checks are also made
6048 on individual component values for composite comparisons, and on the
6049 expressions in type conversions and qualified expressions. Checks are
6050 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6051
6052 @item -gnatVp
6053 @emph{Validity checks for parameters.}
6054 @cindex @option{-gnatVp} (@command{gcc})
6055 This controls the treatment of parameters within a subprogram (as opposed
6056 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6057 of parameters on a call. If either of these call options is used, then
6058 normally an assumption is made within a subprogram that the input arguments
6059 have been validity checking at the point of call, and do not need checking
6060 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6061 is not made, and parameters are not assumed to be valid, so their validity
6062 will be checked (or rechecked) within the subprogram.
6063
6064 @item -gnatVr
6065 @emph{Validity checks for function returns.}
6066 @cindex @option{-gnatVr} (@command{gcc})
6067 The expression in @code{return} statements in functions is validity
6068 checked.
6069
6070 @item -gnatVs
6071 @emph{Validity checks for subscripts.}
6072 @cindex @option{-gnatVs} (@command{gcc})
6073 All subscripts expressions are checked for validity, whether they appear
6074 on the right side or left side (in default mode only left side subscripts
6075 are validity checked).
6076
6077 @item -gnatVt
6078 @emph{Validity checks for tests.}
6079 @cindex @option{-gnatVt} (@command{gcc})
6080 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6081 statements are checked, as well as guard expressions in entry calls.
6082
6083 @end table
6084
6085 @noindent
6086 The @option{-gnatV} switch may be followed by
6087 ^a string of letters^a list of options^
6088 to turn on a series of validity checking options.
6089 For example,
6090 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6091 specifies that in addition to the default validity checking, copies and
6092 function return expressions are to be validity checked.
6093 In order to make it easier
6094 to specify the desired combination of effects,
6095 @ifclear vms
6096 the upper case letters @code{CDFIMORST} may
6097 be used to turn off the corresponding lower case option.
6098 @end ifclear
6099 @ifset vms
6100 the prefix @code{NO} on an option turns off the corresponding validity
6101 checking:
6102 @itemize @bullet
6103 @item @code{NOCOPIES}
6104 @item @code{NODEFAULT}
6105 @item @code{NOFLOATS}
6106 @item @code{NOIN_PARAMS}
6107 @item @code{NOMOD_PARAMS}
6108 @item @code{NOOPERANDS}
6109 @item @code{NORETURNS}
6110 @item @code{NOSUBSCRIPTS}
6111 @item @code{NOTESTS}
6112 @end itemize
6113 @end ifset
6114 Thus
6115 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6116 turns on all validity checking options except for
6117 checking of @code{@b{in out}} procedure arguments.
6118
6119 The specification of additional validity checking generates extra code (and
6120 in the case of @option{-gnatVa} the code expansion can be substantial).
6121 However, these additional checks can be very useful in detecting
6122 uninitialized variables, incorrect use of unchecked conversion, and other
6123 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6124 is useful in conjunction with the extra validity checking, since this
6125 ensures that wherever possible uninitialized variables have invalid values.
6126
6127 See also the pragma @code{Validity_Checks} which allows modification of
6128 the validity checking mode at the program source level, and also allows for
6129 temporary disabling of validity checks.
6130
6131 @node Style Checking
6132 @subsection Style Checking
6133 @findex Style checking
6134
6135 @noindent
6136 The @option{-gnaty^x^(option,option,@dots{})^} switch
6137 @cindex @option{-gnaty} (@command{gcc})
6138 causes the compiler to
6139 enforce specified style rules. A limited set of style rules has been used
6140 in writing the GNAT sources themselves. This switch allows user programs
6141 to activate all or some of these checks. If the source program fails a
6142 specified style check, an appropriate message is given, preceded by
6143 the character sequence ``(style)''. This message does not prevent
6144 successful compilation (unless the @option{-gnatwe} switch is used).
6145
6146 @ifset vms
6147 @code{(option,option,@dots{})} is a sequence of keywords
6148 @end ifset
6149 @ifclear vms
6150 The string @var{x} is a sequence of letters or digits
6151 @end ifclear
6152 indicating the particular style
6153 checks to be performed. The following checks are defined:
6154
6155 @table @option
6156 @c !sort!
6157 @item 0-9
6158 @emph{Specify indentation level.}
6159 If a digit from 1-9 appears
6160 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6161 then proper indentation is checked, with the digit indicating the
6162 indentation level required. A value of zero turns off this style check.
6163 The general style of required indentation is as specified by
6164 the examples in the Ada Reference Manual. Full line comments must be
6165 aligned with the @code{--} starting on a column that is a multiple of
6166 the alignment level, or they may be aligned the same way as the following
6167 non-blank line (this is useful when full line comments appear in the middle
6168 of a statement.
6169
6170 @item ^a^ATTRIBUTE^
6171 @emph{Check attribute casing.}
6172 Attribute names, including the case of keywords such as @code{digits}
6173 used as attributes names, must be written in mixed case, that is, the
6174 initial letter and any letter following an underscore must be uppercase.
6175 All other letters must be lowercase.
6176
6177 @item ^A^ARRAY_INDEXES^
6178 @emph{Use of array index numbers in array attributes.}
6179 When using the array attributes First, Last, Range,
6180 or Length, the index number must be omitted for one-dimensional arrays
6181 and is required for multi-dimensional arrays.
6182
6183 @item ^b^BLANKS^
6184 @emph{Blanks not allowed at statement end.}
6185 Trailing blanks are not allowed at the end of statements. The purpose of this
6186 rule, together with h (no horizontal tabs), is to enforce a canonical format
6187 for the use of blanks to separate source tokens.
6188
6189 @item ^B^BOOLEAN_OPERATORS^
6190 @emph{Check Boolean operators.}
6191 The use of AND/OR operators is not permitted except in the cases of modular
6192 operands, array operands, and simple stand-alone boolean variables or
6193 boolean constants. In all other cases AND THEN/OR ELSE are required.
6194
6195 @item ^c^COMMENTS^
6196 @emph{Check comments.}
6197 Comments must meet the following set of rules:
6198
6199 @itemize @bullet
6200
6201 @item
6202 The ``@code{--}'' that starts the column must either start in column one,
6203 or else at least one blank must precede this sequence.
6204
6205 @item
6206 Comments that follow other tokens on a line must have at least one blank
6207 following the ``@code{--}'' at the start of the comment.
6208
6209 @item
6210 Full line comments must have two blanks following the ``@code{--}'' that
6211 starts the comment, with the following exceptions.
6212
6213 @item
6214 A line consisting only of the ``@code{--}'' characters, possibly preceded
6215 by blanks is permitted.
6216
6217 @item
6218 A comment starting with ``@code{--x}'' where @code{x} is a special character
6219 is permitted.
6220 This allows proper processing of the output generated by specialized tools
6221 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6222 annotation
6223 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6224 special character is defined as being in one of the ASCII ranges
6225 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6226 Note that this usage is not permitted
6227 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6228
6229 @item
6230 A line consisting entirely of minus signs, possibly preceded by blanks, is
6231 permitted. This allows the construction of box comments where lines of minus
6232 signs are used to form the top and bottom of the box.
6233
6234 @item
6235 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6236 least one blank follows the initial ``@code{--}''. Together with the preceding
6237 rule, this allows the construction of box comments, as shown in the following
6238 example:
6239 @smallexample
6240 ---------------------------
6241 -- This is a box comment --
6242 -- with two text lines.  --
6243 ---------------------------
6244 @end smallexample
6245 @end itemize
6246
6247 @item ^d^DOS_LINE_ENDINGS^
6248 @emph{Check no DOS line terminators present.}
6249 All lines must be terminated by a single ASCII.LF
6250 character (in particular the DOS line terminator sequence CR/LF is not
6251 allowed).
6252
6253 @item ^e^END^
6254 @emph{Check end/exit labels.}
6255 Optional labels on @code{end} statements ending subprograms and on
6256 @code{exit} statements exiting named loops, are required to be present.
6257
6258 @item ^f^VTABS^
6259 @emph{No form feeds or vertical tabs.}
6260 Neither form feeds nor vertical tab characters are permitted
6261 in the source text.
6262
6263 @item ^g^GNAT^
6264 @emph{GNAT style mode}
6265 The set of style check switches is set to match that used by the GNAT sources.
6266 This may be useful when developing code that is eventually intended to be
6267 incorporated into GNAT. For further details, see GNAT sources.
6268
6269 @item ^h^HTABS^
6270 @emph{No horizontal tabs.}
6271 Horizontal tab characters are not permitted in the source text.
6272 Together with the b (no blanks at end of line) check, this
6273 enforces a canonical form for the use of blanks to separate
6274 source tokens.
6275
6276 @item ^i^IF_THEN^
6277 @emph{Check if-then layout.}
6278 The keyword @code{then} must appear either on the same
6279 line as corresponding @code{if}, or on a line on its own, lined
6280 up under the @code{if} with at least one non-blank line in between
6281 containing all or part of the condition to be tested.
6282
6283 @item ^I^IN_MODE^
6284 @emph{check mode IN keywords}
6285 Mode @code{in} (the default mode) is not
6286 allowed to be given explicitly. @code{in out} is fine,
6287 but not @code{in} on its own.
6288
6289 @item ^k^KEYWORD^
6290 @emph{Check keyword casing.}
6291 All keywords must be in lower case (with the exception of keywords
6292 such as @code{digits} used as attribute names to which this check
6293 does not apply).
6294
6295 @item ^l^LAYOUT^
6296 @emph{Check layout.}
6297 Layout of statement and declaration constructs must follow the
6298 recommendations in the Ada Reference Manual, as indicated by the
6299 form of the syntax rules. For example an @code{else} keyword must
6300 be lined up with the corresponding @code{if} keyword.
6301
6302 There are two respects in which the style rule enforced by this check
6303 option are more liberal than those in the Ada Reference Manual. First
6304 in the case of record declarations, it is permissible to put the
6305 @code{record} keyword on the same line as the @code{type} keyword, and
6306 then the @code{end} in @code{end record} must line up under @code{type}.
6307 This is also permitted when the type declaration is split on two lines.
6308 For example, any of the following three layouts is acceptable:
6309
6310 @smallexample @c ada
6311 @cartouche
6312 type q is record
6313    a : integer;
6314    b : integer;
6315 end record;
6316
6317 type q is
6318    record
6319       a : integer;
6320       b : integer;
6321    end record;
6322
6323 type q is
6324    record
6325       a : integer;
6326       b : integer;
6327 end record;
6328
6329 @end cartouche
6330 @end smallexample
6331
6332 @noindent
6333 Second, in the case of a block statement, a permitted alternative
6334 is to put the block label on the same line as the @code{declare} or
6335 @code{begin} keyword, and then line the @code{end} keyword up under
6336 the block label. For example both the following are permitted:
6337
6338 @smallexample @c ada
6339 @cartouche
6340 Block : declare
6341    A : Integer := 3;
6342 begin
6343    Proc (A, A);
6344 end Block;
6345
6346 Block :
6347    declare
6348       A : Integer := 3;
6349    begin
6350       Proc (A, A);
6351    end Block;
6352 @end cartouche
6353 @end smallexample
6354
6355 @noindent
6356 The same alternative format is allowed for loops. For example, both of
6357 the following are permitted:
6358
6359 @smallexample @c ada
6360 @cartouche
6361 Clear : while J < 10 loop
6362    A (J) := 0;
6363 end loop Clear;
6364
6365 Clear :
6366    while J < 10 loop
6367       A (J) := 0;
6368    end loop Clear;
6369 @end cartouche
6370 @end smallexample
6371
6372 @item ^Lnnn^MAX_NESTING=nnn^
6373 @emph{Set maximum nesting level}
6374 The maximum level of nesting of constructs (including subprograms, loops,
6375 blocks, packages, and conditionals) may not exceed the given value
6376 @option{nnn}. A value of zero disconnects this style check.
6377
6378 @item ^m^LINE_LENGTH^
6379 @emph{Check maximum line length.}
6380 The length of source lines must not exceed 79 characters, including
6381 any trailing blanks. The value of 79 allows convenient display on an
6382 80 character wide device or window, allowing for possible special
6383 treatment of 80 character lines. Note that this count is of
6384 characters in the source text. This means that a tab character counts
6385 as one character in this count but a wide character sequence counts as
6386 a single character (however many bytes are needed in the encoding).
6387
6388 @item ^Mnnn^MAX_LENGTH=nnn^
6389 @emph{Set maximum line length.}
6390 The length of lines must not exceed the
6391 given value @option{nnn}. The maximum value that can be specified is 32767.
6392
6393 @item ^n^STANDARD_CASING^
6394 @emph{Check casing of entities in Standard.}
6395 Any identifier from Standard must be cased
6396 to match the presentation in the Ada Reference Manual (for example,
6397 @code{Integer} and @code{ASCII.NUL}).
6398
6399 @item ^N^NONE^
6400 @emph{Turn off all style checks}
6401 All style check options are turned off.
6402
6403 @item ^o^ORDERED_SUBPROGRAMS^
6404 @emph{Check order of subprogram bodies.}
6405 All subprogram bodies in a given scope
6406 (e.g.@: a package body) must be in alphabetical order. The ordering
6407 rule uses normal Ada rules for comparing strings, ignoring casing
6408 of letters, except that if there is a trailing numeric suffix, then
6409 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6410 before Junk10).
6411
6412 @item ^O^OVERRIDING_INDICATORS^
6413 @emph{Check that overriding subprograms are explicitly marked as such.}
6414 The declaration of a primitive operation of a type extension that overrides
6415 an inherited operation must carry an overriding indicator.
6416
6417 @item ^p^PRAGMA^
6418 @emph{Check pragma casing.}
6419 Pragma names must be written in mixed case, that is, the
6420 initial letter and any letter following an underscore must be uppercase.
6421 All other letters must be lowercase.
6422
6423 @item ^r^REFERENCES^
6424 @emph{Check references.}
6425 All identifier references must be cased in the same way as the
6426 corresponding declaration. No specific casing style is imposed on
6427 identifiers. The only requirement is for consistency of references
6428 with declarations.
6429
6430 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6431 @emph{Check no statements after THEN/ELSE.}
6432 No statements are allowed
6433 on the same line as a THEN or ELSE keyword following the
6434 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6435 and a special exception allows a pragma to appear after ELSE.
6436
6437 @item ^s^SPECS^
6438 @emph{Check separate specs.}
6439 Separate declarations (``specs'') are required for subprograms (a
6440 body is not allowed to serve as its own declaration). The only
6441 exception is that parameterless library level procedures are
6442 not required to have a separate declaration. This exception covers
6443 the most frequent form of main program procedures.
6444
6445 @item ^t^TOKEN^
6446 @emph{Check token spacing.}
6447 The following token spacing rules are enforced:
6448
6449 @itemize @bullet
6450
6451 @item
6452 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6453
6454 @item
6455 The token @code{=>} must be surrounded by spaces.
6456
6457 @item
6458 The token @code{<>} must be preceded by a space or a left parenthesis.
6459
6460 @item
6461 Binary operators other than @code{**} must be surrounded by spaces.
6462 There is no restriction on the layout of the @code{**} binary operator.
6463
6464 @item
6465 Colon must be surrounded by spaces.
6466
6467 @item
6468 Colon-equal (assignment, initialization) must be surrounded by spaces.
6469
6470 @item
6471 Comma must be the first non-blank character on the line, or be
6472 immediately preceded by a non-blank character, and must be followed
6473 by a space.
6474
6475 @item
6476 If the token preceding a left parenthesis ends with a letter or digit, then
6477 a space must separate the two tokens.
6478
6479 @item
6480 if the token following a right parenthesis starts with a letter or digit, then
6481 a space must separate the two tokens.
6482
6483 @item
6484 A right parenthesis must either be the first non-blank character on
6485 a line, or it must be preceded by a non-blank character.
6486
6487 @item
6488 A semicolon must not be preceded by a space, and must not be followed by
6489 a non-blank character.
6490
6491 @item
6492 A unary plus or minus may not be followed by a space.
6493
6494 @item
6495 A vertical bar must be surrounded by spaces.
6496 @end itemize
6497
6498 @item ^u^UNNECESSARY_BLANK_LINES^
6499 @emph{Check unnecessary blank lines.}
6500 Unnecessary blank lines are not allowed. A blank line is considered
6501 unnecessary if it appears at the end of the file, or if more than
6502 one blank line occurs in sequence.
6503
6504 @item ^x^XTRA_PARENS^
6505 @emph{Check extra parentheses.}
6506 Unnecessary extra level of parentheses (C-style) are not allowed
6507 around conditions in @code{if} statements, @code{while} statements and
6508 @code{exit} statements.
6509
6510 @item ^y^ALL_BUILTIN^
6511 @emph{Set all standard style check options}
6512 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6513 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6514 @option{-gnatyS}, @option{-gnatyLnnn},
6515 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6516
6517 @ifclear vms
6518 @item -
6519 @emph{Remove style check options}
6520 This causes any subsequent options in the string to act as canceling the
6521 corresponding style check option. To cancel maximum nesting level control,
6522 use @option{L} parameter witout any integer value after that, because any
6523 digit following @option{-} in the parameter string of the @option{-gnaty}
6524 option will be threated as canceling indentation check. The same is true
6525 for @option{M} parameter. @option{y} and @option{N} parameters are not
6526 allowed after @option{-}.
6527
6528 @item +
6529 This causes any subsequent options in the string to enable the corresponding
6530 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6531 if any.
6532 @end ifclear
6533
6534 @ifset vms
6535 @item NOxxx
6536 @emph{Removing style check options}
6537 If the name of a style check is preceded by @option{NO} then the corresponding
6538 style check is turned off. For example @option{NOCOMMENTS} turns off style
6539 checking for comments.
6540 @end ifset
6541 @end table
6542
6543 @noindent
6544 In the above rules, appearing in column one is always permitted, that is,
6545 counts as meeting either a requirement for a required preceding space,
6546 or as meeting a requirement for no preceding space.
6547
6548 Appearing at the end of a line is also always permitted, that is, counts
6549 as meeting either a requirement for a following space, or as meeting
6550 a requirement for no following space.
6551
6552 @noindent
6553 If any of these style rules is violated, a message is generated giving
6554 details on the violation. The initial characters of such messages are
6555 always ``@code{(style)}''. Note that these messages are treated as warning
6556 messages, so they normally do not prevent the generation of an object
6557 file. The @option{-gnatwe} switch can be used to treat warning messages,
6558 including style messages, as fatal errors.
6559
6560 The switch
6561 @ifclear vms
6562 @option{-gnaty} on its own (that is not
6563 followed by any letters or digits), then the effect is equivalent
6564 to the use of @option{-gnatyy}, as described above, that is all
6565 built-in standard style check options are enabled.
6566
6567 @end ifclear
6568 @ifset vms
6569 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6570 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6571 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6572 @end ifset
6573
6574 The switch
6575 @ifclear vms
6576 @option{-gnatyN}
6577 @end ifclear
6578 @ifset vms
6579 /STYLE_CHECKS=NONE
6580 @end ifset
6581 clears any previously set style checks.
6582
6583 @node Run-Time Checks
6584 @subsection Run-Time Checks
6585 @cindex Division by zero
6586 @cindex Access before elaboration
6587 @cindex Checks, division by zero
6588 @cindex Checks, access before elaboration
6589 @cindex Checks, stack overflow checking
6590
6591 @noindent
6592 By default, the following checks are suppressed: integer overflow
6593 checks, stack overflow checks, and checks for access before
6594 elaboration on subprogram calls. All other checks, including range
6595 checks and array bounds checks, are turned on by default. The
6596 following @command{gcc} switches refine this default behavior.
6597
6598 @table @option
6599 @c !sort!
6600 @item -gnatp
6601 @cindex @option{-gnatp} (@command{gcc})
6602 @cindex Suppressing checks
6603 @cindex Checks, suppressing
6604 @findex Suppress
6605 This switch causes the unit to be compiled
6606 as though @code{pragma Suppress (All_checks)}
6607 had been present in the source. Validity checks are also eliminated (in
6608 other words @option{-gnatp} also implies @option{-gnatVn}.
6609 Use this switch to improve the performance
6610 of the code at the expense of safety in the presence of invalid data or
6611 program bugs.
6612
6613 Note that when checks are suppressed, the compiler is allowed, but not
6614 required, to omit the checking code. If the run-time cost of the
6615 checking code is zero or near-zero, the compiler will generate it even
6616 if checks are suppressed. In particular, if the compiler can prove
6617 that a certain check will necessarily fail, it will generate code to
6618 do an unconditional ``raise'', even if checks are suppressed. The
6619 compiler warns in this case. Another case in which checks may not be
6620 eliminated is when they are embedded in certain run time routines such
6621 as math library routines.
6622
6623 Of course, run-time checks are omitted whenever the compiler can prove
6624 that they will not fail, whether or not checks are suppressed.
6625
6626 Note that if you suppress a check that would have failed, program
6627 execution is erroneous, which means the behavior is totally
6628 unpredictable. The program might crash, or print wrong answers, or
6629 do anything else. It might even do exactly what you wanted it to do
6630 (and then it might start failing mysteriously next week or next
6631 year). The compiler will generate code based on the assumption that
6632 the condition being checked is true, which can result in disaster if
6633 that assumption is wrong.
6634
6635 The @option{-gnatp} switch has no effect if a subsequent
6636 @option{-gnat-p} switch appears.
6637
6638 @item -gnat-p
6639 @cindex @option{-gnat-p} (@command{gcc})
6640 @cindex Suppressing checks
6641 @cindex Checks, suppressing
6642 @findex Suppress
6643 This switch cancels the effect of a previous @option{gnatp} switch.
6644
6645 @item -gnato
6646 @cindex @option{-gnato} (@command{gcc})
6647 @cindex Overflow checks
6648 @cindex Check, overflow
6649 Enables overflow checking for integer operations.
6650 This causes GNAT to generate slower and larger executable
6651 programs by adding code to check for overflow (resulting in raising
6652 @code{Constraint_Error} as required by standard Ada
6653 semantics). These overflow checks correspond to situations in which
6654 the true value of the result of an operation may be outside the base
6655 range of the result type. The following example shows the distinction:
6656
6657 @smallexample @c ada
6658 X1 : Integer := "Integer'Last";
6659 X2 : Integer range 1 .. 5 := "5";
6660 X3 : Integer := "Integer'Last";
6661 X4 : Integer range 1 .. 5 := "5";
6662 F  : Float := "2.0E+20";
6663 @dots{}
6664 X1 := X1 + 1;
6665 X2 := X2 + 1;
6666 X3 := Integer (F);
6667 X4 := Integer (F);
6668 @end smallexample
6669
6670 @noindent
6671 Note that if explicit values are assigned at compile time, the
6672 compiler may be able to detect overflow at compile time, in which case
6673 no actual run-time checking code is required, and Constraint_Error
6674 will be raised unconditionally, with or without
6675 @option{-gnato}. That's why the assigned values in the above fragment
6676 are in quotes, the meaning is "assign a value not known to the
6677 compiler that happens to be equal to ...". The remaining discussion
6678 assumes that the compiler cannot detect the values at compile time.
6679
6680 Here the first addition results in a value that is outside the base range
6681 of Integer, and hence requires an overflow check for detection of the
6682 constraint error. Thus the first assignment to @code{X1} raises a
6683 @code{Constraint_Error} exception only if @option{-gnato} is set.
6684
6685 The second increment operation results in a violation of the explicit
6686 range constraint; such range checks are performed by default, and are
6687 unaffected by @option{-gnato}.
6688
6689 The two conversions of @code{F} both result in values that are outside
6690 the base range of type @code{Integer} and thus will raise
6691 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6692 The fact that the result of the second conversion is assigned to
6693 variable @code{X4} with a restricted range is irrelevant, since the problem
6694 is in the conversion, not the assignment.
6695
6696 Basically the rule is that in the default mode (@option{-gnato} not
6697 used), the generated code assures that all integer variables stay
6698 within their declared ranges, or within the base range if there is
6699 no declared range. This prevents any serious problems like indexes
6700 out of range for array operations.
6701
6702 What is not checked in default mode is an overflow that results in
6703 an in-range, but incorrect value. In the above example, the assignments
6704 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6705 range of the target variable, but the result is wrong in the sense that
6706 it is too large to be represented correctly. Typically the assignment
6707 to @code{X1} will result in wrap around to the largest negative number.
6708 The conversions of @code{F} will result in some @code{Integer} value
6709 and if that integer value is out of the @code{X4} range then the
6710 subsequent assignment would generate an exception.
6711
6712 @findex Machine_Overflows
6713 Note that the @option{-gnato} switch does not affect the code generated
6714 for any floating-point operations; it applies only to integer
6715 semantics).
6716 For floating-point, GNAT has the @code{Machine_Overflows}
6717 attribute set to @code{False} and the normal mode of operation is to
6718 generate IEEE NaN and infinite values on overflow or invalid operations
6719 (such as dividing 0.0 by 0.0).
6720
6721 The reason that we distinguish overflow checking from other kinds of
6722 range constraint checking is that a failure of an overflow check, unlike
6723 for example the failure of a range check, can result in an incorrect
6724 value, but cannot cause random memory destruction (like an out of range
6725 subscript), or a wild jump (from an out of range case value). Overflow
6726 checking is also quite expensive in time and space, since in general it
6727 requires the use of double length arithmetic.
6728
6729 Note again that @option{-gnato} is off by default, so overflow checking is
6730 not performed in default mode. This means that out of the box, with the
6731 default settings, GNAT does not do all the checks expected from the
6732 language description in the Ada Reference Manual. If you want all constraint
6733 checks to be performed, as described in this Manual, then you must
6734 explicitly use the -gnato switch either on the @command{gnatmake} or
6735 @command{gcc} command.
6736
6737 @item -gnatE
6738 @cindex @option{-gnatE} (@command{gcc})
6739 @cindex Elaboration checks
6740 @cindex Check, elaboration
6741 Enables dynamic checks for access-before-elaboration
6742 on subprogram calls and generic instantiations.
6743 Note that @option{-gnatE} is not necessary for safety, because in the
6744 default mode, GNAT ensures statically that the checks would not fail.
6745 For full details of the effect and use of this switch,
6746 @xref{Compiling Using gcc}.
6747
6748 @item -fstack-check
6749 @cindex @option{-fstack-check} (@command{gcc})
6750 @cindex Stack Overflow Checking
6751 @cindex Checks, stack overflow checking
6752 Activates stack overflow checking. For full details of the effect and use of
6753 this switch see @ref{Stack Overflow Checking}.
6754 @end table
6755
6756 @findex Unsuppress
6757 @noindent
6758 The setting of these switches only controls the default setting of the
6759 checks. You may modify them using either @code{Suppress} (to remove
6760 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6761 the program source.
6762
6763 @node Using gcc for Syntax Checking
6764 @subsection Using @command{gcc} for Syntax Checking
6765 @table @option
6766 @item -gnats
6767 @cindex @option{-gnats} (@command{gcc})
6768 @ifclear vms
6769
6770 @noindent
6771 The @code{s} stands for ``syntax''.
6772 @end ifclear
6773
6774 Run GNAT in syntax checking only mode. For
6775 example, the command
6776
6777 @smallexample
6778 $ gcc -c -gnats x.adb
6779 @end smallexample
6780
6781 @noindent
6782 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6783 series of files in a single command
6784 @ifclear vms
6785 , and can use wild cards to specify such a group of files.
6786 Note that you must specify the @option{-c} (compile
6787 only) flag in addition to the @option{-gnats} flag.
6788 @end ifclear
6789 .
6790 You may use other switches in conjunction with @option{-gnats}. In
6791 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6792 format of any generated error messages.
6793
6794 When the source file is empty or contains only empty lines and/or comments,
6795 the output is a warning:
6796
6797 @smallexample
6798 $ gcc -c -gnats -x ada toto.txt
6799 toto.txt:1:01: warning: empty file, contains no compilation units
6800 $
6801 @end smallexample
6802
6803 Otherwise, the output is simply the error messages, if any. No object file or
6804 ALI file is generated by a syntax-only compilation. Also, no units other
6805 than the one specified are accessed. For example, if a unit @code{X}
6806 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6807 check only mode does not access the source file containing unit
6808 @code{Y}.
6809
6810 @cindex Multiple units, syntax checking
6811 Normally, GNAT allows only a single unit in a source file. However, this
6812 restriction does not apply in syntax-check-only mode, and it is possible
6813 to check a file containing multiple compilation units concatenated
6814 together. This is primarily used by the @code{gnatchop} utility
6815 (@pxref{Renaming Files Using gnatchop}).
6816 @end table
6817
6818 @node Using gcc for Semantic Checking
6819 @subsection Using @command{gcc} for Semantic Checking
6820 @table @option
6821 @item -gnatc
6822 @cindex @option{-gnatc} (@command{gcc})
6823
6824 @ifclear vms
6825 @noindent
6826 The @code{c} stands for ``check''.
6827 @end ifclear
6828 Causes the compiler to operate in semantic check mode,
6829 with full checking for all illegalities specified in the
6830 Ada Reference Manual, but without generation of any object code
6831 (no object file is generated).
6832
6833 Because dependent files must be accessed, you must follow the GNAT
6834 semantic restrictions on file structuring to operate in this mode:
6835
6836 @itemize @bullet
6837 @item
6838 The needed source files must be accessible
6839 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6840
6841 @item
6842 Each file must contain only one compilation unit.
6843
6844 @item
6845 The file name and unit name must match (@pxref{File Naming Rules}).
6846 @end itemize
6847
6848 The output consists of error messages as appropriate. No object file is
6849 generated. An @file{ALI} file is generated for use in the context of
6850 cross-reference tools, but this file is marked as not being suitable
6851 for binding (since no object file is generated).
6852 The checking corresponds exactly to the notion of
6853 legality in the Ada Reference Manual.
6854
6855 Any unit can be compiled in semantics-checking-only mode, including
6856 units that would not normally be compiled (subunits,
6857 and specifications where a separate body is present).
6858 @end table
6859
6860 @node Compiling Different Versions of Ada
6861 @subsection Compiling Different Versions of Ada
6862
6863 @noindent
6864 The switches described in this section allow you to explicitly specify
6865 the version of the Ada language that your programs are written in.
6866 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6867 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6868 indicate Ada 83 compatibility mode.
6869
6870 @table @option
6871 @cindex Compatibility with Ada 83
6872
6873 @item -gnat83 (Ada 83 Compatibility Mode)
6874 @cindex @option{-gnat83} (@command{gcc})
6875 @cindex ACVC, Ada 83 tests
6876 @cindex Ada 83 mode
6877
6878 @noindent
6879 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6880 specifies that the program is to be compiled in Ada 83 mode. With
6881 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6882 semantics where this can be done easily.
6883 It is not possible to guarantee this switch does a perfect
6884 job; some subtle tests, such as are
6885 found in earlier ACVC tests (and that have been removed from the ACATS suite
6886 for Ada 95), might not compile correctly.
6887 Nevertheless, this switch may be useful in some circumstances, for example
6888 where, due to contractual reasons, existing code needs to be maintained
6889 using only Ada 83 features.
6890
6891 With few exceptions (most notably the need to use @code{<>} on
6892 @cindex Generic formal parameters
6893 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6894 reserved words, and the use of packages
6895 with optional bodies), it is not necessary to specify the
6896 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6897 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6898 a correct Ada 83 program is usually also a correct program
6899 in these later versions of the language standard.
6900 For further information, please refer to @ref{Compatibility and Porting Guide}.
6901
6902 @item -gnat95 (Ada 95 mode)
6903 @cindex @option{-gnat95} (@command{gcc})
6904 @cindex Ada 95 mode
6905
6906 @noindent
6907 This switch directs the compiler to implement the Ada 95 version of the
6908 language.
6909 Since Ada 95 is almost completely upwards
6910 compatible with Ada 83, Ada 83 programs may generally be compiled using
6911 this switch (see the description of the @option{-gnat83} switch for further
6912 information about Ada 83 mode).
6913 If an Ada 2005 program is compiled in Ada 95 mode,
6914 uses of the new Ada 2005 features will cause error
6915 messages or warnings.
6916
6917 This switch also can be used to cancel the effect of a previous
6918 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6919 switch earlier in the command line.
6920
6921 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6922 @cindex @option{-gnat05} (@command{gcc})
6923 @cindex @option{-gnat2005} (@command{gcc})
6924 @cindex Ada 2005 mode
6925
6926 @noindent
6927 This switch directs the compiler to implement the Ada 2005 version of the
6928 language, as documented in the official Ada standards document.
6929 Since Ada 2005 is almost completely upwards
6930 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6931 may generally be compiled using this switch (see the description of the
6932 @option{-gnat83} and @option{-gnat95} switches for further
6933 information).
6934
6935 Note that even though Ada 2005 is the current official version of the
6936 language, GNAT still compiles in Ada 95 mode by default, so if you are
6937 using Ada 2005 features in your program, you must use this switch (or
6938 the equivalent Ada_05 or Ada_2005 configuration pragmas).
6939
6940 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6941 @cindex @option{-gnat12} (@command{gcc})
6942 @cindex @option{-gnat2012} (@command{gcc})
6943 @cindex Ada 2012 mode
6944
6945 @noindent
6946 This switch directs the compiler to implement the Ada 2012 version of the
6947 language.
6948 Since Ada 2012 is almost completely upwards
6949 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6950 Ada 83 and Ada 95 programs
6951 may generally be compiled using this switch (see the description of the
6952 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6953 for further information).
6954
6955 For information about the approved ``Ada Issues'' that have been incorporated
6956 into Ada 2012, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6957 Included with GNAT releases is a file @file{features-ada12} that describes
6958 the set of implemented Ada 2012 features.
6959
6960 @item -gnatX (Enable GNAT Extensions)
6961 @cindex @option{-gnatX} (@command{gcc})
6962 @cindex Ada language extensions
6963 @cindex GNAT extensions
6964
6965 @noindent
6966 This switch directs the compiler to implement the latest version of the
6967 language (currently Ada 2012) and also to enable certain GNAT implementation
6968 extensions that are not part of any Ada standard. For a full list of these
6969 extensions, see the GNAT reference manual.
6970
6971 @end table
6972
6973 @node Character Set Control
6974 @subsection Character Set Control
6975 @table @option
6976 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6977 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6978
6979 @noindent
6980 Normally GNAT recognizes the Latin-1 character set in source program
6981 identifiers, as described in the Ada Reference Manual.
6982 This switch causes
6983 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6984 single character ^^or word^ indicating the character set, as follows:
6985
6986 @table @code
6987 @item 1
6988 ISO 8859-1 (Latin-1) identifiers
6989
6990 @item 2
6991 ISO 8859-2 (Latin-2) letters allowed in identifiers
6992
6993 @item 3
6994 ISO 8859-3 (Latin-3) letters allowed in identifiers
6995
6996 @item 4
6997 ISO 8859-4 (Latin-4) letters allowed in identifiers
6998
6999 @item 5
7000 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7001
7002 @item 9
7003 ISO 8859-15 (Latin-9) letters allowed in identifiers
7004
7005 @item ^p^PC^
7006 IBM PC letters (code page 437) allowed in identifiers
7007
7008 @item ^8^PC850^
7009 IBM PC letters (code page 850) allowed in identifiers
7010
7011 @item ^f^FULL_UPPER^
7012 Full upper-half codes allowed in identifiers
7013
7014 @item ^n^NO_UPPER^
7015 No upper-half codes allowed in identifiers
7016
7017 @item ^w^WIDE^
7018 Wide-character codes (that is, codes greater than 255)
7019 allowed in identifiers
7020 @end table
7021
7022 @xref{Foreign Language Representation}, for full details on the
7023 implementation of these character sets.
7024
7025 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7026 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7027 Specify the method of encoding for wide characters.
7028 @var{e} is one of the following:
7029
7030 @table @code
7031
7032 @item ^h^HEX^
7033 Hex encoding (brackets coding also recognized)
7034
7035 @item ^u^UPPER^
7036 Upper half encoding (brackets encoding also recognized)
7037
7038 @item ^s^SHIFT_JIS^
7039 Shift/JIS encoding (brackets encoding also recognized)
7040
7041 @item ^e^EUC^
7042 EUC encoding (brackets encoding also recognized)
7043
7044 @item ^8^UTF8^
7045 UTF-8 encoding (brackets encoding also recognized)
7046
7047 @item ^b^BRACKETS^
7048 Brackets encoding only (default value)
7049 @end table
7050 For full details on these encoding
7051 methods see @ref{Wide Character Encodings}.
7052 Note that brackets coding is always accepted, even if one of the other
7053 options is specified, so for example @option{-gnatW8} specifies that both
7054 brackets and UTF-8 encodings will be recognized. The units that are
7055 with'ed directly or indirectly will be scanned using the specified
7056 representation scheme, and so if one of the non-brackets scheme is
7057 used, it must be used consistently throughout the program. However,
7058 since brackets encoding is always recognized, it may be conveniently
7059 used in standard libraries, allowing these libraries to be used with
7060 any of the available coding schemes.
7061 scheme.
7062
7063 If no @option{-gnatW?} parameter is present, then the default
7064 representation is normally Brackets encoding only. However, if the
7065 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7066 byte order mark or BOM for UTF-8), then these three characters are
7067 skipped and the default representation for the file is set to UTF-8.
7068
7069 Note that the wide character representation that is specified (explicitly
7070 or by default) for the main program also acts as the default encoding used
7071 for Wide_Text_IO files if not specifically overridden by a WCEM form
7072 parameter.
7073
7074 @end table
7075 @node File Naming Control
7076 @subsection File Naming Control
7077
7078 @table @option
7079 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7080 @cindex @option{-gnatk} (@command{gcc})
7081 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7082 1-999, indicates the maximum allowable length of a file name (not
7083 including the @file{.ads} or @file{.adb} extension). The default is not
7084 to enable file name krunching.
7085
7086 For the source file naming rules, @xref{File Naming Rules}.
7087 @end table
7088
7089 @node Subprogram Inlining Control
7090 @subsection Subprogram Inlining Control
7091
7092 @table @option
7093 @c !sort!
7094 @item -gnatn
7095 @cindex @option{-gnatn} (@command{gcc})
7096 @ifclear vms
7097 The @code{n} here is intended to suggest the first syllable of the
7098 word ``inline''.
7099 @end ifclear
7100 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7101 inlining to actually occur, optimization must be enabled. To enable
7102 inlining of subprograms specified by pragma @code{Inline},
7103 you must also specify this switch.
7104 In the absence of this switch, GNAT does not attempt
7105 inlining and does not need to access the bodies of
7106 subprograms for which @code{pragma Inline} is specified if they are not
7107 in the current unit.
7108
7109 If you specify this switch the compiler will access these bodies,
7110 creating an extra source dependency for the resulting object file, and
7111 where possible, the call will be inlined.
7112 For further details on when inlining is possible
7113 see @ref{Inlining of Subprograms}.
7114
7115 @item -gnatN
7116 @cindex @option{-gnatN} (@command{gcc})
7117 This switch activates front-end inlining which also
7118 generates additional dependencies.
7119
7120 When using a gcc-based back end (in practice this means using any version
7121 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7122 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7123 Historically front end inlining was more extensive than the gcc back end
7124 inlining, but that is no longer the case.
7125 @end table
7126
7127 @node Auxiliary Output Control
7128 @subsection Auxiliary Output Control
7129
7130 @table @option
7131 @item -gnatt
7132 @cindex @option{-gnatt} (@command{gcc})
7133 @cindex Writing internal trees
7134 @cindex Internal trees, writing to file
7135 Causes GNAT to write the internal tree for a unit to a file (with the
7136 extension @file{.adt}.
7137 This not normally required, but is used by separate analysis tools.
7138 Typically
7139 these tools do the necessary compilations automatically, so you should
7140 not have to specify this switch in normal operation.
7141 Note that the combination of switches @option{-gnatct}
7142 generates a tree in the form required by ASIS applications.
7143
7144 @item -gnatu
7145 @cindex @option{-gnatu} (@command{gcc})
7146 Print a list of units required by this compilation on @file{stdout}.
7147 The listing includes all units on which the unit being compiled depends
7148 either directly or indirectly.
7149
7150 @ifclear vms
7151 @item -pass-exit-codes
7152 @cindex @option{-pass-exit-codes} (@command{gcc})
7153 If this switch is not used, the exit code returned by @command{gcc} when
7154 compiling multiple files indicates whether all source files have
7155 been successfully used to generate object files or not.
7156
7157 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7158 exit status and allows an integrated development environment to better
7159 react to a compilation failure. Those exit status are:
7160
7161 @table @asis
7162 @item 5
7163 There was an error in at least one source file.
7164 @item 3
7165 At least one source file did not generate an object file.
7166 @item 2
7167 The compiler died unexpectedly (internal error for example).
7168 @item 0
7169 An object file has been generated for every source file.
7170 @end table
7171 @end ifclear
7172 @end table
7173
7174 @node Debugging Control
7175 @subsection Debugging Control
7176
7177 @table @option
7178 @c !sort!
7179 @cindex Debugging options
7180 @ifclear vms
7181 @item -gnatd@var{x}
7182 @cindex @option{-gnatd} (@command{gcc})
7183 Activate internal debugging switches. @var{x} is a letter or digit, or
7184 string of letters or digits, which specifies the type of debugging
7185 outputs desired. Normally these are used only for internal development
7186 or system debugging purposes. You can find full documentation for these
7187 switches in the body of the @code{Debug} unit in the compiler source
7188 file @file{debug.adb}.
7189 @end ifclear
7190
7191 @item -gnatG[=nn]
7192 @cindex @option{-gnatG} (@command{gcc})
7193 This switch causes the compiler to generate auxiliary output containing
7194 a pseudo-source listing of the generated expanded code. Like most Ada
7195 compilers, GNAT works by first transforming the high level Ada code into
7196 lower level constructs. For example, tasking operations are transformed
7197 into calls to the tasking run-time routines. A unique capability of GNAT
7198 is to list this expanded code in a form very close to normal Ada source.
7199 This is very useful in understanding the implications of various Ada
7200 usage on the efficiency of the generated code. There are many cases in
7201 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7202 generate a lot of run-time code. By using @option{-gnatG} you can identify
7203 these cases, and consider whether it may be desirable to modify the coding
7204 approach to improve efficiency.
7205
7206 The optional parameter @code{nn} if present after -gnatG specifies an
7207 alternative maximum line length that overrides the normal default of 72.
7208 This value is in the range 40-999999, values less than 40 being silently
7209 reset to 40. The equal sign is optional.
7210
7211 The format of the output is very similar to standard Ada source, and is
7212 easily understood by an Ada programmer. The following special syntactic
7213 additions correspond to low level features used in the generated code that
7214 do not have any exact analogies in pure Ada source form. The following
7215 is a partial list of these special constructions. See the spec
7216 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7217
7218 If the switch @option{-gnatL} is used in conjunction with
7219 @cindex @option{-gnatL} (@command{gcc})
7220 @option{-gnatG}, then the original source lines are interspersed
7221 in the expanded source (as comment lines with the original line number).
7222
7223 @table @code
7224 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7225 Shows the storage pool being used for an allocator.
7226
7227 @item at end @var{procedure-name};
7228 Shows the finalization (cleanup) procedure for a scope.
7229
7230 @item (if @var{expr} then @var{expr} else @var{expr})
7231 Conditional expression equivalent to the @code{x?y:z} construction in C.
7232
7233 @item @var{target}^^^(@var{source})
7234 A conversion with floating-point truncation instead of rounding.
7235
7236 @item @var{target}?(@var{source})
7237 A conversion that bypasses normal Ada semantic checking. In particular
7238 enumeration types and fixed-point types are treated simply as integers.
7239
7240 @item @var{target}?^^^(@var{source})
7241 Combines the above two cases.
7242
7243 @item @var{x} #/ @var{y}
7244 @itemx @var{x} #mod @var{y}
7245 @itemx @var{x} #* @var{y}
7246 @itemx @var{x} #rem @var{y}
7247 A division or multiplication of fixed-point values which are treated as
7248 integers without any kind of scaling.
7249
7250 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7251 Shows the storage pool associated with a @code{free} statement.
7252
7253 @item [subtype or type declaration]
7254 Used to list an equivalent declaration for an internally generated
7255 type that is referenced elsewhere in the listing.
7256
7257 @c @item freeze @var{type-name} @ovar{actions}
7258 @c Expanding @ovar macro inline (explanation in macro def comments)
7259 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7260 Shows the point at which @var{type-name} is frozen, with possible
7261 associated actions to be performed at the freeze point.
7262
7263 @item reference @var{itype}
7264 Reference (and hence definition) to internal type @var{itype}.
7265
7266 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7267 Intrinsic function call.
7268
7269 @item @var{label-name} : label
7270 Declaration of label @var{labelname}.
7271
7272 @item #$ @var{subprogram-name}
7273 An implicit call to a run-time support routine
7274 (to meet the requirement of H.3.1(9) in a
7275 convenient manner).
7276
7277 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7278 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7279 @var{expr}, but handled more efficiently).
7280
7281 @item [constraint_error]
7282 Raise the @code{Constraint_Error} exception.
7283
7284 @item @var{expression}'reference
7285 A pointer to the result of evaluating @var{expression}.
7286
7287 @item @var{target-type}!(@var{source-expression})
7288 An unchecked conversion of @var{source-expression} to @var{target-type}.
7289
7290 @item [@var{numerator}/@var{denominator}]
7291 Used to represent internal real literals (that) have no exact
7292 representation in base 2-16 (for example, the result of compile time
7293 evaluation of the expression 1.0/27.0).
7294 @end table
7295
7296 @item -gnatD[=nn]
7297 @cindex @option{-gnatD} (@command{gcc})
7298 When used in conjunction with @option{-gnatG}, this switch causes
7299 the expanded source, as described above for
7300 @option{-gnatG} to be written to files with names
7301 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7302 instead of to the standard output file. For
7303 example, if the source file name is @file{hello.adb}, then a file
7304 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7305 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7306 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7307 you to do source level debugging using the generated code which is
7308 sometimes useful for complex code, for example to find out exactly
7309 which part of a complex construction raised an exception. This switch
7310 also suppress generation of cross-reference information (see
7311 @option{-gnatx}) since otherwise the cross-reference information
7312 would refer to the @file{^.dg^.DG^} file, which would cause
7313 confusion since this is not the original source file.
7314
7315 Note that @option{-gnatD} actually implies @option{-gnatG}
7316 automatically, so it is not necessary to give both options.
7317 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7318
7319 If the switch @option{-gnatL} is used in conjunction with
7320 @cindex @option{-gnatL} (@command{gcc})
7321 @option{-gnatDG}, then the original source lines are interspersed
7322 in the expanded source (as comment lines with the original line number).
7323
7324 The optional parameter @code{nn} if present after -gnatD specifies an
7325 alternative maximum line length that overrides the normal default of 72.
7326 This value is in the range 40-999999, values less than 40 being silently
7327 reset to 40. The equal sign is optional.
7328
7329 @item -gnatr
7330 @cindex @option{-gnatr} (@command{gcc})
7331 @cindex pragma Restrictions
7332 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7333 so that violation of restrictions causes warnings rather than illegalities.
7334 This is useful during the development process when new restrictions are added
7335 or investigated. The switch also causes pragma Profile to be treated as
7336 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7337 restriction warnings rather than restrictions.
7338
7339 @ifclear vms
7340 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7341 @cindex @option{-gnatR} (@command{gcc})
7342 This switch controls output from the compiler of a listing showing
7343 representation information for declared types and objects. For
7344 @option{-gnatR0}, no information is output (equivalent to omitting
7345 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7346 so @option{-gnatR} with no parameter has the same effect), size and alignment
7347 information is listed for declared array and record types. For
7348 @option{-gnatR2}, size and alignment information is listed for all
7349 declared types and objects. Finally @option{-gnatR3} includes symbolic
7350 expressions for values that are computed at run time for
7351 variant records. These symbolic expressions have a mostly obvious
7352 format with #n being used to represent the value of the n'th
7353 discriminant. See source files @file{repinfo.ads/adb} in the
7354 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7355 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7356 the output is to a file with the name @file{^file.rep^file_REP^} where
7357 file is the name of the corresponding source file.
7358 @end ifclear
7359 @ifset vms
7360 @item /REPRESENTATION_INFO
7361 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7362 This qualifier controls output from the compiler of a listing showing
7363 representation information for declared types and objects. For
7364 @option{/REPRESENTATION_INFO=NONE}, no information is output
7365 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7366 @option{/REPRESENTATION_INFO} without option is equivalent to
7367 @option{/REPRESENTATION_INFO=ARRAYS}.
7368 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7369 information is listed for declared array and record types. For
7370 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7371 is listed for all expression information for values that are computed
7372 at run time for variant records. These symbolic expressions have a mostly
7373 obvious format with #n being used to represent the value of the n'th
7374 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7375 @code{GNAT} sources for full details on the format of
7376 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7377 If _FILE is added at the end of an option
7378 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7379 then the output is to a file with the name @file{file_REP} where
7380 file is the name of the corresponding source file.
7381 @end ifset
7382 Note that it is possible for record components to have zero size. In
7383 this case, the component clause uses an obvious extension of permitted
7384 Ada syntax, for example @code{at 0 range 0 .. -1}.
7385
7386 Representation information requires that code be generated (since it is the
7387 code generator that lays out complex data structures). If an attempt is made
7388 to output representation information when no code is generated, for example
7389 when a subunit is compiled on its own, then no information can be generated
7390 and the compiler outputs a message to this effect.
7391
7392 @item -gnatS
7393 @cindex @option{-gnatS} (@command{gcc})
7394 The use of the switch @option{-gnatS} for an
7395 Ada compilation will cause the compiler to output a
7396 representation of package Standard in a form very
7397 close to standard Ada. It is not quite possible to
7398 do this entirely in standard Ada (since new
7399 numeric base types cannot be created in standard
7400 Ada), but the output is easily
7401 readable to any Ada programmer, and is useful to
7402 determine the characteristics of target dependent
7403 types in package Standard.
7404
7405 @item -gnatx
7406 @cindex @option{-gnatx} (@command{gcc})
7407 Normally the compiler generates full cross-referencing information in
7408 the @file{ALI} file. This information is used by a number of tools,
7409 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7410 suppresses this information. This saves some space and may slightly
7411 speed up compilation, but means that these tools cannot be used.
7412 @end table
7413
7414 @node Exception Handling Control
7415 @subsection Exception Handling Control
7416
7417 @noindent
7418 GNAT uses two methods for handling exceptions at run-time. The
7419 @code{setjmp/longjmp} method saves the context when entering
7420 a frame with an exception handler. Then when an exception is
7421 raised, the context can be restored immediately, without the
7422 need for tracing stack frames. This method provides very fast
7423 exception propagation, but introduces significant overhead for
7424 the use of exception handlers, even if no exception is raised.
7425
7426 The other approach is called ``zero cost'' exception handling.
7427 With this method, the compiler builds static tables to describe
7428 the exception ranges. No dynamic code is required when entering
7429 a frame containing an exception handler. When an exception is
7430 raised, the tables are used to control a back trace of the
7431 subprogram invocation stack to locate the required exception
7432 handler. This method has considerably poorer performance for
7433 the propagation of exceptions, but there is no overhead for
7434 exception handlers if no exception is raised. Note that in this
7435 mode and in the context of mixed Ada and C/C++ programming,
7436 to propagate an exception through a C/C++ code, the C/C++ code
7437 must be compiled with the @option{-funwind-tables} GCC's
7438 option.
7439
7440 The following switches may be used to control which of the
7441 two exception handling methods is used.
7442
7443 @table @option
7444 @c !sort!
7445
7446 @item --RTS=sjlj
7447 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7448 This switch causes the setjmp/longjmp run-time (when available) to be used
7449 for exception handling. If the default
7450 mechanism for the target is zero cost exceptions, then
7451 this switch can be used to modify this default, and must be
7452 used for all units in the partition.
7453 This option is rarely used. One case in which it may be
7454 advantageous is if you have an application where exception
7455 raising is common and the overall performance of the
7456 application is improved by favoring exception propagation.
7457
7458 @item --RTS=zcx
7459 @cindex @option{--RTS=zcx} (@command{gnatmake})
7460 @cindex Zero Cost Exceptions
7461 This switch causes the zero cost approach to be used
7462 for exception handling. If this is the default mechanism for the
7463 target (see below), then this switch is unneeded. If the default
7464 mechanism for the target is setjmp/longjmp exceptions, then
7465 this switch can be used to modify this default, and must be
7466 used for all units in the partition.
7467 This option can only be used if the zero cost approach
7468 is available for the target in use, otherwise it will generate an error.
7469 @end table
7470
7471 @noindent
7472 The same option @option{--RTS} must be used both for @command{gcc}
7473 and @command{gnatbind}. Passing this option to @command{gnatmake}
7474 (@pxref{Switches for gnatmake}) will ensure the required consistency
7475 through the compilation and binding steps.
7476
7477 @node Units to Sources Mapping Files
7478 @subsection Units to Sources Mapping Files
7479
7480 @table @option
7481
7482 @item -gnatem=@var{path}
7483 @cindex @option{-gnatem} (@command{gcc})
7484 A mapping file is a way to communicate to the compiler two mappings:
7485 from unit names to file names (without any directory information) and from
7486 file names to path names (with full directory information). These mappings
7487 are used by the compiler to short-circuit the path search.
7488
7489 The use of mapping files is not required for correct operation of the
7490 compiler, but mapping files can improve efficiency, particularly when
7491 sources are read over a slow network connection. In normal operation,
7492 you need not be concerned with the format or use of mapping files,
7493 and the @option{-gnatem} switch is not a switch that you would use
7494 explicitly. It is intended primarily for use by automatic tools such as
7495 @command{gnatmake} running under the project file facility. The
7496 description here of the format of mapping files is provided
7497 for completeness and for possible use by other tools.
7498
7499 A mapping file is a sequence of sets of three lines. In each set, the
7500 first line is the unit name, in lower case, with @code{%s} appended
7501 for specs and @code{%b} appended for bodies; the second line is the
7502 file name; and the third line is the path name.
7503
7504 Example:
7505 @smallexample
7506    main%b
7507    main.2.ada
7508    /gnat/project1/sources/main.2.ada
7509 @end smallexample
7510
7511 When the switch @option{-gnatem} is specified, the compiler will
7512 create in memory the two mappings from the specified file. If there is
7513 any problem (nonexistent file, truncated file or duplicate entries),
7514 no mapping will be created.
7515
7516 Several @option{-gnatem} switches may be specified; however, only the
7517 last one on the command line will be taken into account.
7518
7519 When using a project file, @command{gnatmake} creates a temporary
7520 mapping file and communicates it to the compiler using this switch.
7521
7522 @end table
7523
7524 @node Integrated Preprocessing
7525 @subsection Integrated Preprocessing
7526
7527 @noindent
7528 GNAT sources may be preprocessed immediately before compilation.
7529 In this case, the actual
7530 text of the source is not the text of the source file, but is derived from it
7531 through a process called preprocessing. Integrated preprocessing is specified
7532 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7533 indicates, through a text file, the preprocessing data to be used.
7534 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7535
7536 @noindent
7537 Note that when integrated preprocessing is used, the output from the
7538 preprocessor is not written to any external file. Instead it is passed
7539 internally to the compiler. If you need to preserve the result of
7540 preprocessing in a file, then you should use @command{gnatprep}
7541 to perform the desired preprocessing in stand-alone mode.
7542
7543 @noindent
7544 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7545 used when Integrated Preprocessing is used. The reason is that preprocessing
7546 with another Preprocessing Data file without changing the sources will
7547 not trigger recompilation without this switch.
7548
7549 @noindent
7550 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7551 always trigger recompilation for sources that are preprocessed,
7552 because @command{gnatmake} cannot compute the checksum of the source after
7553 preprocessing.
7554
7555 @noindent
7556 The actual preprocessing function is described in details in section
7557 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7558 preprocessing is triggered and parameterized.
7559
7560 @table @code
7561
7562 @item -gnatep=@var{file}
7563 @cindex @option{-gnatep} (@command{gcc})
7564 This switch indicates to the compiler the file name (without directory
7565 information) of the preprocessor data file to use. The preprocessor data file
7566 should be found in the source directories.
7567
7568 @noindent
7569 A preprocessing data file is a text file with significant lines indicating
7570 how should be preprocessed either a specific source or all sources not
7571 mentioned in other lines. A significant line is a nonempty, non-comment line.
7572 Comments are similar to Ada comments.
7573
7574 @noindent
7575 Each significant line starts with either a literal string or the character '*'.
7576 A literal string is the file name (without directory information) of the source
7577 to preprocess. A character '*' indicates the preprocessing for all the sources
7578 that are not specified explicitly on other lines (order of the lines is not
7579 significant). It is an error to have two lines with the same file name or two
7580 lines starting with the character '*'.
7581
7582 @noindent
7583 After the file name or the character '*', another optional literal string
7584 indicating the file name of the definition file to be used for preprocessing
7585 (@pxref{Form of Definitions File}). The definition files are found by the
7586 compiler in one of the source directories. In some cases, when compiling
7587 a source in a directory other than the current directory, if the definition
7588 file is in the current directory, it may be necessary to add the current
7589 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7590 the compiler would not find the definition file.
7591
7592 @noindent
7593 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7594 be found. Those ^switches^switches^ are:
7595
7596 @table @code
7597
7598 @item -b
7599 Causes both preprocessor lines and the lines deleted by
7600 preprocessing to be replaced by blank lines, preserving the line number.
7601 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7602 it cancels the effect of @option{-c}.
7603
7604 @item -c
7605 Causes both preprocessor lines and the lines deleted
7606 by preprocessing to be retained as comments marked
7607 with the special string ``@code{--! }''.
7608
7609 @item -Dsymbol=value
7610 Define or redefine a symbol, associated with value. A symbol is an Ada
7611 identifier, or an Ada reserved word, with the exception of @code{if},
7612 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7613 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7614 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7615 same name defined in a definition file.
7616
7617 @item -s
7618 Causes a sorted list of symbol names and values to be
7619 listed on the standard output file.
7620
7621 @item -u
7622 Causes undefined symbols to be treated as having the value @code{FALSE}
7623 in the context
7624 of a preprocessor test. In the absence of this option, an undefined symbol in
7625 a @code{#if} or @code{#elsif} test will be treated as an error.
7626
7627 @end table
7628
7629 @noindent
7630 Examples of valid lines in a preprocessor data file:
7631
7632 @smallexample
7633   "toto.adb"  "prep.def" -u
7634   --  preprocess "toto.adb", using definition file "prep.def",
7635   --  undefined symbol are False.
7636
7637   * -c -DVERSION=V101
7638   --  preprocess all other sources without a definition file;
7639   --  suppressed lined are commented; symbol VERSION has the value V101.
7640
7641   "titi.adb" "prep2.def" -s
7642   --  preprocess "titi.adb", using definition file "prep2.def";
7643   --  list all symbols with their values.
7644 @end smallexample
7645
7646 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7647 @cindex @option{-gnateD} (@command{gcc})
7648 Define or redefine a preprocessing symbol, associated with value. If no value
7649 is given on the command line, then the value of the symbol is @code{True}.
7650 A symbol is an identifier, following normal Ada (case-insensitive)
7651 rules for its syntax, and value is any sequence (including an empty sequence)
7652 of characters from the set (letters, digits, period, underline).
7653 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7654 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7655
7656 @noindent
7657 A symbol declared with this ^switch^switch^ on the command line replaces a
7658 symbol with the same name either in a definition file or specified with a
7659 ^switch^switch^ -D in the preprocessor data file.
7660
7661 @noindent
7662 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7663
7664 @item -gnateG
7665 When integrated preprocessing is performed and the preprocessor modifies
7666 the source text, write the result of this preprocessing into a file
7667 <source>^.prep^_prep^.
7668
7669 @end table
7670
7671 @node Code Generation Control
7672 @subsection Code Generation Control
7673
7674 @noindent
7675
7676 The GCC technology provides a wide range of target dependent
7677 @option{-m} switches for controlling
7678 details of code generation with respect to different versions of
7679 architectures. This includes variations in instruction sets (e.g.@:
7680 different members of the power pc family), and different requirements
7681 for optimal arrangement of instructions (e.g.@: different members of
7682 the x86 family). The list of available @option{-m} switches may be
7683 found in the GCC documentation.
7684
7685 Use of these @option{-m} switches may in some cases result in improved
7686 code performance.
7687
7688 The GNAT Pro technology is tested and qualified without any
7689 @option{-m} switches,
7690 so generally the most reliable approach is to avoid the use of these
7691 switches. However, we generally expect most of these switches to work
7692 successfully with GNAT Pro, and many customers have reported successful
7693 use of these options.
7694
7695 Our general advice is to avoid the use of @option{-m} switches unless
7696 special needs lead to requirements in this area. In particular,
7697 there is no point in using @option{-m} switches to improve performance
7698 unless you actually see a performance improvement.
7699
7700 @ifset vms
7701 @node Return Codes
7702 @subsection Return Codes
7703 @cindex Return Codes
7704 @cindex @option{/RETURN_CODES=VMS}
7705
7706 @noindent
7707 On VMS, GNAT compiled programs return POSIX-style codes by default,
7708 e.g.@: @option{/RETURN_CODES=POSIX}.
7709
7710 To enable VMS style return codes, use GNAT BIND and LINK with the option
7711 @option{/RETURN_CODES=VMS}. For example:
7712
7713 @smallexample
7714 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7715 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7716 @end smallexample
7717
7718 @noindent
7719 Programs built with /RETURN_CODES=VMS are suitable to be called in
7720 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7721 are suitable for spawning with appropriate GNAT RTL routines.
7722
7723 @end ifset
7724
7725 @node Search Paths and the Run-Time Library (RTL)
7726 @section Search Paths and the Run-Time Library (RTL)
7727
7728 @noindent
7729 With the GNAT source-based library system, the compiler must be able to
7730 find source files for units that are needed by the unit being compiled.
7731 Search paths are used to guide this process.
7732
7733 The compiler compiles one source file whose name must be given
7734 explicitly on the command line. In other words, no searching is done
7735 for this file. To find all other source files that are needed (the most
7736 common being the specs of units), the compiler examines the following
7737 directories, in the following order:
7738
7739 @enumerate
7740 @item
7741 The directory containing the source file of the main unit being compiled
7742 (the file name on the command line).
7743
7744 @item
7745 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7746 @command{gcc} command line, in the order given.
7747
7748 @item
7749 @findex ADA_PRJ_INCLUDE_FILE
7750 Each of the directories listed in the text file whose name is given
7751 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7752
7753 @noindent
7754 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7755 driver when project files are used. It should not normally be set
7756 by other means.
7757
7758 @item
7759 @findex ADA_INCLUDE_PATH
7760 Each of the directories listed in the value of the
7761 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7762 @ifclear vms
7763 Construct this value
7764 exactly as the @env{PATH} environment variable: a list of directory
7765 names separated by colons (semicolons when working with the NT version).
7766 @end ifclear
7767 @ifset vms
7768 Normally, define this value as a logical name containing a comma separated
7769 list of directory names.
7770
7771 This variable can also be defined by means of an environment string
7772 (an argument to the HP C exec* set of functions).
7773
7774 Logical Name:
7775 @smallexample
7776 DEFINE ANOTHER_PATH FOO:[BAG]
7777 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7778 @end smallexample
7779
7780 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7781 first, followed by the standard Ada
7782 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7783 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7784 (Text_IO, Sequential_IO, etc)
7785 instead of the standard Ada packages. Thus, in order to get the standard Ada
7786 packages by default, ADA_INCLUDE_PATH must be redefined.
7787 @end ifset
7788
7789 @item
7790 The content of the @file{ada_source_path} file which is part of the GNAT
7791 installation tree and is used to store standard libraries such as the
7792 GNAT Run Time Library (RTL) source files.
7793 @ifclear vms
7794 @ref{Installing a library}
7795 @end ifclear
7796 @end enumerate
7797
7798 @noindent
7799 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7800 inhibits the use of the directory
7801 containing the source file named in the command line. You can still
7802 have this directory on your search path, but in this case it must be
7803 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7804
7805 Specifying the switch @option{-nostdinc}
7806 inhibits the search of the default location for the GNAT Run Time
7807 Library (RTL) source files.
7808
7809 The compiler outputs its object files and ALI files in the current
7810 working directory.
7811 @ifclear vms
7812 Caution: The object file can be redirected with the @option{-o} switch;
7813 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7814 so the @file{ALI} file will not go to the right place. Therefore, you should
7815 avoid using the @option{-o} switch.
7816 @end ifclear
7817
7818 @findex System.IO
7819 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7820 children make up the GNAT RTL, together with the simple @code{System.IO}
7821 package used in the @code{"Hello World"} example. The sources for these units
7822 are needed by the compiler and are kept together in one directory. Not
7823 all of the bodies are needed, but all of the sources are kept together
7824 anyway. In a normal installation, you need not specify these directory
7825 names when compiling or binding. Either the environment variables or
7826 the built-in defaults cause these files to be found.
7827
7828 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7829 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7830 consisting of child units of @code{GNAT}. This is a collection of generally
7831 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7832 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7833
7834 Besides simplifying access to the RTL, a major use of search paths is
7835 in compiling sources from multiple directories. This can make
7836 development environments much more flexible.
7837
7838 @node Order of Compilation Issues
7839 @section Order of Compilation Issues
7840
7841 @noindent
7842 If, in our earlier example, there was a spec for the @code{hello}
7843 procedure, it would be contained in the file @file{hello.ads}; yet this
7844 file would not have to be explicitly compiled. This is the result of the
7845 model we chose to implement library management. Some of the consequences
7846 of this model are as follows:
7847
7848 @itemize @bullet
7849 @item
7850 There is no point in compiling specs (except for package
7851 specs with no bodies) because these are compiled as needed by clients. If
7852 you attempt a useless compilation, you will receive an error message.
7853 It is also useless to compile subunits because they are compiled as needed
7854 by the parent.
7855
7856 @item
7857 There are no order of compilation requirements: performing a
7858 compilation never obsoletes anything. The only way you can obsolete
7859 something and require recompilations is to modify one of the
7860 source files on which it depends.
7861
7862 @item
7863 There is no library as such, apart from the ALI files
7864 (@pxref{The Ada Library Information Files}, for information on the format
7865 of these files). For now we find it convenient to create separate ALI files,
7866 but eventually the information therein may be incorporated into the object
7867 file directly.
7868
7869 @item
7870 When you compile a unit, the source files for the specs of all units
7871 that it @code{with}'s, all its subunits, and the bodies of any generics it
7872 instantiates must be available (reachable by the search-paths mechanism
7873 described above), or you will receive a fatal error message.
7874 @end itemize
7875
7876 @node Examples
7877 @section Examples
7878
7879 @noindent
7880 The following are some typical Ada compilation command line examples:
7881
7882 @table @code
7883 @item $ gcc -c xyz.adb
7884 Compile body in file @file{xyz.adb} with all default options.
7885
7886 @ifclear vms
7887 @item $ gcc -c -O2 -gnata xyz-def.adb
7888 @end ifclear
7889 @ifset vms
7890 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7891 @end ifset
7892
7893 Compile the child unit package in file @file{xyz-def.adb} with extensive
7894 optimizations, and pragma @code{Assert}/@code{Debug} statements
7895 enabled.
7896
7897 @item $ gcc -c -gnatc abc-def.adb
7898 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7899 mode.
7900 @end table
7901
7902 @node Binding Using gnatbind
7903 @chapter Binding Using @code{gnatbind}
7904 @findex gnatbind
7905
7906 @menu
7907 * Running gnatbind::
7908 * Switches for gnatbind::
7909 * Command-Line Access::
7910 * Search Paths for gnatbind::
7911 * Examples of gnatbind Usage::
7912 @end menu
7913
7914 @noindent
7915 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7916 to bind compiled GNAT objects.
7917
7918 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7919 driver (see @ref{The GNAT Driver and Project Files}).
7920
7921 The @code{gnatbind} program performs four separate functions:
7922
7923 @enumerate
7924 @item
7925 Checks that a program is consistent, in accordance with the rules in
7926 Chapter 10 of the Ada Reference Manual. In particular, error
7927 messages are generated if a program uses inconsistent versions of a
7928 given unit.
7929
7930 @item
7931 Checks that an acceptable order of elaboration exists for the program
7932 and issues an error message if it cannot find an order of elaboration
7933 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7934
7935 @item
7936 Generates a main program incorporating the given elaboration order.
7937 This program is a small Ada package (body and spec) that
7938 must be subsequently compiled
7939 using the GNAT compiler. The necessary compilation step is usually
7940 performed automatically by @command{gnatlink}. The two most important
7941 functions of this program
7942 are to call the elaboration routines of units in an appropriate order
7943 and to call the main program.
7944
7945 @item
7946 Determines the set of object files required by the given main program.
7947 This information is output in the forms of comments in the generated program,
7948 to be read by the @command{gnatlink} utility used to link the Ada application.
7949 @end enumerate
7950
7951 @node Running gnatbind
7952 @section Running @code{gnatbind}
7953
7954 @noindent
7955 The form of the @code{gnatbind} command is
7956
7957 @smallexample
7958 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7959 @c Expanding @ovar macro inline (explanation in macro def comments)
7960 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7961 @end smallexample
7962
7963 @noindent
7964 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7965 unit body. @code{gnatbind} constructs an Ada
7966 package in two files whose names are
7967 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7968 For example, if given the
7969 parameter @file{hello.ali}, for a main program contained in file
7970 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7971 and @file{b~hello.adb}.
7972
7973 When doing consistency checking, the binder takes into consideration
7974 any source files it can locate. For example, if the binder determines
7975 that the given main program requires the package @code{Pack}, whose
7976 @file{.ALI}
7977 file is @file{pack.ali} and whose corresponding source spec file is
7978 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7979 (using the same search path conventions as previously described for the
7980 @command{gcc} command). If it can locate this source file, it checks that
7981 the time stamps
7982 or source checksums of the source and its references to in @file{ALI} files
7983 match. In other words, any @file{ALI} files that mentions this spec must have
7984 resulted from compiling this version of the source file (or in the case
7985 where the source checksums match, a version close enough that the
7986 difference does not matter).
7987
7988 @cindex Source files, use by binder
7989 The effect of this consistency checking, which includes source files, is
7990 that the binder ensures that the program is consistent with the latest
7991 version of the source files that can be located at bind time. Editing a
7992 source file without compiling files that depend on the source file cause
7993 error messages to be generated by the binder.
7994
7995 For example, suppose you have a main program @file{hello.adb} and a
7996 package @code{P}, from file @file{p.ads} and you perform the following
7997 steps:
7998
7999 @enumerate
8000 @item
8001 Enter @code{gcc -c hello.adb} to compile the main program.
8002
8003 @item
8004 Enter @code{gcc -c p.ads} to compile package @code{P}.
8005
8006 @item
8007 Edit file @file{p.ads}.
8008
8009 @item
8010 Enter @code{gnatbind hello}.
8011 @end enumerate
8012
8013 @noindent
8014 At this point, the file @file{p.ali} contains an out-of-date time stamp
8015 because the file @file{p.ads} has been edited. The attempt at binding
8016 fails, and the binder generates the following error messages:
8017
8018 @smallexample
8019 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8020 error: "p.ads" has been modified and must be recompiled
8021 @end smallexample
8022
8023 @noindent
8024 Now both files must be recompiled as indicated, and then the bind can
8025 succeed, generating a main program. You need not normally be concerned
8026 with the contents of this file, but for reference purposes a sample
8027 binder output file is given in @ref{Example of Binder Output File}.
8028
8029 In most normal usage, the default mode of @command{gnatbind} which is to
8030 generate the main package in Ada, as described in the previous section.
8031 In particular, this means that any Ada programmer can read and understand
8032 the generated main program. It can also be debugged just like any other
8033 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8034 @command{gnatbind} and @command{gnatlink}.
8035
8036 @node Switches for gnatbind
8037 @section Switches for @command{gnatbind}
8038
8039 @noindent
8040 The following switches are available with @code{gnatbind}; details will
8041 be presented in subsequent sections.
8042
8043 @menu
8044 * Consistency-Checking Modes::
8045 * Binder Error Message Control::
8046 * Elaboration Control::
8047 * Output Control::
8048 * Binding with Non-Ada Main Programs::
8049 * Binding Programs with No Main Subprogram::
8050 @end menu
8051
8052 @table @option
8053 @c !sort!
8054
8055 @item --version
8056 @cindex @option{--version} @command{gnatbind}
8057 Display Copyright and version, then exit disregarding all other options.
8058
8059 @item --help
8060 @cindex @option{--help} @command{gnatbind}
8061 If @option{--version} was not used, display usage, then exit disregarding
8062 all other options.
8063
8064 @item -a
8065 @cindex @option{-a} @command{gnatbind}
8066 Indicates that, if supported by the platform, the adainit procedure should
8067 be treated as an initialisation routine by the linker (a constructor). This
8068 is intended to be used by the Project Manager to automatically initialize
8069 shared Stand-Alone Libraries.
8070
8071 @item ^-aO^/OBJECT_SEARCH^
8072 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8073 Specify directory to be searched for ALI files.
8074
8075 @item ^-aI^/SOURCE_SEARCH^
8076 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8077 Specify directory to be searched for source file.
8078
8079 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8080 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8081 Output ALI list (to standard output or to the named file).
8082
8083 @item ^-b^/REPORT_ERRORS=BRIEF^
8084 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8085 Generate brief messages to @file{stderr} even if verbose mode set.
8086
8087 @item ^-c^/NOOUTPUT^
8088 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8089 Check only, no generation of binder output file.
8090
8091 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8092 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8093 This switch can be used to change the default task stack size value
8094 to a specified size @var{nn}, which is expressed in bytes by default, or
8095 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8096 with @var{m}.
8097 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8098 in effect, to completing all task specs with
8099 @smallexample @c ada
8100    pragma Storage_Size (nn);
8101 @end smallexample
8102 When they do not already have such a pragma.
8103
8104 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8105 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8106 This switch can be used to change the default secondary stack size value
8107 to a specified size @var{nn}, which is expressed in bytes by default, or
8108 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8109 with @var{m}.
8110
8111 The secondary stack is used to deal with functions that return a variable
8112 sized result, for example a function returning an unconstrained
8113 String. There are two ways in which this secondary stack is allocated.
8114
8115 For most targets, the secondary stack is growing on demand and is allocated
8116 as a chain of blocks in the heap. The -D option is not very
8117 relevant. It only give some control over the size of the allocated
8118 blocks (whose size is the minimum of the default secondary stack size value,
8119 and the actual size needed for the current allocation request).
8120
8121 For certain targets, notably VxWorks 653,
8122 the secondary stack is allocated by carving off a fixed ratio chunk of the
8123 primary task stack. The -D option is used to define the
8124 size of the environment task's secondary stack.
8125
8126 @item ^-e^/ELABORATION_DEPENDENCIES^
8127 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8128 Output complete list of elaboration-order dependencies.
8129
8130 @item ^-E^/STORE_TRACEBACKS^
8131 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8132 Store tracebacks in exception occurrences when the target supports it.
8133 @ignore
8134 @c The following may get moved to an appendix
8135 This option is currently supported on the following targets:
8136 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8137 @end ignore
8138 See also the packages @code{GNAT.Traceback} and
8139 @code{GNAT.Traceback.Symbolic} for more information.
8140 @ifclear vms
8141 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8142 @command{gcc} option.
8143 @end ifclear
8144
8145 @item ^-F^/FORCE_ELABS_FLAGS^
8146 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8147 Force the checks of elaboration flags. @command{gnatbind} does not normally
8148 generate checks of elaboration flags for the main executable, except when
8149 a Stand-Alone Library is used. However, there are cases when this cannot be
8150 detected by gnatbind. An example is importing an interface of a Stand-Alone
8151 Library through a pragma Import and only specifying through a linker switch
8152 this Stand-Alone Library. This switch is used to guarantee that elaboration
8153 flag checks are generated.
8154
8155 @item ^-h^/HELP^
8156 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8157 Output usage (help) information
8158
8159 @item ^-I^/SEARCH^
8160 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8161 Specify directory to be searched for source and ALI files.
8162
8163 @item ^-I-^/NOCURRENT_DIRECTORY^
8164 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8165 Do not look for sources in the current directory where @code{gnatbind} was
8166 invoked, and do not look for ALI files in the directory containing the
8167 ALI file named in the @code{gnatbind} command line.
8168
8169 @item ^-l^/ORDER_OF_ELABORATION^
8170 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8171 Output chosen elaboration order.
8172
8173 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8174 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8175 Bind the units for library building. In this case the adainit and
8176 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8177 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8178 ^@var{xxx}final^@var{XXX}FINAL^.
8179 Implies ^-n^/NOCOMPILE^.
8180 @ifclear vms
8181 (@xref{GNAT and Libraries}, for more details.)
8182 @end ifclear
8183 @ifset vms
8184 On OpenVMS, these init and final procedures are exported in uppercase
8185 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8186 the init procedure will be "TOTOINIT" and the exported name of the final
8187 procedure will be "TOTOFINAL".
8188 @end ifset
8189
8190 @item ^-Mxyz^/RENAME_MAIN=xyz^
8191 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8192 Rename generated main program from main to xyz. This option is
8193 supported on cross environments only.
8194
8195 @item ^-m^/ERROR_LIMIT=^@var{n}
8196 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8197 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8198 in the range 1..999999. The default value if no switch is
8199 given is 9999. If the number of warnings reaches this limit, then a
8200 message is output and further warnings are suppressed, the bind
8201 continues in this case. If the number of errors reaches this
8202 limit, then a message is output and the bind is abandoned.
8203 A value of zero means that no limit is enforced. The equal
8204 sign is optional.
8205
8206 @ifset unw
8207 Furthermore, under Windows, the sources pointed to by the libraries path
8208 set in the registry are not searched for.
8209 @end ifset
8210
8211 @item ^-n^/NOMAIN^
8212 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8213 No main program.
8214
8215 @item -nostdinc
8216 @cindex @option{-nostdinc} (@command{gnatbind})
8217 Do not look for sources in the system default directory.
8218
8219 @item -nostdlib
8220 @cindex @option{-nostdlib} (@command{gnatbind})
8221 Do not look for library files in the system default directory.
8222
8223 @item --RTS=@var{rts-path}
8224 @cindex @option{--RTS} (@code{gnatbind})
8225 Specifies the default location of the runtime library. Same meaning as the
8226 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8227
8228 @item ^-o ^/OUTPUT=^@var{file}
8229 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8230 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8231 Note that if this option is used, then linking must be done manually,
8232 gnatlink cannot be used.
8233
8234 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8235 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8236 Output object list (to standard output or to the named file).
8237
8238 @item ^-p^/PESSIMISTIC_ELABORATION^
8239 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8240 Pessimistic (worst-case) elaboration order
8241
8242 @item ^-R^-R^
8243 @cindex @option{^-R^-R^} (@command{gnatbind})
8244 Output closure source list.
8245
8246 @item ^-s^/READ_SOURCES=ALL^
8247 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8248 Require all source files to be present.
8249
8250 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8251 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8252 Specifies the value to be used when detecting uninitialized scalar
8253 objects with pragma Initialize_Scalars.
8254 The @var{xxx} ^string specified with the switch^option^ may be either
8255 @itemize @bullet
8256 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8257 @item ``@option{^lo^LOW^}'' for the lowest possible value
8258 @item ``@option{^hi^HIGH^}'' for the highest possible value
8259 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8260 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8261 @end itemize
8262
8263 In addition, you can specify @option{-Sev} to indicate that the value is
8264 to be set at run time. In this case, the program will look for an environment
8265 @cindex GNAT_INIT_SCALARS
8266 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8267 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8268 If no environment variable is found, or if it does not have a valid value,
8269 then the default is @option{in} (invalid values).
8270
8271 @ifclear vms
8272 @item -static
8273 @cindex @option{-static} (@code{gnatbind})
8274 Link against a static GNAT run time.
8275
8276 @item -shared
8277 @cindex @option{-shared} (@code{gnatbind})
8278 Link against a shared GNAT run time when available.
8279 @end ifclear
8280
8281 @item ^-t^/NOTIME_STAMP_CHECK^
8282 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8283 Tolerate time stamp and other consistency errors
8284
8285 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8286 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8287 Set the time slice value to @var{n} milliseconds. If the system supports
8288 the specification of a specific time slice value, then the indicated value
8289 is used. If the system does not support specific time slice values, but
8290 does support some general notion of round-robin scheduling, then any
8291 nonzero value will activate round-robin scheduling.
8292
8293 A value of zero is treated specially. It turns off time
8294 slicing, and in addition, indicates to the tasking run time that the
8295 semantics should match as closely as possible the Annex D
8296 requirements of the Ada RM, and in particular sets the default
8297 scheduling policy to @code{FIFO_Within_Priorities}.
8298
8299 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8300 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8301 Enable dynamic stack usage, with @var{n} results stored and displayed
8302 at program termination. A result is generated when a task
8303 terminates. Results that can't be stored are displayed on the fly, at
8304 task termination. This option is currently not supported on Itanium
8305 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8306
8307 @item ^-v^/REPORT_ERRORS=VERBOSE^
8308 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8309 Verbose mode. Write error messages, header, summary output to
8310 @file{stdout}.
8311
8312 @ifclear vms
8313 @item -w@var{x}
8314 @cindex @option{-w} (@code{gnatbind})
8315 Warning mode (@var{x}=s/e for suppress/treat as error)
8316 @end ifclear
8317
8318 @ifset vms
8319 @item /WARNINGS=NORMAL
8320 @cindex @option{/WARNINGS} (@code{gnatbind})
8321 Normal warnings mode. Warnings are issued but ignored
8322
8323 @item /WARNINGS=SUPPRESS
8324 @cindex @option{/WARNINGS} (@code{gnatbind})
8325 All warning messages are suppressed
8326
8327 @item /WARNINGS=ERROR
8328 @cindex @option{/WARNINGS} (@code{gnatbind})
8329 Warning messages are treated as fatal errors
8330 @end ifset
8331
8332 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8333 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8334 Override default wide character encoding for standard Text_IO files.
8335
8336 @item ^-x^/READ_SOURCES=NONE^
8337 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8338 Exclude source files (check object consistency only).
8339
8340 @ifset vms
8341 @item /READ_SOURCES=AVAILABLE
8342 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8343 Default mode, in which sources are checked for consistency only if
8344 they are available.
8345 @end ifset
8346
8347 @item ^-y^/ENABLE_LEAP_SECONDS^
8348 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8349 Enable leap seconds support in @code{Ada.Calendar} and its children.
8350
8351 @item ^-z^/ZERO_MAIN^
8352 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8353 No main subprogram.
8354 @end table
8355
8356 @ifclear vms
8357 @noindent
8358 You may obtain this listing of switches by running @code{gnatbind} with
8359 no arguments.
8360 @end ifclear
8361
8362 @node Consistency-Checking Modes
8363 @subsection Consistency-Checking Modes
8364
8365 @noindent
8366 As described earlier, by default @code{gnatbind} checks
8367 that object files are consistent with one another and are consistent
8368 with any source files it can locate. The following switches control binder
8369 access to sources.
8370
8371 @table @option
8372 @c !sort!
8373 @item ^-s^/READ_SOURCES=ALL^
8374 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8375 Require source files to be present. In this mode, the binder must be
8376 able to locate all source files that are referenced, in order to check
8377 their consistency. In normal mode, if a source file cannot be located it
8378 is simply ignored. If you specify this switch, a missing source
8379 file is an error.
8380
8381 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8382 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8383 Override default wide character encoding for standard Text_IO files.
8384 Normally the default wide character encoding method used for standard
8385 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8386 the main source input (see description of switch
8387 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8388 use of this switch for the binder (which has the same set of
8389 possible arguments) overrides this default as specified.
8390
8391 @item ^-x^/READ_SOURCES=NONE^
8392 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8393 Exclude source files. In this mode, the binder only checks that ALI
8394 files are consistent with one another. Source files are not accessed.
8395 The binder runs faster in this mode, and there is still a guarantee that
8396 the resulting program is self-consistent.
8397 If a source file has been edited since it was last compiled, and you
8398 specify this switch, the binder will not detect that the object
8399 file is out of date with respect to the source file. Note that this is the
8400 mode that is automatically used by @command{gnatmake} because in this
8401 case the checking against sources has already been performed by
8402 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8403
8404 @ifset vms
8405 @item /READ_SOURCES=AVAILABLE
8406 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8407 This is the default mode in which source files are checked if they are
8408 available, and ignored if they are not available.
8409 @end ifset
8410 @end table
8411
8412 @node Binder Error Message Control
8413 @subsection Binder Error Message Control
8414
8415 @noindent
8416 The following switches provide control over the generation of error
8417 messages from the binder:
8418
8419 @table @option
8420 @c !sort!
8421 @item ^-v^/REPORT_ERRORS=VERBOSE^
8422 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8423 Verbose mode. In the normal mode, brief error messages are generated to
8424 @file{stderr}. If this switch is present, a header is written
8425 to @file{stdout} and any error messages are directed to @file{stdout}.
8426 All that is written to @file{stderr} is a brief summary message.
8427
8428 @item ^-b^/REPORT_ERRORS=BRIEF^
8429 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8430 Generate brief error messages to @file{stderr} even if verbose mode is
8431 specified. This is relevant only when used with the
8432 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8433
8434 @ifclear vms
8435 @item -m@var{n}
8436 @cindex @option{-m} (@code{gnatbind})
8437 Limits the number of error messages to @var{n}, a decimal integer in the
8438 range 1-999. The binder terminates immediately if this limit is reached.
8439
8440 @item -M@var{xxx}
8441 @cindex @option{-M} (@code{gnatbind})
8442 Renames the generated main program from @code{main} to @code{xxx}.
8443 This is useful in the case of some cross-building environments, where
8444 the actual main program is separate from the one generated
8445 by @code{gnatbind}.
8446 @end ifclear
8447
8448 @item ^-ws^/WARNINGS=SUPPRESS^
8449 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8450 @cindex Warnings
8451 Suppress all warning messages.
8452
8453 @item ^-we^/WARNINGS=ERROR^
8454 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8455 Treat any warning messages as fatal errors.
8456
8457 @ifset vms
8458 @item /WARNINGS=NORMAL
8459 Standard mode with warnings generated, but warnings do not get treated
8460 as errors.
8461 @end ifset
8462
8463 @item ^-t^/NOTIME_STAMP_CHECK^
8464 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8465 @cindex Time stamp checks, in binder
8466 @cindex Binder consistency checks
8467 @cindex Consistency checks, in binder
8468 The binder performs a number of consistency checks including:
8469
8470 @itemize @bullet
8471 @item
8472 Check that time stamps of a given source unit are consistent
8473 @item
8474 Check that checksums of a given source unit are consistent
8475 @item
8476 Check that consistent versions of @code{GNAT} were used for compilation
8477 @item
8478 Check consistency of configuration pragmas as required
8479 @end itemize
8480
8481 @noindent
8482 Normally failure of such checks, in accordance with the consistency
8483 requirements of the Ada Reference Manual, causes error messages to be
8484 generated which abort the binder and prevent the output of a binder
8485 file and subsequent link to obtain an executable.
8486
8487 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8488 into warnings, so that
8489 binding and linking can continue to completion even in the presence of such
8490 errors. The result may be a failed link (due to missing symbols), or a
8491 non-functional executable which has undefined semantics.
8492 @emph{This means that
8493 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8494 with extreme care.}
8495 @end table
8496
8497 @node Elaboration Control
8498 @subsection Elaboration Control
8499
8500 @noindent
8501 The following switches provide additional control over the elaboration
8502 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8503
8504 @table @option
8505 @item ^-p^/PESSIMISTIC_ELABORATION^
8506 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8507 Normally the binder attempts to choose an elaboration order that is
8508 likely to minimize the likelihood of an elaboration order error resulting
8509 in raising a @code{Program_Error} exception. This switch reverses the
8510 action of the binder, and requests that it deliberately choose an order
8511 that is likely to maximize the likelihood of an elaboration error.
8512 This is useful in ensuring portability and avoiding dependence on
8513 accidental fortuitous elaboration ordering.
8514
8515 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8516 switch if dynamic
8517 elaboration checking is used (@option{-gnatE} switch used for compilation).
8518 This is because in the default static elaboration mode, all necessary
8519 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8520 These implicit pragmas are still respected by the binder in
8521 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8522 safe elaboration order is assured.
8523 @end table
8524
8525 @node Output Control
8526 @subsection Output Control
8527
8528 @noindent
8529 The following switches allow additional control over the output
8530 generated by the binder.
8531
8532 @table @option
8533 @c !sort!
8534
8535 @item ^-c^/NOOUTPUT^
8536 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8537 Check only. Do not generate the binder output file. In this mode the
8538 binder performs all error checks but does not generate an output file.
8539
8540 @item ^-e^/ELABORATION_DEPENDENCIES^
8541 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8542 Output complete list of elaboration-order dependencies, showing the
8543 reason for each dependency. This output can be rather extensive but may
8544 be useful in diagnosing problems with elaboration order. The output is
8545 written to @file{stdout}.
8546
8547 @item ^-h^/HELP^
8548 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8549 Output usage information. The output is written to @file{stdout}.
8550
8551 @item ^-K^/LINKER_OPTION_LIST^
8552 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8553 Output linker options to @file{stdout}. Includes library search paths,
8554 contents of pragmas Ident and Linker_Options, and libraries added
8555 by @code{gnatbind}.
8556
8557 @item ^-l^/ORDER_OF_ELABORATION^
8558 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8559 Output chosen elaboration order. The output is written to @file{stdout}.
8560
8561 @item ^-O^/OBJECT_LIST^
8562 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8563 Output full names of all the object files that must be linked to provide
8564 the Ada component of the program. The output is written to @file{stdout}.
8565 This list includes the files explicitly supplied and referenced by the user
8566 as well as implicitly referenced run-time unit files. The latter are
8567 omitted if the corresponding units reside in shared libraries. The
8568 directory names for the run-time units depend on the system configuration.
8569
8570 @item ^-o ^/OUTPUT=^@var{file}
8571 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8572 Set name of output file to @var{file} instead of the normal
8573 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8574 binder generated body filename.
8575 Note that if this option is used, then linking must be done manually.
8576 It is not possible to use gnatlink in this case, since it cannot locate
8577 the binder file.
8578
8579 @item ^-r^/RESTRICTION_LIST^
8580 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8581 Generate list of @code{pragma Restrictions} that could be applied to
8582 the current unit. This is useful for code audit purposes, and also may
8583 be used to improve code generation in some cases.
8584
8585 @end table
8586
8587 @node Binding with Non-Ada Main Programs
8588 @subsection Binding with Non-Ada Main Programs
8589
8590 @noindent
8591 In our description so far we have assumed that the main
8592 program is in Ada, and that the task of the binder is to generate a
8593 corresponding function @code{main} that invokes this Ada main
8594 program. GNAT also supports the building of executable programs where
8595 the main program is not in Ada, but some of the called routines are
8596 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8597 The following switch is used in this situation:
8598
8599 @table @option
8600 @item ^-n^/NOMAIN^
8601 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8602 No main program. The main program is not in Ada.
8603 @end table
8604
8605 @noindent
8606 In this case, most of the functions of the binder are still required,
8607 but instead of generating a main program, the binder generates a file
8608 containing the following callable routines:
8609
8610 @table @code
8611 @item adainit
8612 @findex adainit
8613 You must call this routine to initialize the Ada part of the program by
8614 calling the necessary elaboration routines. A call to @code{adainit} is
8615 required before the first call to an Ada subprogram.
8616
8617 Note that it is assumed that the basic execution environment must be setup
8618 to be appropriate for Ada execution at the point where the first Ada
8619 subprogram is called. In particular, if the Ada code will do any
8620 floating-point operations, then the FPU must be setup in an appropriate
8621 manner. For the case of the x86, for example, full precision mode is
8622 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8623 that the FPU is in the right state.
8624
8625 @item adafinal
8626 @findex adafinal
8627 You must call this routine to perform any library-level finalization
8628 required by the Ada subprograms. A call to @code{adafinal} is required
8629 after the last call to an Ada subprogram, and before the program
8630 terminates.
8631 @end table
8632
8633 @noindent
8634 If the @option{^-n^/NOMAIN^} switch
8635 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8636 @cindex Binder, multiple input files
8637 is given, more than one ALI file may appear on
8638 the command line for @code{gnatbind}. The normal @dfn{closure}
8639 calculation is performed for each of the specified units. Calculating
8640 the closure means finding out the set of units involved by tracing
8641 @code{with} references. The reason it is necessary to be able to
8642 specify more than one ALI file is that a given program may invoke two or
8643 more quite separate groups of Ada units.
8644
8645 The binder takes the name of its output file from the last specified ALI
8646 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8647 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8648 The output is an Ada unit in source form that can be compiled with GNAT.
8649 This compilation occurs automatically as part of the @command{gnatlink}
8650 processing.
8651
8652 Currently the GNAT run time requires a FPU using 80 bits mode
8653 precision. Under targets where this is not the default it is required to
8654 call GNAT.Float_Control.Reset before using floating point numbers (this
8655 include float computation, float input and output) in the Ada code. A
8656 side effect is that this could be the wrong mode for the foreign code
8657 where floating point computation could be broken after this call.
8658
8659 @node Binding Programs with No Main Subprogram
8660 @subsection Binding Programs with No Main Subprogram
8661
8662 @noindent
8663 It is possible to have an Ada program which does not have a main
8664 subprogram. This program will call the elaboration routines of all the
8665 packages, then the finalization routines.
8666
8667 The following switch is used to bind programs organized in this manner:
8668
8669 @table @option
8670 @item ^-z^/ZERO_MAIN^
8671 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8672 Normally the binder checks that the unit name given on the command line
8673 corresponds to a suitable main subprogram. When this switch is used,
8674 a list of ALI files can be given, and the execution of the program
8675 consists of elaboration of these units in an appropriate order. Note
8676 that the default wide character encoding method for standard Text_IO
8677 files is always set to Brackets if this switch is set (you can use
8678 the binder switch
8679 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8680 @end table
8681
8682 @node Command-Line Access
8683 @section Command-Line Access
8684
8685 @noindent
8686 The package @code{Ada.Command_Line} provides access to the command-line
8687 arguments and program name. In order for this interface to operate
8688 correctly, the two variables
8689
8690 @smallexample
8691 @group
8692 int gnat_argc;
8693 char **gnat_argv;
8694 @end group
8695 @end smallexample
8696
8697 @noindent
8698 @findex gnat_argv
8699 @findex gnat_argc
8700 are declared in one of the GNAT library routines. These variables must
8701 be set from the actual @code{argc} and @code{argv} values passed to the
8702 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8703 generates the C main program to automatically set these variables.
8704 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8705 set these variables. If they are not set, the procedures in
8706 @code{Ada.Command_Line} will not be available, and any attempt to use
8707 them will raise @code{Constraint_Error}. If command line access is
8708 required, your main program must set @code{gnat_argc} and
8709 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8710 it.
8711
8712 @node Search Paths for gnatbind
8713 @section Search Paths for @code{gnatbind}
8714
8715 @noindent
8716 The binder takes the name of an ALI file as its argument and needs to
8717 locate source files as well as other ALI files to verify object consistency.
8718
8719 For source files, it follows exactly the same search rules as @command{gcc}
8720 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8721 directories searched are:
8722
8723 @enumerate
8724 @item
8725 The directory containing the ALI file named in the command line, unless
8726 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8727
8728 @item
8729 All directories specified by @option{^-I^/SEARCH^}
8730 switches on the @code{gnatbind}
8731 command line, in the order given.
8732
8733 @item
8734 @findex ADA_PRJ_OBJECTS_FILE
8735 Each of the directories listed in the text file whose name is given
8736 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8737
8738 @noindent
8739 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8740 driver when project files are used. It should not normally be set
8741 by other means.
8742
8743 @item
8744 @findex ADA_OBJECTS_PATH
8745 Each of the directories listed in the value of the
8746 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8747 @ifset unw
8748 Construct this value
8749 exactly as the @env{PATH} environment variable: a list of directory
8750 names separated by colons (semicolons when working with the NT version
8751 of GNAT).
8752 @end ifset
8753 @ifset vms
8754 Normally, define this value as a logical name containing a comma separated
8755 list of directory names.
8756
8757 This variable can also be defined by means of an environment string
8758 (an argument to the HP C exec* set of functions).
8759
8760 Logical Name:
8761 @smallexample
8762 DEFINE ANOTHER_PATH FOO:[BAG]
8763 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8764 @end smallexample
8765
8766 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8767 first, followed by the standard Ada
8768 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8769 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8770 (Text_IO, Sequential_IO, etc)
8771 instead of the standard Ada packages. Thus, in order to get the standard Ada
8772 packages by default, ADA_OBJECTS_PATH must be redefined.
8773 @end ifset
8774
8775 @item
8776 The content of the @file{ada_object_path} file which is part of the GNAT
8777 installation tree and is used to store standard libraries such as the
8778 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8779 specified.
8780 @ifclear vms
8781 @ref{Installing a library}
8782 @end ifclear
8783 @end enumerate
8784
8785 @noindent
8786 In the binder the switch @option{^-I^/SEARCH^}
8787 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8788 is used to specify both source and
8789 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8790 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8791 instead if you want to specify
8792 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8793 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8794 if you want to specify library paths
8795 only. This means that for the binder
8796 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8797 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8798 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8799 The binder generates the bind file (a C language source file) in the
8800 current working directory.
8801
8802 @findex Ada
8803 @findex System
8804 @findex Interfaces
8805 @findex GNAT
8806 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8807 children make up the GNAT Run-Time Library, together with the package
8808 GNAT and its children, which contain a set of useful additional
8809 library functions provided by GNAT. The sources for these units are
8810 needed by the compiler and are kept together in one directory. The ALI
8811 files and object files generated by compiling the RTL are needed by the
8812 binder and the linker and are kept together in one directory, typically
8813 different from the directory containing the sources. In a normal
8814 installation, you need not specify these directory names when compiling
8815 or binding. Either the environment variables or the built-in defaults
8816 cause these files to be found.
8817
8818 Besides simplifying access to the RTL, a major use of search paths is
8819 in compiling sources from multiple directories. This can make
8820 development environments much more flexible.
8821
8822 @node Examples of gnatbind Usage
8823 @section Examples of @code{gnatbind} Usage
8824
8825 @noindent
8826 This section contains a number of examples of using the GNAT binding
8827 utility @code{gnatbind}.
8828
8829 @table @code
8830 @item gnatbind hello
8831 The main program @code{Hello} (source program in @file{hello.adb}) is
8832 bound using the standard switch settings. The generated main program is
8833 @file{b~hello.adb}. This is the normal, default use of the binder.
8834
8835 @ifclear vms
8836 @item gnatbind hello -o mainprog.adb
8837 @end ifclear
8838 @ifset vms
8839 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8840 @end ifset
8841 The main program @code{Hello} (source program in @file{hello.adb}) is
8842 bound using the standard switch settings. The generated main program is
8843 @file{mainprog.adb} with the associated spec in
8844 @file{mainprog.ads}. Note that you must specify the body here not the
8845 spec. Note that if this option is used, then linking must be done manually,
8846 since gnatlink will not be able to find the generated file.
8847 @end table
8848
8849 @c ------------------------------------
8850 @node Linking Using gnatlink
8851 @chapter Linking Using @command{gnatlink}
8852 @c ------------------------------------
8853 @findex gnatlink
8854
8855 @noindent
8856 This chapter discusses @command{gnatlink}, a tool that links
8857 an Ada program and builds an executable file. This utility
8858 invokes the system linker ^(via the @command{gcc} command)^^
8859 with a correct list of object files and library references.
8860 @command{gnatlink} automatically determines the list of files and
8861 references for the Ada part of a program. It uses the binder file
8862 generated by the @command{gnatbind} to determine this list.
8863
8864 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8865 driver (see @ref{The GNAT Driver and Project Files}).
8866
8867 @menu
8868 * Running gnatlink::
8869 * Switches for gnatlink::
8870 @end menu
8871
8872 @node Running gnatlink
8873 @section Running @command{gnatlink}
8874
8875 @noindent
8876 The form of the @command{gnatlink} command is
8877
8878 @smallexample
8879 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8880 @c            @ovar{non-Ada objects} @ovar{linker options}
8881 @c Expanding @ovar macro inline (explanation in macro def comments)
8882 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8883            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8884
8885 @end smallexample
8886
8887 @noindent
8888 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8889 non-Ada objects
8890 or linker options) may be in any order, provided that no non-Ada object may
8891 be mistaken for a main @file{ALI} file.
8892 Any file name @file{F} without the @file{.ali}
8893 extension will be taken as the main @file{ALI} file if a file exists
8894 whose name is the concatenation of @file{F} and @file{.ali}.
8895
8896 @noindent
8897 @file{@var{mainprog}.ali} references the ALI file of the main program.
8898 The @file{.ali} extension of this file can be omitted. From this
8899 reference, @command{gnatlink} locates the corresponding binder file
8900 @file{b~@var{mainprog}.adb} and, using the information in this file along
8901 with the list of non-Ada objects and linker options, constructs a
8902 linker command file to create the executable.
8903
8904 The arguments other than the @command{gnatlink} switches and the main
8905 @file{ALI} file are passed to the linker uninterpreted.
8906 They typically include the names of
8907 object files for units written in other languages than Ada and any library
8908 references required to resolve references in any of these foreign language
8909 units, or in @code{Import} pragmas in any Ada units.
8910
8911 @var{linker options} is an optional list of linker specific
8912 switches.
8913 The default linker called by gnatlink is @command{gcc} which in
8914 turn calls the appropriate system linker.
8915 Standard options for the linker such as @option{-lmy_lib} or
8916 @option{-Ldir} can be added as is.
8917 For options that are not recognized by
8918 @command{gcc} as linker options, use the @command{gcc} switches
8919 @option{-Xlinker} or @option{-Wl,}.
8920 Refer to the GCC documentation for
8921 details. Here is an example showing how to generate a linker map:
8922
8923 @smallexample
8924 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8925 @end smallexample
8926
8927 Using @var{linker options} it is possible to set the program stack and
8928 heap size.
8929 @ifset unw
8930 See @ref{Setting Stack Size from gnatlink} and
8931 @ref{Setting Heap Size from gnatlink}.
8932 @end ifset
8933
8934 @command{gnatlink} determines the list of objects required by the Ada
8935 program and prepends them to the list of objects passed to the linker.
8936 @command{gnatlink} also gathers any arguments set by the use of
8937 @code{pragma Linker_Options} and adds them to the list of arguments
8938 presented to the linker.
8939
8940 @ifset vms
8941 @command{gnatlink} accepts the following types of extra files on the command
8942 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8943 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8944 handled according to their extension.
8945 @end ifset
8946
8947 @node Switches for gnatlink
8948 @section Switches for @command{gnatlink}
8949
8950 @noindent
8951 The following switches are available with the @command{gnatlink} utility:
8952
8953 @table @option
8954 @c !sort!
8955
8956 @item --version
8957 @cindex @option{--version} @command{gnatlink}
8958 Display Copyright and version, then exit disregarding all other options.
8959
8960 @item --help
8961 @cindex @option{--help} @command{gnatlink}
8962 If @option{--version} was not used, display usage, then exit disregarding
8963 all other options.
8964
8965 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8966 @cindex Command line length
8967 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8968 On some targets, the command line length is limited, and @command{gnatlink}
8969 will generate a separate file for the linker if the list of object files
8970 is too long.
8971 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8972 to be generated even if
8973 the limit is not exceeded. This is useful in some cases to deal with
8974 special situations where the command line length is exceeded.
8975
8976 @item ^-g^/DEBUG^
8977 @cindex Debugging information, including
8978 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8979 The option to include debugging information causes the Ada bind file (in
8980 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8981 @option{^-g^/DEBUG^}.
8982 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8983 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8984 Without @option{^-g^/DEBUG^}, the binder removes these files by
8985 default. The same procedure apply if a C bind file was generated using
8986 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8987 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8988
8989 @item ^-n^/NOCOMPILE^
8990 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8991 Do not compile the file generated by the binder. This may be used when
8992 a link is rerun with different options, but there is no need to recompile
8993 the binder file.
8994
8995 @item ^-v^/VERBOSE^
8996 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8997 Causes additional information to be output, including a full list of the
8998 included object files. This switch option is most useful when you want
8999 to see what set of object files are being used in the link step.
9000
9001 @item ^-v -v^/VERBOSE/VERBOSE^
9002 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9003 Very verbose mode. Requests that the compiler operate in verbose mode when
9004 it compiles the binder file, and that the system linker run in verbose mode.
9005
9006 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9007 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9008 @var{exec-name} specifies an alternate name for the generated
9009 executable program. If this switch is omitted, the executable has the same
9010 name as the main unit. For example, @code{gnatlink try.ali} creates
9011 an executable called @file{^try^TRY.EXE^}.
9012
9013 @ifclear vms
9014 @item -b @var{target}
9015 @cindex @option{-b} (@command{gnatlink})
9016 Compile your program to run on @var{target}, which is the name of a
9017 system configuration. You must have a GNAT cross-compiler built if
9018 @var{target} is not the same as your host system.
9019
9020 @item -B@var{dir}
9021 @cindex @option{-B} (@command{gnatlink})
9022 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9023 from @var{dir} instead of the default location. Only use this switch
9024 when multiple versions of the GNAT compiler are available.
9025 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9026 for further details. You would normally use the @option{-b} or
9027 @option{-V} switch instead.
9028
9029 @item --GCC=@var{compiler_name}
9030 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9031 Program used for compiling the binder file. The default is
9032 @command{gcc}. You need to use quotes around @var{compiler_name} if
9033 @code{compiler_name} contains spaces or other separator characters.
9034 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9035 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9036 inserted after your command name. Thus in the above example the compiler
9037 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9038 A limitation of this syntax is that the name and path name of the executable
9039 itself must not include any embedded spaces. If the compiler executable is
9040 different from the default one (gcc or <prefix>-gcc), then the back-end
9041 switches in the ALI file are not used to compile the binder generated source.
9042 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9043 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9044 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9045 is taken into account. However, all the additional switches are also taken
9046 into account. Thus,
9047 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9048 @option{--GCC="bar -x -y -z -t"}.
9049
9050 @item --LINK=@var{name}
9051 @cindex @option{--LINK=} (@command{gnatlink})
9052 @var{name} is the name of the linker to be invoked. This is especially
9053 useful in mixed language programs since languages such as C++ require
9054 their own linker to be used. When this switch is omitted, the default
9055 name for the linker is @command{gcc}. When this switch is used, the
9056 specified linker is called instead of @command{gcc} with exactly the same
9057 parameters that would have been passed to @command{gcc} so if the desired
9058 linker requires different parameters it is necessary to use a wrapper
9059 script that massages the parameters before invoking the real linker. It
9060 may be useful to control the exact invocation by using the verbose
9061 switch.
9062
9063 @end ifclear
9064
9065 @ifset vms
9066 @item /DEBUG=TRACEBACK
9067 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9068 This qualifier causes sufficient information to be included in the
9069 executable file to allow a traceback, but does not include the full
9070 symbol information needed by the debugger.
9071
9072 @item /IDENTIFICATION="<string>"
9073 @code{"<string>"} specifies the string to be stored in the image file
9074 identification field in the image header.
9075 It overrides any pragma @code{Ident} specified string.
9076
9077 @item /NOINHIBIT-EXEC
9078 Generate the executable file even if there are linker warnings.
9079
9080 @item /NOSTART_FILES
9081 Don't link in the object file containing the ``main'' transfer address.
9082 Used when linking with a foreign language main program compiled with an
9083 HP compiler.
9084
9085 @item /STATIC
9086 Prefer linking with object libraries over sharable images, even without
9087 /DEBUG.
9088 @end ifset
9089
9090 @end table
9091
9092 @node The GNAT Make Program gnatmake
9093 @chapter The GNAT Make Program @command{gnatmake}
9094 @findex gnatmake
9095
9096 @menu
9097 * Running gnatmake::
9098 * Switches for gnatmake::
9099 * Mode Switches for gnatmake::
9100 * Notes on the Command Line::
9101 * How gnatmake Works::
9102 * Examples of gnatmake Usage::
9103 @end menu
9104 @noindent
9105 A typical development cycle when working on an Ada program consists of
9106 the following steps:
9107
9108 @enumerate
9109 @item
9110 Edit some sources to fix bugs.
9111
9112 @item
9113 Add enhancements.
9114
9115 @item
9116 Compile all sources affected.
9117
9118 @item
9119 Rebind and relink.
9120
9121 @item
9122 Test.
9123 @end enumerate
9124
9125 @noindent
9126 The third step can be tricky, because not only do the modified files
9127 @cindex Dependency rules
9128 have to be compiled, but any files depending on these files must also be
9129 recompiled. The dependency rules in Ada can be quite complex, especially
9130 in the presence of overloading, @code{use} clauses, generics and inlined
9131 subprograms.
9132
9133 @command{gnatmake} automatically takes care of the third and fourth steps
9134 of this process. It determines which sources need to be compiled,
9135 compiles them, and binds and links the resulting object files.
9136
9137 Unlike some other Ada make programs, the dependencies are always
9138 accurately recomputed from the new sources. The source based approach of
9139 the GNAT compilation model makes this possible. This means that if
9140 changes to the source program cause corresponding changes in
9141 dependencies, they will always be tracked exactly correctly by
9142 @command{gnatmake}.
9143
9144 @node Running gnatmake
9145 @section Running @command{gnatmake}
9146
9147 @noindent
9148 The usual form of the @command{gnatmake} command is
9149
9150 @smallexample
9151 @c $ gnatmake @ovar{switches} @var{file_name}
9152 @c       @ovar{file_names} @ovar{mode_switches}
9153 @c Expanding @ovar macro inline (explanation in macro def comments)
9154 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9155       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9156 @end smallexample
9157
9158 @noindent
9159 The only required argument is one @var{file_name}, which specifies
9160 a compilation unit that is a main program. Several @var{file_names} can be
9161 specified: this will result in several executables being built.
9162 If @code{switches} are present, they can be placed before the first
9163 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9164 If @var{mode_switches} are present, they must always be placed after
9165 the last @var{file_name} and all @code{switches}.
9166
9167 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9168 extension may be omitted from the @var{file_name} arguments. However, if
9169 you are using non-standard extensions, then it is required that the
9170 extension be given. A relative or absolute directory path can be
9171 specified in a @var{file_name}, in which case, the input source file will
9172 be searched for in the specified directory only. Otherwise, the input
9173 source file will first be searched in the directory where
9174 @command{gnatmake} was invoked and if it is not found, it will be search on
9175 the source path of the compiler as described in
9176 @ref{Search Paths and the Run-Time Library (RTL)}.
9177
9178 All @command{gnatmake} output (except when you specify
9179 @option{^-M^/DEPENDENCIES_LIST^}) is to
9180 @file{stderr}. The output produced by the
9181 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9182 @file{stdout}.
9183
9184 @node Switches for gnatmake
9185 @section Switches for @command{gnatmake}
9186
9187 @noindent
9188 You may specify any of the following switches to @command{gnatmake}:
9189
9190 @table @option
9191 @c !sort!
9192
9193 @item --version
9194 @cindex @option{--version} @command{gnatmake}
9195 Display Copyright and version, then exit disregarding all other options.
9196
9197 @item --help
9198 @cindex @option{--help} @command{gnatmake}
9199 If @option{--version} was not used, display usage, then exit disregarding
9200 all other options.
9201
9202 @ifclear vms
9203 @item --GCC=@var{compiler_name}
9204 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9205 Program used for compiling. The default is `@command{gcc}'. You need to use
9206 quotes around @var{compiler_name} if @code{compiler_name} contains
9207 spaces or other separator characters. As an example @option{--GCC="foo -x
9208 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9209 compiler. A limitation of this syntax is that the name and path name of
9210 the executable itself must not include any embedded spaces. Note that
9211 switch @option{-c} is always inserted after your command name. Thus in the
9212 above example the compiler command that will be used by @command{gnatmake}
9213 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9214 used, only the last @var{compiler_name} is taken into account. However,
9215 all the additional switches are also taken into account. Thus,
9216 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9217 @option{--GCC="bar -x -y -z -t"}.
9218
9219 @item --GNATBIND=@var{binder_name}
9220 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9221 Program used for binding. The default is `@code{gnatbind}'. You need to
9222 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9223 or other separator characters. As an example @option{--GNATBIND="bar -x
9224 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9225 binder. Binder switches that are normally appended by @command{gnatmake}
9226 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9227 A limitation of this syntax is that the name and path name of the executable
9228 itself must not include any embedded spaces.
9229
9230 @item --GNATLINK=@var{linker_name}
9231 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9232 Program used for linking. The default is `@command{gnatlink}'. You need to
9233 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9234 or other separator characters. As an example @option{--GNATLINK="lan -x
9235 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9236 linker. Linker switches that are normally appended by @command{gnatmake} to
9237 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9238 A limitation of this syntax is that the name and path name of the executable
9239 itself must not include any embedded spaces.
9240
9241 @end ifclear
9242
9243 @item ^--subdirs^/SUBDIRS^=subdir
9244 Actual object directory of each project file is the subdirectory subdir of the
9245 object directory specified or defauted in the project file.
9246
9247 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9248 By default, shared library projects are not allowed to import static library
9249 projects. When this switch is used on the command line, this restriction is
9250 relaxed.
9251
9252 @item ^-a^/ALL_FILES^
9253 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9254 Consider all files in the make process, even the GNAT internal system
9255 files (for example, the predefined Ada library files), as well as any
9256 locked files. Locked files are files whose ALI file is write-protected.
9257 By default,
9258 @command{gnatmake} does not check these files,
9259 because the assumption is that the GNAT internal files are properly up
9260 to date, and also that any write protected ALI files have been properly
9261 installed. Note that if there is an installation problem, such that one
9262 of these files is not up to date, it will be properly caught by the
9263 binder.
9264 You may have to specify this switch if you are working on GNAT
9265 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9266 in conjunction with @option{^-f^/FORCE_COMPILE^}
9267 if you need to recompile an entire application,
9268 including run-time files, using special configuration pragmas,
9269 such as a @code{Normalize_Scalars} pragma.
9270
9271 By default
9272 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9273 internal files with
9274 @ifclear vms
9275 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9276 @end ifclear
9277 @ifset vms
9278 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9279 @end ifset
9280
9281 @item ^-b^/ACTIONS=BIND^
9282 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9283 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9284 compilation and binding, but no link.
9285 Can be combined with @option{^-l^/ACTIONS=LINK^}
9286 to do binding and linking. When not combined with
9287 @option{^-c^/ACTIONS=COMPILE^}
9288 all the units in the closure of the main program must have been previously
9289 compiled and must be up to date. The root unit specified by @var{file_name}
9290 may be given without extension, with the source extension or, if no GNAT
9291 Project File is specified, with the ALI file extension.
9292
9293 @item ^-c^/ACTIONS=COMPILE^
9294 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9295 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9296 is also specified. Do not perform linking, except if both
9297 @option{^-b^/ACTIONS=BIND^} and
9298 @option{^-l^/ACTIONS=LINK^} are also specified.
9299 If the root unit specified by @var{file_name} is not a main unit, this is the
9300 default. Otherwise @command{gnatmake} will attempt binding and linking
9301 unless all objects are up to date and the executable is more recent than
9302 the objects.
9303
9304 @item ^-C^/MAPPING^
9305 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9306 Use a temporary mapping file. A mapping file is a way to communicate
9307 to the compiler two mappings: from unit names to file names (without
9308 any directory information) and from file names to path names (with
9309 full directory information). A mapping file can make the compiler's
9310 file searches faster, especially if there are many source directories,
9311 or the sources are read over a slow network connection. If
9312 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9313 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9314 is initially populated based on the project file. If
9315 @option{^-C^/MAPPING^} is used without
9316 @option{^-P^/PROJECT_FILE^},
9317 the mapping file is initially empty. Each invocation of the compiler
9318 will add any newly accessed sources to the mapping file.
9319
9320 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9321 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9322 Use a specific mapping file. The file, specified as a path name (absolute or
9323 relative) by this switch, should already exist, otherwise the switch is
9324 ineffective. The specified mapping file will be communicated to the compiler.
9325 This switch is not compatible with a project file
9326 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9327 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9328
9329 @item ^-d^/DISPLAY_PROGRESS^
9330 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9331 Display progress for each source, up to date or not, as a single line
9332
9333 @smallexample
9334 completed x out of y (zz%)
9335 @end smallexample
9336
9337 If the file needs to be compiled this is displayed after the invocation of
9338 the compiler. These lines are displayed even in quiet output mode.
9339
9340 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9341 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9342 Put all object files and ALI file in directory @var{dir}.
9343 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9344 and ALI files go in the current working directory.
9345
9346 This switch cannot be used when using a project file.
9347
9348 @ifclear vms
9349 @item -eL
9350 @cindex @option{-eL} (@command{gnatmake})
9351 @cindex symbolic links
9352 Follow all symbolic links when processing project files.
9353 This should be used if your project uses symbolic links for files or
9354 directories, but is not needed in other cases.
9355
9356 @cindex naming scheme
9357 This also assumes that no directory matches the naming scheme for files (for
9358 instance that you do not have a directory called "sources.ads" when using the
9359 default GNAT naming scheme).
9360
9361 When you do not have to use this switch (ie by default), gnatmake is able to
9362 save a lot of system calls (several per source file and object file), which
9363 can result in a significant speed up to load and manipulate a project file,
9364 especially when using source files from a remote system.
9365
9366 @end ifclear
9367
9368 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9369 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9370 Output the commands for the compiler, the binder and the linker
9371 on ^standard output^SYS$OUTPUT^,
9372 instead of ^standard error^SYS$ERROR^.
9373
9374 @item ^-f^/FORCE_COMPILE^
9375 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9376 Force recompilations. Recompile all sources, even though some object
9377 files may be up to date, but don't recompile predefined or GNAT internal
9378 files or locked files (files with a write-protected ALI file),
9379 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9380
9381 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9382 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9383 When using project files, if some errors or warnings are detected during
9384 parsing and verbose mode is not in effect (no use of switch
9385 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9386 file, rather than its simple file name.
9387
9388 @item ^-g^/DEBUG^
9389 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9390 Enable debugging. This switch is simply passed to the compiler and to the
9391 linker.
9392
9393 @item ^-i^/IN_PLACE^
9394 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9395 In normal mode, @command{gnatmake} compiles all object files and ALI files
9396 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9397 then instead object files and ALI files that already exist are overwritten
9398 in place. This means that once a large project is organized into separate
9399 directories in the desired manner, then @command{gnatmake} will automatically
9400 maintain and update this organization. If no ALI files are found on the
9401 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9402 the new object and ALI files are created in the
9403 directory containing the source being compiled. If another organization
9404 is desired, where objects and sources are kept in different directories,
9405 a useful technique is to create dummy ALI files in the desired directories.
9406 When detecting such a dummy file, @command{gnatmake} will be forced to
9407 recompile the corresponding source file, and it will be put the resulting
9408 object and ALI files in the directory where it found the dummy file.
9409
9410 @item ^-j^/PROCESSES=^@var{n}
9411 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9412 @cindex Parallel make
9413 Use @var{n} processes to carry out the (re)compilations. On a
9414 multiprocessor machine compilations will occur in parallel. In the
9415 event of compilation errors, messages from various compilations might
9416 get interspersed (but @command{gnatmake} will give you the full ordered
9417 list of failing compiles at the end). If this is problematic, rerun
9418 the make process with n set to 1 to get a clean list of messages.
9419
9420 @item ^-k^/CONTINUE_ON_ERROR^
9421 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9422 Keep going. Continue as much as possible after a compilation error. To
9423 ease the programmer's task in case of compilation errors, the list of
9424 sources for which the compile fails is given when @command{gnatmake}
9425 terminates.
9426
9427 If @command{gnatmake} is invoked with several @file{file_names} and with this
9428 switch, if there are compilation errors when building an executable,
9429 @command{gnatmake} will not attempt to build the following executables.
9430
9431 @item ^-l^/ACTIONS=LINK^
9432 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9433 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9434 and linking. Linking will not be performed if combined with
9435 @option{^-c^/ACTIONS=COMPILE^}
9436 but not with @option{^-b^/ACTIONS=BIND^}.
9437 When not combined with @option{^-b^/ACTIONS=BIND^}
9438 all the units in the closure of the main program must have been previously
9439 compiled and must be up to date, and the main program needs to have been bound.
9440 The root unit specified by @var{file_name}
9441 may be given without extension, with the source extension or, if no GNAT
9442 Project File is specified, with the ALI file extension.
9443
9444 @item ^-m^/MINIMAL_RECOMPILATION^
9445 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9446 Specify that the minimum necessary amount of recompilations
9447 be performed. In this mode @command{gnatmake} ignores time
9448 stamp differences when the only
9449 modifications to a source file consist in adding/removing comments,
9450 empty lines, spaces or tabs. This means that if you have changed the
9451 comments in a source file or have simply reformatted it, using this
9452 switch will tell @command{gnatmake} not to recompile files that depend on it
9453 (provided other sources on which these files depend have undergone no
9454 semantic modifications). Note that the debugging information may be
9455 out of date with respect to the sources if the @option{-m} switch causes
9456 a compilation to be switched, so the use of this switch represents a
9457 trade-off between compilation time and accurate debugging information.
9458
9459 @item ^-M^/DEPENDENCIES_LIST^
9460 @cindex Dependencies, producing list
9461 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9462 Check if all objects are up to date. If they are, output the object
9463 dependences to @file{stdout} in a form that can be directly exploited in
9464 a @file{Makefile}. By default, each source file is prefixed with its
9465 (relative or absolute) directory name. This name is whatever you
9466 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9467 and @option{^-I^/SEARCH^} switches. If you use
9468 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9469 @option{^-q^/QUIET^}
9470 (see below), only the source file names,
9471 without relative paths, are output. If you just specify the
9472 @option{^-M^/DEPENDENCIES_LIST^}
9473 switch, dependencies of the GNAT internal system files are omitted. This
9474 is typically what you want. If you also specify
9475 the @option{^-a^/ALL_FILES^} switch,
9476 dependencies of the GNAT internal files are also listed. Note that
9477 dependencies of the objects in external Ada libraries (see switch
9478 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9479 are never reported.
9480
9481 @item ^-n^/DO_OBJECT_CHECK^
9482 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9483 Don't compile, bind, or link. Checks if all objects are up to date.
9484 If they are not, the full name of the first file that needs to be
9485 recompiled is printed.
9486 Repeated use of this option, followed by compiling the indicated source
9487 file, will eventually result in recompiling all required units.
9488
9489 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9490 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9491 Output executable name. The name of the final executable program will be
9492 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9493 name for the executable will be the name of the input file in appropriate form
9494 for an executable file on the host system.
9495
9496 This switch cannot be used when invoking @command{gnatmake} with several
9497 @file{file_names}.
9498
9499 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9500 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9501 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9502 automatically missing object directories, library directories and exec
9503 directories.
9504
9505 @item ^-P^/PROJECT_FILE=^@var{project}
9506 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9507 Use project file @var{project}. Only one such switch can be used.
9508 @xref{gnatmake and Project Files}.
9509
9510 @item ^-q^/QUIET^
9511 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9512 Quiet. When this flag is not set, the commands carried out by
9513 @command{gnatmake} are displayed.
9514
9515 @item ^-s^/SWITCH_CHECK/^
9516 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9517 Recompile if compiler switches have changed since last compilation.
9518 All compiler switches but -I and -o are taken into account in the
9519 following way:
9520 orders between different ``first letter'' switches are ignored, but
9521 orders between same switches are taken into account. For example,
9522 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9523 is equivalent to @option{-O -g}.
9524
9525 This switch is recommended when Integrated Preprocessing is used.
9526
9527 @item ^-u^/UNIQUE^
9528 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9529 Unique. Recompile at most the main files. It implies -c. Combined with
9530 -f, it is equivalent to calling the compiler directly. Note that using
9531 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9532 (@pxref{Project Files and Main Subprograms}).
9533
9534 @item ^-U^/ALL_PROJECTS^
9535 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9536 When used without a project file or with one or several mains on the command
9537 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9538 on the command line, all sources of all project files are checked and compiled
9539 if not up to date, and libraries are rebuilt, if necessary.
9540
9541 @item ^-v^/REASONS^
9542 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9543 Verbose. Display the reason for all recompilations @command{gnatmake}
9544 decides are necessary, with the highest verbosity level.
9545
9546 @item ^-vl^/LOW_VERBOSITY^
9547 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9548 Verbosity level Low. Display fewer lines than in verbosity Medium.
9549
9550 @item ^-vm^/MEDIUM_VERBOSITY^
9551 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9552 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9553
9554 @item ^-vh^/HIGH_VERBOSITY^
9555 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9556 Verbosity level High. Equivalent to ^-v^/REASONS^.
9557
9558 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9559 Indicate the verbosity of the parsing of GNAT project files.
9560 @xref{Switches Related to Project Files}.
9561
9562 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9563 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9564 Indicate that sources that are not part of any Project File may be compiled.
9565 Normally, when using Project Files, only sources that are part of a Project
9566 File may be compile. When this switch is used, a source outside of all Project
9567 Files may be compiled. The ALI file and the object file will be put in the
9568 object directory of the main Project. The compilation switches used will only
9569 be those specified on the command line. Even when
9570 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9571 command line need to be sources of a project file.
9572
9573 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9574 Indicate that external variable @var{name} has the value @var{value}.
9575 The Project Manager will use this value for occurrences of
9576 @code{external(name)} when parsing the project file.
9577 @xref{Switches Related to Project Files}.
9578
9579 @item ^-z^/NOMAIN^
9580 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9581 No main subprogram. Bind and link the program even if the unit name
9582 given on the command line is a package name. The resulting executable
9583 will execute the elaboration routines of the package and its closure,
9584 then the finalization routines.
9585
9586 @end table
9587
9588 @table @asis
9589 @item @command{gcc} @asis{switches}
9590 @ifclear vms
9591 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9592 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9593 @end ifclear
9594 @ifset vms
9595 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9596 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9597 automatically treated as a compiler switch, and passed on to all
9598 compilations that are carried out.
9599 @end ifset
9600 @end table
9601
9602 @noindent
9603 Source and library search path switches:
9604
9605 @table @option
9606 @c !sort!
9607 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9608 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9609 When looking for source files also look in directory @var{dir}.
9610 The order in which source files search is undertaken is
9611 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9612
9613 @item ^-aL^/SKIP_MISSING=^@var{dir}
9614 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9615 Consider @var{dir} as being an externally provided Ada library.
9616 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9617 files have been located in directory @var{dir}. This allows you to have
9618 missing bodies for the units in @var{dir} and to ignore out of date bodies
9619 for the same units. You still need to specify
9620 the location of the specs for these units by using the switches
9621 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9622 or @option{^-I^/SEARCH=^@var{dir}}.
9623 Note: this switch is provided for compatibility with previous versions
9624 of @command{gnatmake}. The easier method of causing standard libraries
9625 to be excluded from consideration is to write-protect the corresponding
9626 ALI files.
9627
9628 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9629 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9630 When searching for library and object files, look in directory
9631 @var{dir}. The order in which library files are searched is described in
9632 @ref{Search Paths for gnatbind}.
9633
9634 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9635 @cindex Search paths, for @command{gnatmake}
9636 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9637 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9638 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9639
9640 @item ^-I^/SEARCH=^@var{dir}
9641 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9642 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9643 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9644
9645 @item ^-I-^/NOCURRENT_DIRECTORY^
9646 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9647 @cindex Source files, suppressing search
9648 Do not look for source files in the directory containing the source
9649 file named in the command line.
9650 Do not look for ALI or object files in the directory
9651 where @command{gnatmake} was invoked.
9652
9653 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9654 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9655 @cindex Linker libraries
9656 Add directory @var{dir} to the list of directories in which the linker
9657 will search for libraries. This is equivalent to
9658 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9659 @ifclear vms
9660 Furthermore, under Windows, the sources pointed to by the libraries path
9661 set in the registry are not searched for.
9662 @end ifclear
9663
9664 @item -nostdinc
9665 @cindex @option{-nostdinc} (@command{gnatmake})
9666 Do not look for source files in the system default directory.
9667
9668 @item -nostdlib
9669 @cindex @option{-nostdlib} (@command{gnatmake})
9670 Do not look for library files in the system default directory.
9671
9672 @item --RTS=@var{rts-path}
9673 @cindex @option{--RTS} (@command{gnatmake})
9674 Specifies the default location of the runtime library. GNAT looks for the
9675 runtime
9676 in the following directories, and stops as soon as a valid runtime is found
9677 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9678 @file{ada_object_path} present):
9679
9680 @itemize @bullet
9681 @item <current directory>/$rts_path
9682
9683 @item <default-search-dir>/$rts_path
9684
9685 @item <default-search-dir>/rts-$rts_path
9686 @end itemize
9687
9688 @noindent
9689 The selected path is handled like a normal RTS path.
9690
9691 @end table
9692
9693 @node Mode Switches for gnatmake
9694 @section Mode Switches for @command{gnatmake}
9695
9696 @noindent
9697 The mode switches (referred to as @code{mode_switches}) allow the
9698 inclusion of switches that are to be passed to the compiler itself, the
9699 binder or the linker. The effect of a mode switch is to cause all
9700 subsequent switches up to the end of the switch list, or up to the next
9701 mode switch, to be interpreted as switches to be passed on to the
9702 designated component of GNAT.
9703
9704 @table @option
9705 @c !sort!
9706 @item -cargs @var{switches}
9707 @cindex @option{-cargs} (@command{gnatmake})
9708 Compiler switches. Here @var{switches} is a list of switches
9709 that are valid switches for @command{gcc}. They will be passed on to
9710 all compile steps performed by @command{gnatmake}.
9711
9712 @item -bargs @var{switches}
9713 @cindex @option{-bargs} (@command{gnatmake})
9714 Binder switches. Here @var{switches} is a list of switches
9715 that are valid switches for @code{gnatbind}. They will be passed on to
9716 all bind steps performed by @command{gnatmake}.
9717
9718 @item -largs @var{switches}
9719 @cindex @option{-largs} (@command{gnatmake})
9720 Linker switches. Here @var{switches} is a list of switches
9721 that are valid switches for @command{gnatlink}. They will be passed on to
9722 all link steps performed by @command{gnatmake}.
9723
9724 @item -margs @var{switches}
9725 @cindex @option{-margs} (@command{gnatmake})
9726 Make switches. The switches are directly interpreted by @command{gnatmake},
9727 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9728 or @option{-largs}.
9729 @end table
9730
9731 @node Notes on the Command Line
9732 @section Notes on the Command Line
9733
9734 @noindent
9735 This section contains some additional useful notes on the operation
9736 of the @command{gnatmake} command.
9737
9738 @itemize @bullet
9739 @item
9740 @cindex Recompilation, by @command{gnatmake}
9741 If @command{gnatmake} finds no ALI files, it recompiles the main program
9742 and all other units required by the main program.
9743 This means that @command{gnatmake}
9744 can be used for the initial compile, as well as during subsequent steps of
9745 the development cycle.
9746
9747 @item
9748 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9749 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9750 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9751 warning.
9752
9753 @item
9754 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9755 is used to specify both source and
9756 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9757 instead if you just want to specify
9758 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9759 if you want to specify library paths
9760 only.
9761
9762 @item
9763 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9764 This may conveniently be used to exclude standard libraries from
9765 consideration and in particular it means that the use of the
9766 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9767 unless @option{^-a^/ALL_FILES^} is also specified.
9768
9769 @item
9770 @command{gnatmake} has been designed to make the use of Ada libraries
9771 particularly convenient. Assume you have an Ada library organized
9772 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9773 of your Ada compilation units,
9774 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9775 specs of these units, but no bodies. Then to compile a unit
9776 stored in @code{main.adb}, which uses this Ada library you would just type
9777
9778 @smallexample
9779 @ifclear vms
9780 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9781 @end ifclear
9782 @ifset vms
9783 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9784            /SKIP_MISSING=@i{[OBJ_DIR]} main
9785 @end ifset
9786 @end smallexample
9787
9788 @item
9789 Using @command{gnatmake} along with the
9790 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9791 switch provides a mechanism for avoiding unnecessary recompilations. Using
9792 this switch,
9793 you can update the comments/format of your
9794 source files without having to recompile everything. Note, however, that
9795 adding or deleting lines in a source files may render its debugging
9796 info obsolete. If the file in question is a spec, the impact is rather
9797 limited, as that debugging info will only be useful during the
9798 elaboration phase of your program. For bodies the impact can be more
9799 significant. In all events, your debugger will warn you if a source file
9800 is more recent than the corresponding object, and alert you to the fact
9801 that the debugging information may be out of date.
9802 @end itemize
9803
9804 @node How gnatmake Works
9805 @section How @command{gnatmake} Works
9806
9807 @noindent
9808 Generally @command{gnatmake} automatically performs all necessary
9809 recompilations and you don't need to worry about how it works. However,
9810 it may be useful to have some basic understanding of the @command{gnatmake}
9811 approach and in particular to understand how it uses the results of
9812 previous compilations without incorrectly depending on them.
9813
9814 First a definition: an object file is considered @dfn{up to date} if the
9815 corresponding ALI file exists and if all the source files listed in the
9816 dependency section of this ALI file have time stamps matching those in
9817 the ALI file. This means that neither the source file itself nor any
9818 files that it depends on have been modified, and hence there is no need
9819 to recompile this file.
9820
9821 @command{gnatmake} works by first checking if the specified main unit is up
9822 to date. If so, no compilations are required for the main unit. If not,
9823 @command{gnatmake} compiles the main program to build a new ALI file that
9824 reflects the latest sources. Then the ALI file of the main unit is
9825 examined to find all the source files on which the main program depends,
9826 and @command{gnatmake} recursively applies the above procedure on all these
9827 files.
9828
9829 This process ensures that @command{gnatmake} only trusts the dependencies
9830 in an existing ALI file if they are known to be correct. Otherwise it
9831 always recompiles to determine a new, guaranteed accurate set of
9832 dependencies. As a result the program is compiled ``upside down'' from what may
9833 be more familiar as the required order of compilation in some other Ada
9834 systems. In particular, clients are compiled before the units on which
9835 they depend. The ability of GNAT to compile in any order is critical in
9836 allowing an order of compilation to be chosen that guarantees that
9837 @command{gnatmake} will recompute a correct set of new dependencies if
9838 necessary.
9839
9840 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9841 imported by several of the executables, it will be recompiled at most once.
9842
9843 Note: when using non-standard naming conventions
9844 (@pxref{Using Other File Names}), changing through a configuration pragmas
9845 file the version of a source and invoking @command{gnatmake} to recompile may
9846 have no effect, if the previous version of the source is still accessible
9847 by @command{gnatmake}. It may be necessary to use the switch
9848 ^-f^/FORCE_COMPILE^.
9849
9850 @node Examples of gnatmake Usage
9851 @section Examples of @command{gnatmake} Usage
9852
9853 @table @code
9854 @item gnatmake hello.adb
9855 Compile all files necessary to bind and link the main program
9856 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9857 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9858
9859 @item gnatmake main1 main2 main3
9860 Compile all files necessary to bind and link the main programs
9861 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9862 (containing unit @code{Main2}) and @file{main3.adb}
9863 (containing unit @code{Main3}) and bind and link the resulting object files
9864 to generate three executable files @file{^main1^MAIN1.EXE^},
9865 @file{^main2^MAIN2.EXE^}
9866 and @file{^main3^MAIN3.EXE^}.
9867
9868 @ifclear vms
9869 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9870 @end ifclear
9871
9872 @ifset vms
9873 @item gnatmake Main_Unit /QUIET
9874 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9875 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9876 @end ifset
9877 Compile all files necessary to bind and link the main program unit
9878 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9879 be done with optimization level 2 and the order of elaboration will be
9880 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9881 displaying commands it is executing.
9882 @end table
9883
9884 @c *************************
9885 @node Improving Performance
9886 @chapter Improving Performance
9887 @cindex Improving performance
9888
9889 @noindent
9890 This chapter presents several topics related to program performance.
9891 It first describes some of the tradeoffs that need to be considered
9892 and some of the techniques for making your program run faster.
9893 It then documents the @command{gnatelim} tool and unused subprogram/data
9894 elimination feature, which can reduce the size of program executables.
9895
9896 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9897 driver (see @ref{The GNAT Driver and Project Files}).
9898
9899 @ifnottex
9900 @menu
9901 * Performance Considerations::
9902 * Text_IO Suggestions::
9903 * Reducing Size of Ada Executables with gnatelim::
9904 * Reducing Size of Executables with unused subprogram/data elimination::
9905 @end menu
9906 @end ifnottex
9907
9908 @c *****************************
9909 @node Performance Considerations
9910 @section Performance Considerations
9911
9912 @noindent
9913 The GNAT system provides a number of options that allow a trade-off
9914 between
9915
9916 @itemize @bullet
9917 @item
9918 performance of the generated code
9919
9920 @item
9921 speed of compilation
9922
9923 @item
9924 minimization of dependences and recompilation
9925
9926 @item
9927 the degree of run-time checking.
9928 @end itemize
9929
9930 @noindent
9931 The defaults (if no options are selected) aim at improving the speed
9932 of compilation and minimizing dependences, at the expense of performance
9933 of the generated code:
9934
9935 @itemize @bullet
9936 @item
9937 no optimization
9938
9939 @item
9940 no inlining of subprogram calls
9941
9942 @item
9943 all run-time checks enabled except overflow and elaboration checks
9944 @end itemize
9945
9946 @noindent
9947 These options are suitable for most program development purposes. This
9948 chapter describes how you can modify these choices, and also provides
9949 some guidelines on debugging optimized code.
9950
9951 @menu
9952 * Controlling Run-Time Checks::
9953 * Use of Restrictions::
9954 * Optimization Levels::
9955 * Debugging Optimized Code::
9956 * Inlining of Subprograms::
9957 * Other Optimization Switches::
9958 * Optimization and Strict Aliasing::
9959
9960 @ifset vms
9961 * Coverage Analysis::
9962 @end ifset
9963 @end menu
9964
9965 @node Controlling Run-Time Checks
9966 @subsection Controlling Run-Time Checks
9967
9968 @noindent
9969 By default, GNAT generates all run-time checks, except integer overflow
9970 checks, stack overflow checks, and checks for access before elaboration on
9971 subprogram calls. The latter are not required in default mode, because all
9972 necessary checking is done at compile time.
9973 @cindex @option{-gnatp} (@command{gcc})
9974 @cindex @option{-gnato} (@command{gcc})
9975 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9976 be modified. @xref{Run-Time Checks}.
9977
9978 Our experience is that the default is suitable for most development
9979 purposes.
9980
9981 We treat integer overflow specially because these
9982 are quite expensive and in our experience are not as important as other
9983 run-time checks in the development process. Note that division by zero
9984 is not considered an overflow check, and divide by zero checks are
9985 generated where required by default.
9986
9987 Elaboration checks are off by default, and also not needed by default, since
9988 GNAT uses a static elaboration analysis approach that avoids the need for
9989 run-time checking. This manual contains a full chapter discussing the issue
9990 of elaboration checks, and if the default is not satisfactory for your use,
9991 you should read this chapter.
9992
9993 For validity checks, the minimal checks required by the Ada Reference
9994 Manual (for case statements and assignments to array elements) are on
9995 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9996 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9997 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9998 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9999 are also suppressed entirely if @option{-gnatp} is used.
10000
10001 @cindex Overflow checks
10002 @cindex Checks, overflow
10003 @findex Suppress
10004 @findex Unsuppress
10005 @cindex pragma Suppress
10006 @cindex pragma Unsuppress
10007 Note that the setting of the switches controls the default setting of
10008 the checks. They may be modified using either @code{pragma Suppress} (to
10009 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10010 checks) in the program source.
10011
10012 @node Use of Restrictions
10013 @subsection Use of Restrictions
10014
10015 @noindent
10016 The use of pragma Restrictions allows you to control which features are
10017 permitted in your program. Apart from the obvious point that if you avoid
10018 relatively expensive features like finalization (enforceable by the use
10019 of pragma Restrictions (No_Finalization), the use of this pragma does not
10020 affect the generated code in most cases.
10021
10022 One notable exception to this rule is that the possibility of task abort
10023 results in some distributed overhead, particularly if finalization or
10024 exception handlers are used. The reason is that certain sections of code
10025 have to be marked as non-abortable.
10026
10027 If you use neither the @code{abort} statement, nor asynchronous transfer
10028 of control (@code{select @dots{} then abort}), then this distributed overhead
10029 is removed, which may have a general positive effect in improving
10030 overall performance.  Especially code involving frequent use of tasking
10031 constructs and controlled types will show much improved performance.
10032 The relevant restrictions pragmas are
10033
10034 @smallexample @c ada
10035    pragma Restrictions (No_Abort_Statements);
10036    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10037 @end smallexample
10038
10039 @noindent
10040 It is recommended that these restriction pragmas be used if possible. Note
10041 that this also means that you can write code without worrying about the
10042 possibility of an immediate abort at any point.
10043
10044 @node Optimization Levels
10045 @subsection Optimization Levels
10046 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10047
10048 @noindent
10049 Without any optimization ^option,^qualifier,^
10050 the compiler's goal is to reduce the cost of
10051 compilation and to make debugging produce the expected results.
10052 Statements are independent: if you stop the program with a breakpoint between
10053 statements, you can then assign a new value to any variable or change
10054 the program counter to any other statement in the subprogram and get exactly
10055 the results you would expect from the source code.
10056
10057 Turning on optimization makes the compiler attempt to improve the
10058 performance and/or code size at the expense of compilation time and
10059 possibly the ability to debug the program.
10060
10061 If you use multiple
10062 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10063 the last such option is the one that is effective.
10064
10065 @noindent
10066 The default is optimization off. This results in the fastest compile
10067 times, but GNAT makes absolutely no attempt to optimize, and the
10068 generated programs are considerably larger and slower than when
10069 optimization is enabled. You can use the
10070 @ifclear vms
10071 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10072 @option{-O2}, @option{-O3}, and @option{-Os})
10073 @end ifclear
10074 @ifset vms
10075 @code{OPTIMIZE} qualifier
10076 @end ifset
10077 to @command{gcc} to control the optimization level:
10078
10079 @table @option
10080 @item ^-O0^/OPTIMIZE=NONE^
10081 No optimization (the default);
10082 generates unoptimized code but has
10083 the fastest compilation time.
10084
10085 Note that many other compilers do fairly extensive optimization
10086 even if ``no optimization'' is specified. With gcc, it is
10087 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10088 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10089 really does mean no optimization at all. This difference between
10090 gcc and other compilers should be kept in mind when doing
10091 performance comparisons.
10092
10093 @item ^-O1^/OPTIMIZE=SOME^
10094 Moderate optimization;
10095 optimizes reasonably well but does not
10096 degrade compilation time significantly.
10097
10098 @item ^-O2^/OPTIMIZE=ALL^
10099 @ifset vms
10100 @itemx /OPTIMIZE=DEVELOPMENT
10101 @end ifset
10102 Full optimization;
10103 generates highly optimized code and has
10104 the slowest compilation time.
10105
10106 @item ^-O3^/OPTIMIZE=INLINING^
10107 Full optimization as in @option{-O2},
10108 and also attempts automatic inlining of small
10109 subprograms within a unit (@pxref{Inlining of Subprograms}).
10110
10111 @item ^-Os^/OPTIMIZE=SPACE^
10112 Optimize space usage of resulting program.
10113 @end table
10114
10115 @noindent
10116 Higher optimization levels perform more global transformations on the
10117 program and apply more expensive analysis algorithms in order to generate
10118 faster and more compact code. The price in compilation time, and the
10119 resulting improvement in execution time,
10120 both depend on the particular application and the hardware environment.
10121 You should experiment to find the best level for your application.
10122
10123 Since the precise set of optimizations done at each level will vary from
10124 release to release (and sometime from target to target), it is best to think
10125 of the optimization settings in general terms.
10126 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10127 the GNU Compiler Collection (GCC)}, for details about
10128 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10129 individually enable or disable specific optimizations.
10130
10131 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10132 been tested extensively at all optimization levels. There are some bugs
10133 which appear only with optimization turned on, but there have also been
10134 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10135 level of optimization does not improve the reliability of the code
10136 generator, which in practice is highly reliable at all optimization
10137 levels.
10138
10139 Note regarding the use of @option{-O3}: The use of this optimization level
10140 is generally discouraged with GNAT, since it often results in larger
10141 executables which run more slowly. See further discussion of this point
10142 in @ref{Inlining of Subprograms}.
10143
10144 @node Debugging Optimized Code
10145 @subsection Debugging Optimized Code
10146 @cindex Debugging optimized code
10147 @cindex Optimization and debugging
10148
10149 @noindent
10150 Although it is possible to do a reasonable amount of debugging at
10151 @ifclear vms
10152 nonzero optimization levels,
10153 the higher the level the more likely that
10154 @end ifclear
10155 @ifset vms
10156 @option{/OPTIMIZE} settings other than @code{NONE},
10157 such settings will make it more likely that
10158 @end ifset
10159 source-level constructs will have been eliminated by optimization.
10160 For example, if a loop is strength-reduced, the loop
10161 control variable may be completely eliminated and thus cannot be
10162 displayed in the debugger.
10163 This can only happen at @option{-O2} or @option{-O3}.
10164 Explicit temporary variables that you code might be eliminated at
10165 ^level^setting^ @option{-O1} or higher.
10166
10167 The use of the @option{^-g^/DEBUG^} switch,
10168 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10169 which is needed for source-level debugging,
10170 affects the size of the program executable on disk,
10171 and indeed the debugging information can be quite large.
10172 However, it has no effect on the generated code (and thus does not
10173 degrade performance)
10174
10175 Since the compiler generates debugging tables for a compilation unit before
10176 it performs optimizations, the optimizing transformations may invalidate some
10177 of the debugging data.  You therefore need to anticipate certain
10178 anomalous situations that may arise while debugging optimized code.
10179 These are the most common cases:
10180
10181 @enumerate
10182 @item
10183 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10184 commands show
10185 the PC bouncing back and forth in the code.  This may result from any of
10186 the following optimizations:
10187
10188 @itemize @bullet
10189 @item
10190 @i{Common subexpression elimination:} using a single instance of code for a
10191 quantity that the source computes several times.  As a result you
10192 may not be able to stop on what looks like a statement.
10193
10194 @item
10195 @i{Invariant code motion:} moving an expression that does not change within a
10196 loop, to the beginning of the loop.
10197
10198 @item
10199 @i{Instruction scheduling:} moving instructions so as to
10200 overlap loads and stores (typically) with other code, or in
10201 general to move computations of values closer to their uses. Often
10202 this causes you to pass an assignment statement without the assignment
10203 happening and then later bounce back to the statement when the
10204 value is actually needed.  Placing a breakpoint on a line of code
10205 and then stepping over it may, therefore, not always cause all the
10206 expected side-effects.
10207 @end itemize
10208
10209 @item
10210 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10211 two identical pieces of code are merged and the program counter suddenly
10212 jumps to a statement that is not supposed to be executed, simply because
10213 it (and the code following) translates to the same thing as the code
10214 that @emph{was} supposed to be executed.  This effect is typically seen in
10215 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10216 a @code{break} in a C @code{^switch^switch^} statement.
10217
10218 @item
10219 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10220 There are various reasons for this effect:
10221
10222 @itemize @bullet
10223 @item
10224 In a subprogram prologue, a parameter may not yet have been moved to its
10225 ``home''.
10226
10227 @item
10228 A variable may be dead, and its register re-used.  This is
10229 probably the most common cause.
10230
10231 @item
10232 As mentioned above, the assignment of a value to a variable may
10233 have been moved.
10234
10235 @item
10236 A variable may be eliminated entirely by value propagation or
10237 other means.  In this case, GCC may incorrectly generate debugging
10238 information for the variable
10239 @end itemize
10240
10241 @noindent
10242 In general, when an unexpected value appears for a local variable or parameter
10243 you should first ascertain if that value was actually computed by
10244 your program, as opposed to being incorrectly reported by the debugger.
10245 Record fields or
10246 array elements in an object designated by an access value
10247 are generally less of a problem, once you have ascertained that the access
10248 value is sensible.
10249 Typically, this means checking variables in the preceding code and in the
10250 calling subprogram to verify that the value observed is explainable from other
10251 values (one must apply the procedure recursively to those
10252 other values); or re-running the code and stopping a little earlier
10253 (perhaps before the call) and stepping to better see how the variable obtained
10254 the value in question; or continuing to step @emph{from} the point of the
10255 strange value to see if code motion had simply moved the variable's
10256 assignments later.
10257 @end enumerate
10258
10259 @noindent
10260 In light of such anomalies, a recommended technique is to use @option{-O0}
10261 early in the software development cycle, when extensive debugging capabilities
10262 are most needed, and then move to @option{-O1} and later @option{-O2} as
10263 the debugger becomes less critical.
10264 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10265 a release management issue.
10266 @ifclear vms
10267 Note that if you use @option{-g} you can then use the @command{strip} program
10268 on the resulting executable,
10269 which removes both debugging information and global symbols.
10270 @end ifclear
10271
10272 @node Inlining of Subprograms
10273 @subsection Inlining of Subprograms
10274
10275 @noindent
10276 A call to a subprogram in the current unit is inlined if all the
10277 following conditions are met:
10278
10279 @itemize @bullet
10280 @item
10281 The optimization level is at least @option{-O1}.
10282
10283 @item
10284 The called subprogram is suitable for inlining: It must be small enough
10285 and not contain something that @command{gcc} cannot support in inlined
10286 subprograms.
10287
10288 @item
10289 @cindex pragma Inline
10290 @findex Inline
10291 Either @code{pragma Inline} applies to the subprogram, or it is local
10292 to the unit and called once from within it, or it is small and automatic
10293 inlining (optimization level @option{-O3}) is specified.
10294 @end itemize
10295
10296 @noindent
10297 Calls to subprograms in @code{with}'ed units are normally not inlined.
10298 To achieve actual inlining (that is, replacement of the call by the code
10299 in the body of the subprogram), the following conditions must all be true.
10300
10301 @itemize @bullet
10302 @item
10303 The optimization level is at least @option{-O1}.
10304
10305 @item
10306 The called subprogram is suitable for inlining: It must be small enough
10307 and not contain something that @command{gcc} cannot support in inlined
10308 subprograms.
10309
10310 @item
10311 The call appears in a body (not in a package spec).
10312
10313 @item
10314 There is a @code{pragma Inline} for the subprogram.
10315
10316 @item
10317 @cindex @option{-gnatn} (@command{gcc})
10318 The @option{^-gnatn^/INLINE^} switch
10319 is used in the @command{gcc} command line
10320 @end itemize
10321
10322 Even if all these conditions are met, it may not be possible for
10323 the compiler to inline the call, due to the length of the body,
10324 or features in the body that make it impossible for the compiler
10325 to do the inlining.
10326
10327 Note that specifying the @option{-gnatn} switch causes additional
10328 compilation dependencies. Consider the following:
10329
10330 @smallexample @c ada
10331 @cartouche
10332 package R is
10333    procedure Q;
10334    pragma Inline (Q);
10335 end R;
10336 package body R is
10337    @dots{}
10338 end R;
10339
10340 with R;
10341 procedure Main is
10342 begin
10343    @dots{}
10344    R.Q;
10345 end Main;
10346 @end cartouche
10347 @end smallexample
10348
10349 @noindent
10350 With the default behavior (no @option{-gnatn} switch specified), the
10351 compilation of the @code{Main} procedure depends only on its own source,
10352 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10353 means that editing the body of @code{R} does not require recompiling
10354 @code{Main}.
10355
10356 On the other hand, the call @code{R.Q} is not inlined under these
10357 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10358 is compiled, the call will be inlined if the body of @code{Q} is small
10359 enough, but now @code{Main} depends on the body of @code{R} in
10360 @file{r.adb} as well as on the spec. This means that if this body is edited,
10361 the main program must be recompiled. Note that this extra dependency
10362 occurs whether or not the call is in fact inlined by @command{gcc}.
10363
10364 The use of front end inlining with @option{-gnatN} generates similar
10365 additional dependencies.
10366
10367 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10368 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10369 can be used to prevent
10370 all inlining. This switch overrides all other conditions and ensures
10371 that no inlining occurs. The extra dependences resulting from
10372 @option{-gnatn} will still be active, even if
10373 this switch is used to suppress the resulting inlining actions.
10374
10375 @cindex @option{-fno-inline-functions} (@command{gcc})
10376 Note: The @option{-fno-inline-functions} switch can be used to prevent
10377 automatic inlining of small subprograms if @option{-O3} is used.
10378
10379 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10380 Note: The @option{-fno-inline-functions-called-once} switch
10381 can be used to prevent inlining of subprograms local to the unit
10382 and called once from within it if @option{-O1} is used.
10383
10384 Note regarding the use of @option{-O3}: There is no difference in inlining
10385 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10386 pragma @code{Inline} assuming the use of @option{-gnatn}
10387 or @option{-gnatN} (the switches that activate inlining). If you have used
10388 pragma @code{Inline} in appropriate cases, then it is usually much better
10389 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10390 in this case only has the effect of inlining subprograms you did not
10391 think should be inlined. We often find that the use of @option{-O3} slows
10392 down code by performing excessive inlining, leading to increased instruction
10393 cache pressure from the increased code size. So the bottom line here is
10394 that you should not automatically assume that @option{-O3} is better than
10395 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10396 it actually improves performance.
10397
10398 @node Other Optimization Switches
10399 @subsection Other Optimization Switches
10400 @cindex Optimization Switches
10401
10402 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10403 @command{gcc} optimization switches are potentially usable. These switches
10404 have not been extensively tested with GNAT but can generally be expected
10405 to work. Examples of switches in this category are
10406 @option{-funroll-loops} and
10407 the various target-specific @option{-m} options (in particular, it has been
10408 observed that @option{-march=pentium4} can significantly improve performance
10409 on appropriate machines). For full details of these switches, see
10410 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10411 the GNU Compiler Collection (GCC)}.
10412
10413 @node Optimization and Strict Aliasing
10414 @subsection Optimization and Strict Aliasing
10415 @cindex Aliasing
10416 @cindex Strict Aliasing
10417 @cindex No_Strict_Aliasing
10418
10419 @noindent
10420 The strong typing capabilities of Ada allow an optimizer to generate
10421 efficient code in situations where other languages would be forced to
10422 make worst case assumptions preventing such optimizations. Consider
10423 the following example:
10424
10425 @smallexample @c ada
10426 @cartouche
10427 procedure R is
10428    type Int1 is new Integer;
10429    type Int2 is new Integer;
10430    type Int1A is access Int1;
10431    type Int2A is access Int2;
10432    Int1V : Int1A;
10433    Int2V : Int2A;
10434    @dots{}
10435
10436 begin
10437    @dots{}
10438    for J in Data'Range loop
10439       if Data (J) = Int1V.all then
10440          Int2V.all := Int2V.all + 1;
10441       end if;
10442    end loop;
10443    @dots{}
10444 end R;
10445 @end cartouche
10446 @end smallexample
10447
10448 @noindent
10449 In this example, since the variable @code{Int1V} can only access objects
10450 of type @code{Int1}, and @code{Int2V} can only access objects of type
10451 @code{Int2}, there is no possibility that the assignment to
10452 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10453 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10454 for all iterations of the loop and avoid the extra memory reference
10455 required to dereference it each time through the loop.
10456
10457 This kind of optimization, called strict aliasing analysis, is
10458 triggered by specifying an optimization level of @option{-O2} or
10459 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10460 when access values are involved.
10461
10462 However, although this optimization is always correct in terms of
10463 the formal semantics of the Ada Reference Manual, difficulties can
10464 arise if features like @code{Unchecked_Conversion} are used to break
10465 the typing system. Consider the following complete program example:
10466
10467 @smallexample @c ada
10468 @cartouche
10469 package p1 is
10470    type int1 is new integer;
10471    type int2 is new integer;
10472    type a1 is access int1;
10473    type a2 is access int2;
10474 end p1;
10475
10476 with p1; use p1;
10477 package p2 is
10478    function to_a2 (Input : a1) return a2;
10479 end p2;
10480
10481 with Unchecked_Conversion;
10482 package body p2 is
10483    function to_a2 (Input : a1) return a2 is
10484       function to_a2u is
10485         new Unchecked_Conversion (a1, a2);
10486    begin
10487       return to_a2u (Input);
10488    end to_a2;
10489 end p2;
10490
10491 with p2; use p2;
10492 with p1; use p1;
10493 with Text_IO; use Text_IO;
10494 procedure m is
10495    v1 : a1 := new int1;
10496    v2 : a2 := to_a2 (v1);
10497 begin
10498    v1.all := 1;
10499    v2.all := 0;
10500    put_line (int1'image (v1.all));
10501 end;
10502 @end cartouche
10503 @end smallexample
10504
10505 @noindent
10506 This program prints out 0 in @option{-O0} or @option{-O1}
10507 mode, but it prints out 1 in @option{-O2} mode. That's
10508 because in strict aliasing mode, the compiler can and
10509 does assume that the assignment to @code{v2.all} could not
10510 affect the value of @code{v1.all}, since different types
10511 are involved.
10512
10513 This behavior is not a case of non-conformance with the standard, since
10514 the Ada RM specifies that an unchecked conversion where the resulting
10515 bit pattern is not a correct value of the target type can result in an
10516 abnormal value and attempting to reference an abnormal value makes the
10517 execution of a program erroneous.  That's the case here since the result
10518 does not point to an object of type @code{int2}.  This means that the
10519 effect is entirely unpredictable.
10520
10521 However, although that explanation may satisfy a language
10522 lawyer, in practice an applications programmer expects an
10523 unchecked conversion involving pointers to create true
10524 aliases and the behavior of printing 1 seems plain wrong.
10525 In this case, the strict aliasing optimization is unwelcome.
10526
10527 Indeed the compiler recognizes this possibility, and the
10528 unchecked conversion generates a warning:
10529
10530 @smallexample
10531 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10532 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10533 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10534 @end smallexample
10535
10536 @noindent
10537 Unfortunately the problem is recognized when compiling the body of
10538 package @code{p2}, but the actual "bad" code is generated while
10539 compiling the body of @code{m} and this latter compilation does not see
10540 the suspicious @code{Unchecked_Conversion}.
10541
10542 As implied by the warning message, there are approaches you can use to
10543 avoid the unwanted strict aliasing optimization in a case like this.
10544
10545 One possibility is to simply avoid the use of @option{-O2}, but
10546 that is a bit drastic, since it throws away a number of useful
10547 optimizations that do not involve strict aliasing assumptions.
10548
10549 A less drastic approach is to compile the program using the
10550 option @option{-fno-strict-aliasing}. Actually it is only the
10551 unit containing the dereferencing of the suspicious pointer
10552 that needs to be compiled. So in this case, if we compile
10553 unit @code{m} with this switch, then we get the expected
10554 value of zero printed. Analyzing which units might need
10555 the switch can be painful, so a more reasonable approach
10556 is to compile the entire program with options @option{-O2}
10557 and @option{-fno-strict-aliasing}. If the performance is
10558 satisfactory with this combination of options, then the
10559 advantage is that the entire issue of possible "wrong"
10560 optimization due to strict aliasing is avoided.
10561
10562 To avoid the use of compiler switches, the configuration
10563 pragma @code{No_Strict_Aliasing} with no parameters may be
10564 used to specify that for all access types, the strict
10565 aliasing optimization should be suppressed.
10566
10567 However, these approaches are still overkill, in that they causes
10568 all manipulations of all access values to be deoptimized. A more
10569 refined approach is to concentrate attention on the specific
10570 access type identified as problematic.
10571
10572 First, if a careful analysis of uses of the pointer shows
10573 that there are no possible problematic references, then
10574 the warning can be suppressed by bracketing the
10575 instantiation of @code{Unchecked_Conversion} to turn
10576 the warning off:
10577
10578 @smallexample @c ada
10579    pragma Warnings (Off);
10580    function to_a2u is
10581      new Unchecked_Conversion (a1, a2);
10582    pragma Warnings (On);
10583 @end smallexample
10584
10585 @noindent
10586 Of course that approach is not appropriate for this particular
10587 example, since indeed there is a problematic reference. In this
10588 case we can take one of two other approaches.
10589
10590 The first possibility is to move the instantiation of unchecked
10591 conversion to the unit in which the type is declared. In
10592 this example, we would move the instantiation of
10593 @code{Unchecked_Conversion} from the body of package
10594 @code{p2} to the spec of package @code{p1}. Now the
10595 warning disappears. That's because any use of the
10596 access type knows there is a suspicious unchecked
10597 conversion, and the strict aliasing optimization
10598 is automatically suppressed for the type.
10599
10600 If it is not practical to move the unchecked conversion to the same unit
10601 in which the destination access type is declared (perhaps because the
10602 source type is not visible in that unit), you may use pragma
10603 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10604 same declarative sequence as the declaration of the access type:
10605
10606 @smallexample @c ada
10607    type a2 is access int2;
10608    pragma No_Strict_Aliasing (a2);
10609 @end smallexample
10610
10611 @noindent
10612 Here again, the compiler now knows that the strict aliasing optimization
10613 should be suppressed for any reference to type @code{a2} and the
10614 expected behavior is obtained.
10615
10616 Finally, note that although the compiler can generate warnings for
10617 simple cases of unchecked conversions, there are tricker and more
10618 indirect ways of creating type incorrect aliases which the compiler
10619 cannot detect. Examples are the use of address overlays and unchecked
10620 conversions involving composite types containing access types as
10621 components. In such cases, no warnings are generated, but there can
10622 still be aliasing problems. One safe coding practice is to forbid the
10623 use of address clauses for type overlaying, and to allow unchecked
10624 conversion only for primitive types. This is not really a significant
10625 restriction since any possible desired effect can be achieved by
10626 unchecked conversion of access values.
10627
10628 The aliasing analysis done in strict aliasing mode can certainly
10629 have significant benefits. We have seen cases of large scale
10630 application code where the time is increased by up to 5% by turning
10631 this optimization off. If you have code that includes significant
10632 usage of unchecked conversion, you might want to just stick with
10633 @option{-O1} and avoid the entire issue. If you get adequate
10634 performance at this level of optimization level, that's probably
10635 the safest approach. If tests show that you really need higher
10636 levels of optimization, then you can experiment with @option{-O2}
10637 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10638 has on size and speed of the code. If you really need to use
10639 @option{-O2} with strict aliasing in effect, then you should
10640 review any uses of unchecked conversion of access types,
10641 particularly if you are getting the warnings described above.
10642
10643 @ifset vms
10644 @node Coverage Analysis
10645 @subsection Coverage Analysis
10646
10647 @noindent
10648 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10649 the user to determine the distribution of execution time across a program,
10650 @pxref{Profiling} for details of usage.
10651 @end ifset
10652
10653
10654 @node Text_IO Suggestions
10655 @section @code{Text_IO} Suggestions
10656 @cindex @code{Text_IO} and performance
10657
10658 @noindent
10659 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10660 the requirement of maintaining page and line counts. If performance
10661 is critical, a recommendation is to use @code{Stream_IO} instead of
10662 @code{Text_IO} for volume output, since this package has less overhead.
10663
10664 If @code{Text_IO} must be used, note that by default output to the standard
10665 output and standard error files is unbuffered (this provides better
10666 behavior when output statements are used for debugging, or if the
10667 progress of a program is observed by tracking the output, e.g. by
10668 using the Unix @command{tail -f} command to watch redirected output.
10669
10670 If you are generating large volumes of output with @code{Text_IO} and
10671 performance is an important factor, use a designated file instead
10672 of the standard output file, or change the standard output file to
10673 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10674
10675
10676
10677 @node Reducing Size of Ada Executables with gnatelim
10678 @section Reducing Size of Ada Executables with @code{gnatelim}
10679 @findex gnatelim
10680
10681 @noindent
10682 This section describes @command{gnatelim}, a tool which detects unused
10683 subprograms and helps the compiler to create a smaller executable for your
10684 program.
10685
10686 @menu
10687 * About gnatelim::
10688 * Running gnatelim::
10689 * Processing Precompiled Libraries::
10690 * Correcting the List of Eliminate Pragmas::
10691 * Making Your Executables Smaller::
10692 * Summary of the gnatelim Usage Cycle::
10693 @end menu
10694
10695 @node About gnatelim
10696 @subsection About @code{gnatelim}
10697
10698 @noindent
10699 When a program shares a set of Ada
10700 packages with other programs, it may happen that this program uses
10701 only a fraction of the subprograms defined in these packages. The code
10702 created for these unused subprograms increases the size of the executable.
10703
10704 @code{gnatelim} tracks unused subprograms in an Ada program and
10705 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10706 subprograms that are declared but never called. By placing the list of
10707 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10708 recompiling your program, you may decrease the size of its executable,
10709 because the compiler will not generate the code for 'eliminated' subprograms.
10710 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10711 information about this pragma.
10712
10713 @code{gnatelim} needs as its input data the name of the main subprogram.
10714
10715 If a set of source files is specified as @code{gnatelim} arguments, it
10716 treats these files as a complete set of sources making up a program to
10717 analyse, and analyses only these sources.
10718
10719 After a full successful build of the main subprogram @code{gnatelim} can be
10720 called without  specifying sources to analyse, in this case it computes
10721 the source closure of the main unit from the @file{ALI} files.
10722
10723 The following command will create the set of @file{ALI} files needed for
10724 @code{gnatelim}:
10725
10726 @smallexample
10727 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10728 @end smallexample
10729
10730 Note that @code{gnatelim} does not need object files.
10731
10732 @node Running gnatelim
10733 @subsection Running @code{gnatelim}
10734
10735 @noindent
10736 @code{gnatelim} has the following command-line interface:
10737
10738 @smallexample
10739 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10740 @end smallexample
10741
10742 @noindent
10743 @var{main_unit_name} should be a name of a source file that contains the main
10744 subprogram of a program (partition).
10745
10746 Each @var{filename} is the name (including the extension) of a source
10747 file to process. ``Wildcards'' are allowed, and
10748 the file name may contain path information.
10749
10750 @samp{@var{gcc_switches}} is a list of switches for
10751 @command{gcc}. They will be passed on to all compiler invocations made by
10752 @command{gnatelim} to generate the ASIS trees. Here you can provide
10753 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10754 use the @option{-gnatec} switch to set the configuration file etc.
10755
10756 @code{gnatelim} has the following switches:
10757
10758 @table @option
10759 @c !sort!
10760 @item ^-files^/FILES^=@var{filename}
10761 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10762 Take the argument source files from the specified file. This file should be an
10763 ordinary text file containing file names separated by spaces or
10764 line breaks. You can use this switch more than once in the same call to
10765 @command{gnatelim}. You also can combine this switch with
10766 an explicit list of files.
10767
10768 @item ^-log^/LOG^
10769 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10770 Duplicate all the output sent to @file{stderr} into a log file. The log file
10771 is named @file{gnatelim.log} and is located in the current directory.
10772
10773 @item ^-log^/LOGFILE^=@var{filename}
10774 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10775 Duplicate all the output sent to @file{stderr} into a specified log file.
10776
10777 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10778 @item ^--no-elim-dispatch^/NO_DISPATCH^
10779 Do not generate pragmas for dispatching operations.
10780
10781 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10782 @item ^-o^/OUTPUT^=@var{report_file}
10783 Put @command{gnatelim} output into a specified file. If this file already exists,
10784 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10785 into @file{stderr}
10786
10787 @item ^-q^/QUIET^
10788 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10789 Quiet mode: by default @code{gnatelim} outputs to the standard error
10790 stream the number of program units left to be processed. This option turns
10791 this trace off.
10792
10793 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10794 @item ^-t^/TIME^
10795 Print out execution time.
10796
10797 @item ^-v^/VERBOSE^
10798 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10799 Verbose mode: @code{gnatelim} version information is printed as Ada
10800 comments to the standard output stream. Also, in addition to the number of
10801 program units left @code{gnatelim} will output the name of the current unit
10802 being processed.
10803
10804 @item ^-wq^/WARNINGS=QUIET^
10805 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10806 Quet warning mode - some warnings are suppressed. In particular warnings that
10807 indicate that the analysed set of sources is incomplete to make up a
10808 partition and that some subprogram bodies are missing are not generated.
10809 @end table
10810
10811 @node Processing Precompiled Libraries
10812 @subsection Processing Precompiled Libraries
10813
10814 @noindent
10815 If some program uses a precompiled Ada library, it can be processed by
10816 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10817 Eliminate pragma for a subprogram if the body of this subprogram has not
10818 been analysed, this is a typical case for subprograms from precompiled
10819 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10820 warnings about missing source files and non-analyzed subprogram bodies
10821 that can be generated when processing precompiled Ada libraries.
10822
10823 @node Correcting the List of Eliminate Pragmas
10824 @subsection Correcting the List of Eliminate Pragmas
10825
10826 @noindent
10827 In some rare cases @code{gnatelim} may try to eliminate
10828 subprograms that are actually called in the program. In this case, the
10829 compiler will generate an error message of the form:
10830
10831 @smallexample
10832 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10833 @end smallexample
10834
10835 @noindent
10836 You will need to manually remove the wrong @code{Eliminate} pragmas from
10837 the configuration file indicated in the error message. You should recompile
10838 your program from scratch after that, because you need a consistent
10839 configuration file(s) during the entire compilation.
10840
10841 @node Making Your Executables Smaller
10842 @subsection Making Your Executables Smaller
10843
10844 @noindent
10845 In order to get a smaller executable for your program you now have to
10846 recompile the program completely with the configuration file containing
10847 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10848 @file{gnat.adc} file located in your current directory, just do:
10849
10850 @smallexample
10851 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10852 @end smallexample
10853
10854 @noindent
10855 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10856 recompile everything
10857 with the set of pragmas @code{Eliminate} that you have obtained with
10858 @command{gnatelim}).
10859
10860 Be aware that the set of @code{Eliminate} pragmas is specific to each
10861 program. It is not recommended to merge sets of @code{Eliminate}
10862 pragmas created for different programs in one configuration file.
10863
10864 @node Summary of the gnatelim Usage Cycle
10865 @subsection Summary of the @code{gnatelim} Usage Cycle
10866
10867 @noindent
10868 Here is a quick summary of the steps to be taken in order to reduce
10869 the size of your executables with @code{gnatelim}. You may use
10870 other GNAT options to control the optimization level,
10871 to produce the debugging information, to set search path, etc.
10872
10873 @enumerate
10874 @item
10875 Create a complete set of @file{ALI} files (if the program has not been
10876 built already)
10877
10878 @smallexample
10879 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10880 @end smallexample
10881
10882 @item
10883 Generate a list of @code{Eliminate} pragmas in default configuration file
10884 @file{gnat.adc} in the current directory
10885 @smallexample
10886 @ifset vms
10887 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10888 @end ifset
10889 @ifclear vms
10890 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10891 @end ifclear
10892 @end smallexample
10893
10894 @item
10895 Recompile the application
10896
10897 @smallexample
10898 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10899 @end smallexample
10900
10901 @end enumerate
10902
10903 @node Reducing Size of Executables with unused subprogram/data elimination
10904 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10905 @findex unused subprogram/data elimination
10906
10907 @noindent
10908 This section describes how you can eliminate unused subprograms and data from
10909 your executable just by setting options at compilation time.
10910
10911 @menu
10912 * About unused subprogram/data elimination::
10913 * Compilation options::
10914 * Example of unused subprogram/data elimination::
10915 @end menu
10916
10917 @node About unused subprogram/data elimination
10918 @subsection About unused subprogram/data elimination
10919
10920 @noindent
10921 By default, an executable contains all code and data of its composing objects
10922 (directly linked or coming from statically linked libraries), even data or code
10923 never used by this executable.
10924
10925 This feature will allow you to eliminate such unused code from your
10926 executable, making it smaller (in disk and in memory).
10927
10928 This functionality is available on all Linux platforms except for the IA-64
10929 architecture and on all cross platforms using the ELF binary file format.
10930 In both cases GNU binutils version 2.16 or later are required to enable it.
10931
10932 @node Compilation options
10933 @subsection Compilation options
10934
10935 @noindent
10936 The operation of eliminating the unused code and data from the final executable
10937 is directly performed by the linker.
10938
10939 In order to do this, it has to work with objects compiled with the
10940 following options:
10941 @option{-ffunction-sections} @option{-fdata-sections}.
10942 @cindex @option{-ffunction-sections} (@command{gcc})
10943 @cindex @option{-fdata-sections} (@command{gcc})
10944 These options are usable with C and Ada files.
10945 They will place respectively each
10946 function or data in a separate section in the resulting object file.
10947
10948 Once the objects and static libraries are created with these options, the
10949 linker can perform the dead code elimination. You can do this by setting
10950 the @option{-Wl,--gc-sections} option to gcc command or in the
10951 @option{-largs} section of @command{gnatmake}. This will perform a
10952 garbage collection of code and data never referenced.
10953
10954 If the linker performs a partial link (@option{-r} ld linker option), then you
10955 will need to provide one or several entry point using the
10956 @option{-e} / @option{--entry} ld option.
10957
10958 Note that objects compiled without the @option{-ffunction-sections} and
10959 @option{-fdata-sections} options can still be linked with the executable.
10960 However, no dead code elimination will be performed on those objects (they will
10961 be linked as is).
10962
10963 The GNAT static library is now compiled with -ffunction-sections and
10964 -fdata-sections on some platforms. This allows you to eliminate the unused code
10965 and data of the GNAT library from your executable.
10966
10967 @node Example of unused subprogram/data elimination
10968 @subsection Example of unused subprogram/data elimination
10969
10970 @noindent
10971 Here is a simple example:
10972
10973 @smallexample @c ada
10974 with Aux;
10975
10976 procedure Test is
10977 begin
10978    Aux.Used (10);
10979 end Test;
10980
10981 package Aux is
10982    Used_Data   : Integer;
10983    Unused_Data : Integer;
10984
10985    procedure Used   (Data : Integer);
10986    procedure Unused (Data : Integer);
10987 end Aux;
10988
10989 package body Aux is
10990    procedure Used (Data : Integer) is
10991    begin
10992       Used_Data := Data;
10993    end Used;
10994
10995    procedure Unused (Data : Integer) is
10996    begin
10997       Unused_Data := Data;
10998    end Unused;
10999 end Aux;
11000 @end smallexample
11001
11002 @noindent
11003 @code{Unused} and @code{Unused_Data} are never referenced in this code
11004 excerpt, and hence they may be safely removed from the final executable.
11005
11006 @smallexample
11007 $ gnatmake test
11008
11009 $ nm test | grep used
11010 020015f0 T aux__unused
11011 02005d88 B aux__unused_data
11012 020015cc T aux__used
11013 02005d84 B aux__used_data
11014
11015 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11016      -largs -Wl,--gc-sections
11017
11018 $ nm test | grep used
11019 02005350 T aux__used
11020 0201ffe0 B aux__used_data
11021 @end smallexample
11022
11023 @noindent
11024 It can be observed that the procedure @code{Unused} and the object
11025 @code{Unused_Data} are removed by the linker when using the
11026 appropriate options.
11027
11028 @c ********************************
11029 @node Renaming Files Using gnatchop
11030 @chapter Renaming Files Using @code{gnatchop}
11031 @findex gnatchop
11032
11033 @noindent
11034 This chapter discusses how to handle files with multiple units by using
11035 the @code{gnatchop} utility. This utility is also useful in renaming
11036 files to meet the standard GNAT default file naming conventions.
11037
11038 @menu
11039 * Handling Files with Multiple Units::
11040 * Operating gnatchop in Compilation Mode::
11041 * Command Line for gnatchop::
11042 * Switches for gnatchop::
11043 * Examples of gnatchop Usage::
11044 @end menu
11045
11046 @node Handling Files with Multiple Units
11047 @section Handling Files with Multiple Units
11048
11049 @noindent
11050 The basic compilation model of GNAT requires that a file submitted to the
11051 compiler have only one unit and there be a strict correspondence
11052 between the file name and the unit name.
11053
11054 The @code{gnatchop} utility allows both of these rules to be relaxed,
11055 allowing GNAT to process files which contain multiple compilation units
11056 and files with arbitrary file names. @code{gnatchop}
11057 reads the specified file and generates one or more output files,
11058 containing one unit per file. The unit and the file name correspond,
11059 as required by GNAT.
11060
11061 If you want to permanently restructure a set of ``foreign'' files so that
11062 they match the GNAT rules, and do the remaining development using the
11063 GNAT structure, you can simply use @command{gnatchop} once, generate the
11064 new set of files and work with them from that point on.
11065
11066 Alternatively, if you want to keep your files in the ``foreign'' format,
11067 perhaps to maintain compatibility with some other Ada compilation
11068 system, you can set up a procedure where you use @command{gnatchop} each
11069 time you compile, regarding the source files that it writes as temporary
11070 files that you throw away.
11071
11072 Note that if your file containing multiple units starts with a byte order
11073 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11074 will each start with a copy of this BOM, meaning that they can be compiled
11075 automatically in UTF-8 mode without needing to specify an explicit encoding.
11076
11077 @node Operating gnatchop in Compilation Mode
11078 @section Operating gnatchop in Compilation Mode
11079
11080 @noindent
11081 The basic function of @code{gnatchop} is to take a file with multiple units
11082 and split it into separate files. The boundary between files is reasonably
11083 clear, except for the issue of comments and pragmas. In default mode, the
11084 rule is that any pragmas between units belong to the previous unit, except
11085 that configuration pragmas always belong to the following unit. Any comments
11086 belong to the following unit. These rules
11087 almost always result in the right choice of
11088 the split point without needing to mark it explicitly and most users will
11089 find this default to be what they want. In this default mode it is incorrect to
11090 submit a file containing only configuration pragmas, or one that ends in
11091 configuration pragmas, to @code{gnatchop}.
11092
11093 However, using a special option to activate ``compilation mode'',
11094 @code{gnatchop}
11095 can perform another function, which is to provide exactly the semantics
11096 required by the RM for handling of configuration pragmas in a compilation.
11097 In the absence of configuration pragmas (at the main file level), this
11098 option has no effect, but it causes such configuration pragmas to be handled
11099 in a quite different manner.
11100
11101 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11102 only configuration pragmas, then this file is appended to the
11103 @file{gnat.adc} file in the current directory. This behavior provides
11104 the required behavior described in the RM for the actions to be taken
11105 on submitting such a file to the compiler, namely that these pragmas
11106 should apply to all subsequent compilations in the same compilation
11107 environment. Using GNAT, the current directory, possibly containing a
11108 @file{gnat.adc} file is the representation
11109 of a compilation environment. For more information on the
11110 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11111
11112 Second, in compilation mode, if @code{gnatchop}
11113 is given a file that starts with
11114 configuration pragmas, and contains one or more units, then these
11115 configuration pragmas are prepended to each of the chopped files. This
11116 behavior provides the required behavior described in the RM for the
11117 actions to be taken on compiling such a file, namely that the pragmas
11118 apply to all units in the compilation, but not to subsequently compiled
11119 units.
11120
11121 Finally, if configuration pragmas appear between units, they are appended
11122 to the previous unit. This results in the previous unit being illegal,
11123 since the compiler does not accept configuration pragmas that follow
11124 a unit. This provides the required RM behavior that forbids configuration
11125 pragmas other than those preceding the first compilation unit of a
11126 compilation.
11127
11128 For most purposes, @code{gnatchop} will be used in default mode. The
11129 compilation mode described above is used only if you need exactly
11130 accurate behavior with respect to compilations, and you have files
11131 that contain multiple units and configuration pragmas. In this
11132 circumstance the use of @code{gnatchop} with the compilation mode
11133 switch provides the required behavior, and is for example the mode
11134 in which GNAT processes the ACVC tests.
11135
11136 @node Command Line for gnatchop
11137 @section Command Line for @code{gnatchop}
11138
11139 @noindent
11140 The @code{gnatchop} command has the form:
11141
11142 @smallexample
11143 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11144 @c      @ovar{directory}
11145 @c Expanding @ovar macro inline (explanation in macro def comments)
11146 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11147       @r{[}@var{directory}@r{]}
11148 @end smallexample
11149
11150 @noindent
11151 The only required argument is the file name of the file to be chopped.
11152 There are no restrictions on the form of this file name. The file itself
11153 contains one or more Ada units, in normal GNAT format, concatenated
11154 together. As shown, more than one file may be presented to be chopped.
11155
11156 When run in default mode, @code{gnatchop} generates one output file in
11157 the current directory for each unit in each of the files.
11158
11159 @var{directory}, if specified, gives the name of the directory to which
11160 the output files will be written. If it is not specified, all files are
11161 written to the current directory.
11162
11163 For example, given a
11164 file called @file{hellofiles} containing
11165
11166 @smallexample @c ada
11167 @group
11168 @cartouche
11169 procedure hello;
11170
11171 with Text_IO; use Text_IO;
11172 procedure hello is
11173 begin
11174    Put_Line ("Hello");
11175 end hello;
11176 @end cartouche
11177 @end group
11178 @end smallexample
11179
11180 @noindent
11181 the command
11182
11183 @smallexample
11184 $ gnatchop ^hellofiles^HELLOFILES.^
11185 @end smallexample
11186
11187 @noindent
11188 generates two files in the current directory, one called
11189 @file{hello.ads} containing the single line that is the procedure spec,
11190 and the other called @file{hello.adb} containing the remaining text. The
11191 original file is not affected. The generated files can be compiled in
11192 the normal manner.
11193
11194 @noindent
11195 When gnatchop is invoked on a file that is empty or that contains only empty
11196 lines and/or comments, gnatchop will not fail, but will not produce any
11197 new sources.
11198
11199 For example, given a
11200 file called @file{toto.txt} containing
11201
11202 @smallexample @c ada
11203 @group
11204 @cartouche
11205 --  Just a comment
11206 @end cartouche
11207 @end group
11208 @end smallexample
11209
11210 @noindent
11211 the command
11212
11213 @smallexample
11214 $ gnatchop ^toto.txt^TOT.TXT^
11215 @end smallexample
11216
11217 @noindent
11218 will not produce any new file and will result in the following warnings:
11219
11220 @smallexample
11221 toto.txt:1:01: warning: empty file, contains no compilation units
11222 no compilation units found
11223 no source files written
11224 @end smallexample
11225
11226 @node Switches for gnatchop
11227 @section Switches for @code{gnatchop}
11228
11229 @noindent
11230 @command{gnatchop} recognizes the following switches:
11231
11232 @table @option
11233 @c !sort!
11234
11235 @item --version
11236 @cindex @option{--version} @command{gnatchop}
11237 Display Copyright and version, then exit disregarding all other options.
11238
11239 @item --help
11240 @cindex @option{--help} @command{gnatchop}
11241 If @option{--version} was not used, display usage, then exit disregarding
11242 all other options.
11243
11244 @item ^-c^/COMPILATION^
11245 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11246 Causes @code{gnatchop} to operate in compilation mode, in which
11247 configuration pragmas are handled according to strict RM rules. See
11248 previous section for a full description of this mode.
11249
11250 @ifclear vms
11251 @item -gnat@var{xxx}
11252 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11253 used to parse the given file. Not all @var{xxx} options make sense,
11254 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11255 process a source file that uses Latin-2 coding for identifiers.
11256 @end ifclear
11257
11258 @item ^-h^/HELP^
11259 Causes @code{gnatchop} to generate a brief help summary to the standard
11260 output file showing usage information.
11261
11262 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11263 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11264 Limit generated file names to the specified number @code{mm}
11265 of characters.
11266 This is useful if the
11267 resulting set of files is required to be interoperable with systems
11268 which limit the length of file names.
11269 @ifset vms
11270 If no value is given, or
11271 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11272 a default of 39, suitable for OpenVMS Alpha
11273 Systems, is assumed
11274 @end ifset
11275 @ifclear vms
11276 No space is allowed between the @option{-k} and the numeric value. The numeric
11277 value may be omitted in which case a default of @option{-k8},
11278 suitable for use
11279 with DOS-like file systems, is used. If no @option{-k} switch
11280 is present then
11281 there is no limit on the length of file names.
11282 @end ifclear
11283
11284 @item ^-p^/PRESERVE^
11285 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11286 Causes the file ^modification^creation^ time stamp of the input file to be
11287 preserved and used for the time stamp of the output file(s). This may be
11288 useful for preserving coherency of time stamps in an environment where
11289 @code{gnatchop} is used as part of a standard build process.
11290
11291 @item ^-q^/QUIET^
11292 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11293 Causes output of informational messages indicating the set of generated
11294 files to be suppressed. Warnings and error messages are unaffected.
11295
11296 @item ^-r^/REFERENCE^
11297 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11298 @findex Source_Reference
11299 Generate @code{Source_Reference} pragmas. Use this switch if the output
11300 files are regarded as temporary and development is to be done in terms
11301 of the original unchopped file. This switch causes
11302 @code{Source_Reference} pragmas to be inserted into each of the
11303 generated files to refers back to the original file name and line number.
11304 The result is that all error messages refer back to the original
11305 unchopped file.
11306 In addition, the debugging information placed into the object file (when
11307 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11308 specified)
11309 also refers back to this original file so that tools like profilers and
11310 debuggers will give information in terms of the original unchopped file.
11311
11312 If the original file to be chopped itself contains
11313 a @code{Source_Reference}
11314 pragma referencing a third file, then gnatchop respects
11315 this pragma, and the generated @code{Source_Reference} pragmas
11316 in the chopped file refer to the original file, with appropriate
11317 line numbers. This is particularly useful when @code{gnatchop}
11318 is used in conjunction with @code{gnatprep} to compile files that
11319 contain preprocessing statements and multiple units.
11320
11321 @item ^-v^/VERBOSE^
11322 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11323 Causes @code{gnatchop} to operate in verbose mode. The version
11324 number and copyright notice are output, as well as exact copies of
11325 the gnat1 commands spawned to obtain the chop control information.
11326
11327 @item ^-w^/OVERWRITE^
11328 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11329 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11330 fatal error if there is already a file with the same name as a
11331 file it would otherwise output, in other words if the files to be
11332 chopped contain duplicated units. This switch bypasses this
11333 check, and causes all but the last instance of such duplicated
11334 units to be skipped.
11335
11336 @ifclear vms
11337 @item --GCC=@var{xxxx}
11338 @cindex @option{--GCC=} (@code{gnatchop})
11339 Specify the path of the GNAT parser to be used. When this switch is used,
11340 no attempt is made to add the prefix to the GNAT parser executable.
11341 @end ifclear
11342 @end table
11343
11344 @node Examples of gnatchop Usage
11345 @section Examples of @code{gnatchop} Usage
11346
11347 @table @code
11348 @ifset vms
11349 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11350 @end ifset
11351 @ifclear vms
11352 @item gnatchop -w hello_s.ada prerelease/files
11353 @end ifclear
11354
11355 Chops the source file @file{hello_s.ada}. The output files will be
11356 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11357 overwriting any
11358 files with matching names in that directory (no files in the current
11359 directory are modified).
11360
11361 @item gnatchop ^archive^ARCHIVE.^
11362 Chops the source file @file{^archive^ARCHIVE.^}
11363 into the current directory. One
11364 useful application of @code{gnatchop} is in sending sets of sources
11365 around, for example in email messages. The required sources are simply
11366 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11367 command), and then
11368 @command{gnatchop} is used at the other end to reconstitute the original
11369 file names.
11370
11371 @item gnatchop file1 file2 file3 direc
11372 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11373 the resulting files in the directory @file{direc}. Note that if any units
11374 occur more than once anywhere within this set of files, an error message
11375 is generated, and no files are written. To override this check, use the
11376 @option{^-w^/OVERWRITE^} switch,
11377 in which case the last occurrence in the last file will
11378 be the one that is output, and earlier duplicate occurrences for a given
11379 unit will be skipped.
11380 @end table
11381
11382 @node Configuration Pragmas
11383 @chapter Configuration Pragmas
11384 @cindex Configuration pragmas
11385 @cindex Pragmas, configuration
11386
11387 @noindent
11388 Configuration pragmas include those pragmas described as
11389 such in the Ada Reference Manual, as well as
11390 implementation-dependent pragmas that are configuration pragmas.
11391 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11392 for details on these additional GNAT-specific configuration pragmas.
11393 Most notably, the pragma @code{Source_File_Name}, which allows
11394 specifying non-default names for source files, is a configuration
11395 pragma. The following is a complete list of configuration pragmas
11396 recognized by GNAT:
11397
11398 @smallexample
11399    Ada_83
11400    Ada_95
11401    Ada_05
11402    Ada_2005
11403    Ada_12
11404    Ada_2012
11405    Assertion_Policy
11406    Assume_No_Invalid_Values
11407    C_Pass_By_Copy
11408    Check_Name
11409    Check_Policy
11410    Compile_Time_Error
11411    Compile_Time_Warning
11412    Compiler_Unit
11413    Component_Alignment
11414    Convention_Identifier
11415    Debug_Policy
11416    Detect_Blocking
11417    Discard_Names
11418    Elaboration_Checks
11419    Eliminate
11420    Extend_System
11421    Extensions_Allowed
11422    External_Name_Casing
11423    Fast_Math
11424    Favor_Top_Level
11425    Float_Representation
11426    Implicit_Packing
11427    Initialize_Scalars
11428    Interrupt_State
11429    License
11430    Locking_Policy
11431    Long_Float
11432    No_Run_Time
11433    No_Strict_Aliasing
11434    Normalize_Scalars
11435    Optimize_Alignment
11436    Persistent_BSS
11437    Polling
11438    Priority_Specific_Dispatching
11439    Profile
11440    Profile_Warnings
11441    Propagate_Exceptions
11442    Queuing_Policy
11443    Ravenscar
11444    Restricted_Run_Time
11445    Restrictions
11446    Restrictions_Warnings
11447    Reviewable
11448    Short_Circuit_And_Or
11449    Source_File_Name
11450    Source_File_Name_Project
11451    Style_Checks
11452    Suppress
11453    Suppress_Exception_Locations
11454    Task_Dispatching_Policy
11455    Universal_Data
11456    Unsuppress
11457    Use_VADS_Size
11458    Validity_Checks
11459    Warnings
11460    Wide_Character_Encoding
11461
11462 @end smallexample
11463
11464 @menu
11465 * Handling of Configuration Pragmas::
11466 * The Configuration Pragmas Files::
11467 @end menu
11468
11469 @node Handling of Configuration Pragmas
11470 @section Handling of Configuration Pragmas
11471
11472 Configuration pragmas may either appear at the start of a compilation
11473 unit, in which case they apply only to that unit, or they may apply to
11474 all compilations performed in a given compilation environment.
11475
11476 GNAT also provides the @code{gnatchop} utility to provide an automatic
11477 way to handle configuration pragmas following the semantics for
11478 compilations (that is, files with multiple units), described in the RM.
11479 See @ref{Operating gnatchop in Compilation Mode} for details.
11480 However, for most purposes, it will be more convenient to edit the
11481 @file{gnat.adc} file that contains configuration pragmas directly,
11482 as described in the following section.
11483
11484 @node The Configuration Pragmas Files
11485 @section The Configuration Pragmas Files
11486 @cindex @file{gnat.adc}
11487
11488 @noindent
11489 In GNAT a compilation environment is defined by the current
11490 directory at the time that a compile command is given. This current
11491 directory is searched for a file whose name is @file{gnat.adc}. If
11492 this file is present, it is expected to contain one or more
11493 configuration pragmas that will be applied to the current compilation.
11494 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11495 considered.
11496
11497 Configuration pragmas may be entered into the @file{gnat.adc} file
11498 either by running @code{gnatchop} on a source file that consists only of
11499 configuration pragmas, or more conveniently  by
11500 direct editing of the @file{gnat.adc} file, which is a standard format
11501 source file.
11502
11503 In addition to @file{gnat.adc}, additional files containing configuration
11504 pragmas may be applied to the current compilation using the switch
11505 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11506 contains only configuration pragmas. These configuration pragmas are
11507 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11508 is present and switch @option{-gnatA} is not used).
11509
11510 It is allowed to specify several switches @option{-gnatec}, all of which
11511 will be taken into account.
11512
11513 If you are using project file, a separate mechanism is provided using
11514 project attributes, see @ref{Specifying Configuration Pragmas} for more
11515 details.
11516
11517 @ifset vms
11518 Of special interest to GNAT OpenVMS Alpha is the following
11519 configuration pragma:
11520
11521 @smallexample @c ada
11522 @cartouche
11523 pragma Extend_System (Aux_DEC);
11524 @end cartouche
11525 @end smallexample
11526
11527 @noindent
11528 In the presence of this pragma, GNAT adds to the definition of the
11529 predefined package SYSTEM all the additional types and subprograms that are
11530 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11531 @end ifset
11532
11533 @node Handling Arbitrary File Naming Conventions Using gnatname
11534 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11535 @cindex Arbitrary File Naming Conventions
11536
11537 @menu
11538 * Arbitrary File Naming Conventions::
11539 * Running gnatname::
11540 * Switches for gnatname::
11541 * Examples of gnatname Usage::
11542 @end menu
11543
11544 @node Arbitrary File Naming Conventions
11545 @section Arbitrary File Naming Conventions
11546
11547 @noindent
11548 The GNAT compiler must be able to know the source file name of a compilation
11549 unit.  When using the standard GNAT default file naming conventions
11550 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11551 does not need additional information.
11552
11553 @noindent
11554 When the source file names do not follow the standard GNAT default file naming
11555 conventions, the GNAT compiler must be given additional information through
11556 a configuration pragmas file (@pxref{Configuration Pragmas})
11557 or a project file.
11558 When the non-standard file naming conventions are well-defined,
11559 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11560 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11561 if the file naming conventions are irregular or arbitrary, a number
11562 of pragma @code{Source_File_Name} for individual compilation units
11563 must be defined.
11564 To help maintain the correspondence between compilation unit names and
11565 source file names within the compiler,
11566 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11567 set of files.
11568
11569 @node Running gnatname
11570 @section Running @code{gnatname}
11571
11572 @noindent
11573 The usual form of the @code{gnatname} command is
11574
11575 @smallexample
11576 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11577 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11578 @c Expanding @ovar macro inline (explanation in macro def comments)
11579 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11580       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11581 @end smallexample
11582
11583 @noindent
11584 All of the arguments are optional. If invoked without any argument,
11585 @code{gnatname} will display its usage.
11586
11587 @noindent
11588 When used with at least one naming pattern, @code{gnatname} will attempt to
11589 find all the compilation units in files that follow at least one of the
11590 naming patterns. To find these compilation units,
11591 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11592 regular files.
11593
11594 @noindent
11595 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11596 Each Naming Pattern is enclosed between double quotes (or single
11597 quotes on Windows).
11598 A Naming Pattern is a regular expression similar to the wildcard patterns
11599 used in file names by the Unix shells or the DOS prompt.
11600
11601 @noindent
11602 @code{gnatname} may be called with several sections of directories/patterns.
11603 Sections are separated by switch @code{--and}. In each section, there must be
11604 at least one pattern. If no directory is specified in a section, the current
11605 directory (or the project directory is @code{-P} is used) is implied.
11606 The options other that the directory switches and the patterns apply globally
11607 even if they are in different sections.
11608
11609 @noindent
11610 Examples of Naming Patterns are
11611
11612 @smallexample
11613    "*.[12].ada"
11614    "*.ad[sb]*"
11615    "body_*"    "spec_*"
11616 @end smallexample
11617
11618 @noindent
11619 For a more complete description of the syntax of Naming Patterns,
11620 see the second kind of regular expressions described in @file{g-regexp.ads}
11621 (the ``Glob'' regular expressions).
11622
11623 @noindent
11624 When invoked with no switch @code{-P}, @code{gnatname} will create a
11625 configuration pragmas file @file{gnat.adc} in the current working directory,
11626 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11627 unit.
11628
11629 @node Switches for gnatname
11630 @section Switches for @code{gnatname}
11631
11632 @noindent
11633 Switches for @code{gnatname} must precede any specified Naming Pattern.
11634
11635 @noindent
11636 You may specify any of the following switches to @code{gnatname}:
11637
11638 @table @option
11639 @c !sort!
11640
11641 @item --version
11642 @cindex @option{--version} @command{gnatname}
11643 Display Copyright and version, then exit disregarding all other options.
11644
11645 @item --help
11646 @cindex @option{--help} @command{gnatname}
11647 If @option{--version} was not used, display usage, then exit disregarding
11648 all other options.
11649
11650 @item --and
11651 Start another section of directories/patterns.
11652
11653 @item ^-c^/CONFIG_FILE=^@file{file}
11654 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11655 Create a configuration pragmas file @file{file} (instead of the default
11656 @file{gnat.adc}).
11657 @ifclear vms
11658 There may be zero, one or more space between @option{-c} and
11659 @file{file}.
11660 @end ifclear
11661 @file{file} may include directory information. @file{file} must be
11662 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11663 When a switch @option{^-c^/CONFIG_FILE^} is
11664 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11665
11666 @item ^-d^/SOURCE_DIRS=^@file{dir}
11667 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11668 Look for source files in directory @file{dir}. There may be zero, one or more
11669 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11670 When a switch @option{^-d^/SOURCE_DIRS^}
11671 is specified, the current working directory will not be searched for source
11672 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11673 or @option{^-D^/DIR_FILES^} switch.
11674 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11675 If @file{dir} is a relative path, it is relative to the directory of
11676 the configuration pragmas file specified with switch
11677 @option{^-c^/CONFIG_FILE^},
11678 or to the directory of the project file specified with switch
11679 @option{^-P^/PROJECT_FILE^} or,
11680 if neither switch @option{^-c^/CONFIG_FILE^}
11681 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11682 current working directory. The directory
11683 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11684
11685 @item ^-D^/DIRS_FILE=^@file{file}
11686 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11687 Look for source files in all directories listed in text file @file{file}.
11688 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11689 and @file{file}.
11690 @file{file} must be an existing, readable text file.
11691 Each nonempty line in @file{file} must be a directory.
11692 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11693 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11694 @file{file}.
11695
11696 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11697 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11698 Foreign patterns. Using this switch, it is possible to add sources of languages
11699 other than Ada to the list of sources of a project file.
11700 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11701 For example,
11702 @smallexample
11703 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11704 @end smallexample
11705 @noindent
11706 will look for Ada units in all files with the @file{.ada} extension,
11707 and will add to the list of file for project @file{prj.gpr} the C files
11708 with extension @file{.^c^C^}.
11709
11710 @item ^-h^/HELP^
11711 @cindex @option{^-h^/HELP^} (@code{gnatname})
11712 Output usage (help) information. The output is written to @file{stdout}.
11713
11714 @item ^-P^/PROJECT_FILE=^@file{proj}
11715 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11716 Create or update project file @file{proj}. There may be zero, one or more space
11717 between @option{-P} and @file{proj}. @file{proj} may include directory
11718 information. @file{proj} must be writable.
11719 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11720 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11721 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11722
11723 @item ^-v^/VERBOSE^
11724 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11725 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11726 This includes name of the file written, the name of the directories to search
11727 and, for each file in those directories whose name matches at least one of
11728 the Naming Patterns, an indication of whether the file contains a unit,
11729 and if so the name of the unit.
11730
11731 @item ^-v -v^/VERBOSE /VERBOSE^
11732 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11733 Very Verbose mode. In addition to the output produced in verbose mode,
11734 for each file in the searched directories whose name matches none of
11735 the Naming Patterns, an indication is given that there is no match.
11736
11737 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11738 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11739 Excluded patterns. Using this switch, it is possible to exclude some files
11740 that would match the name patterns. For example,
11741 @smallexample
11742 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11743 @end smallexample
11744 @noindent
11745 will look for Ada units in all files with the @file{.ada} extension,
11746 except those whose names end with @file{_nt.ada}.
11747
11748 @end table
11749
11750 @node Examples of gnatname Usage
11751 @section Examples of @code{gnatname} Usage
11752
11753 @ifset vms
11754 @smallexample
11755 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11756 @end smallexample
11757 @end ifset
11758
11759 @ifclear vms
11760 @smallexample
11761 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11762 @end smallexample
11763 @end ifclear
11764
11765 @noindent
11766 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11767 and be writable. In addition, the directory
11768 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11769 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11770
11771 @ifclear vms
11772 Note the optional spaces after @option{-c} and @option{-d}.
11773 @end ifclear
11774
11775 @smallexample
11776 @ifclear vms
11777 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11778   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11779 @end ifclear
11780 @ifset vms
11781 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11782   /EXCLUDED_PATTERN=*_nt_body.ada
11783   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11784   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11785 @end ifset
11786 @end smallexample
11787
11788 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11789 even in conjunction with one or several switches
11790 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11791 are used in this example.
11792
11793 @c *****************************************
11794 @c * G N A T  P r o j e c t  M a n a g e r *
11795 @c *****************************************
11796
11797 @c ------ macros for projects.texi
11798 @c These macros are needed when building the gprbuild documentation, but
11799 @c should have no effect in the gnat user's guide
11800
11801 @macro CODESAMPLE{TXT}
11802 @smallexample
11803 @group
11804 \TXT\
11805 @end group
11806 @end smallexample
11807 @end macro
11808
11809 @macro PROJECTFILE{TXT}
11810 @CODESAMPLE{\TXT\}
11811 @end macro
11812
11813 @c simulates a newline when in a @CODESAMPLE
11814 @macro NL{}
11815 @end macro
11816
11817 @macro TIP{TXT}
11818 @quotation
11819 @noindent
11820 \TXT\
11821 @end quotation
11822 @end macro
11823
11824 @macro TIPHTML{TXT}
11825 \TXT\
11826 @end macro
11827
11828 @macro IMPORTANT{TXT}
11829 @quotation
11830 @noindent
11831 \TXT\
11832 @end quotation
11833
11834 @end macro
11835
11836 @macro NOTE{TXT}
11837 @quotation
11838 @noindent
11839 \TXT\
11840 @end quotation
11841 @end macro
11842
11843 @include projects.texi
11844
11845 @c *****************************************
11846 @c * Cross-referencing tools
11847 @c *****************************************
11848
11849 @node The Cross-Referencing Tools gnatxref and gnatfind
11850 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11851 @findex gnatxref
11852 @findex gnatfind
11853
11854 @noindent
11855 The compiler generates cross-referencing information (unless
11856 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
11857 This information indicates where in the source each entity is declared and
11858 referenced. Note that entities in package Standard are not included, but
11859 entities in all other predefined units are included in the output.
11860
11861 Before using any of these two tools, you need to compile successfully your
11862 application, so that GNAT gets a chance to generate the cross-referencing
11863 information.
11864
11865 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
11866 information to provide the user with the capability to easily locate the
11867 declaration and references to an entity. These tools are quite similar,
11868 the difference being that @code{gnatfind} is intended for locating
11869 definitions and/or references to a specified entity or entities, whereas
11870 @code{gnatxref} is oriented to generating a full report of all
11871 cross-references.
11872
11873 To use these tools, you must not compile your application using the
11874 @option{-gnatx} switch on the @command{gnatmake} command line
11875 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
11876 information will not be generated.
11877
11878 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
11879 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
11880
11881 @menu
11882 * Switches for gnatxref::
11883 * Switches for gnatfind::
11884 * Project Files for gnatxref and gnatfind::
11885 * Regular Expressions in gnatfind and gnatxref::
11886 * Examples of gnatxref Usage::
11887 * Examples of gnatfind Usage::
11888 @end menu
11889
11890 @node Switches for gnatxref
11891 @section @code{gnatxref} Switches
11892
11893 @noindent
11894 The command invocation for @code{gnatxref} is:
11895 @smallexample
11896 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11897 @c Expanding @ovar macro inline (explanation in macro def comments)
11898 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11899 @end smallexample
11900
11901 @noindent
11902 where
11903
11904 @table @var
11905 @item sourcefile1
11906 @itemx sourcefile2
11907 identifies the source files for which a report is to be generated. The
11908 ``with''ed units will be processed too. You must provide at least one file.
11909
11910 These file names are considered to be regular expressions, so for instance
11911 specifying @file{source*.adb} is the same as giving every file in the current
11912 directory whose name starts with @file{source} and whose extension is
11913 @file{adb}.
11914
11915 You shouldn't specify any directory name, just base names. @command{gnatxref}
11916 and @command{gnatfind} will be able to locate these files by themselves using
11917 the source path. If you specify directories, no result is produced.
11918
11919 @end table
11920
11921 @noindent
11922 The switches can be:
11923 @table @option
11924 @c !sort!
11925 @item --version
11926 @cindex @option{--version} @command{gnatxref}
11927 Display Copyright and version, then exit disregarding all other options.
11928
11929 @item --help
11930 @cindex @option{--help} @command{gnatxref}
11931 If @option{--version} was not used, display usage, then exit disregarding
11932 all other options.
11933
11934 @item ^-a^/ALL_FILES^
11935 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
11936 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
11937 the read-only files found in the library search path. Otherwise, these files
11938 will be ignored. This option can be used to protect Gnat sources or your own
11939 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
11940 much faster, and their output much smaller. Read-only here refers to access
11941 or permissions status in the file system for the current user.
11942
11943 @item -aIDIR
11944 @cindex @option{-aIDIR} (@command{gnatxref})
11945 When looking for source files also look in directory DIR. The order in which
11946 source file search is undertaken is the same as for @command{gnatmake}.
11947
11948 @item -aODIR
11949 @cindex @option{-aODIR} (@command{gnatxref})
11950 When searching for library and object files, look in directory
11951 DIR. The order in which library files are searched is the same as for
11952 @command{gnatmake}.
11953
11954 @item -nostdinc
11955 @cindex @option{-nostdinc} (@command{gnatxref})
11956 Do not look for sources in the system default directory.
11957
11958 @item -nostdlib
11959 @cindex @option{-nostdlib} (@command{gnatxref})
11960 Do not look for library files in the system default directory.
11961
11962 @item --ext=@var{extension}
11963 @cindex @option{--ext} (@command{gnatxref})
11964 Specify an alternate ali file extension. The default is @code{ali} and other
11965 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
11966 switch. Note that if this switch overrides the default, which means that only
11967 the new extension will be considered.
11968
11969 @item --RTS=@var{rts-path}
11970 @cindex @option{--RTS} (@command{gnatxref})
11971 Specifies the default location of the runtime library. Same meaning as the
11972 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
11973
11974 @item ^-d^/DERIVED_TYPES^
11975 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
11976 If this switch is set @code{gnatxref} will output the parent type
11977 reference for each matching derived types.
11978
11979 @item ^-f^/FULL_PATHNAME^
11980 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
11981 If this switch is set, the output file names will be preceded by their
11982 directory (if the file was found in the search path). If this switch is
11983 not set, the directory will not be printed.
11984
11985 @item ^-g^/IGNORE_LOCALS^
11986 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
11987 If this switch is set, information is output only for library-level
11988 entities, ignoring local entities. The use of this switch may accelerate
11989 @code{gnatfind} and @code{gnatxref}.
11990
11991 @item -IDIR
11992 @cindex @option{-IDIR} (@command{gnatxref})
11993 Equivalent to @samp{-aODIR -aIDIR}.
11994
11995 @item -pFILE
11996 @cindex @option{-pFILE} (@command{gnatxref})
11997 Specify a project file to use @xref{GNAT Project Manager}.
11998 If you need to use the @file{.gpr}
11999 project files, you should use gnatxref through the GNAT driver
12000 (@command{gnat xref -Pproject}).
12001
12002 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12003 project file in the current directory.
12004
12005 If a project file is either specified or found by the tools, then the content
12006 of the source directory and object directory lines are added as if they
12007 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12008 and @samp{^-aO^OBJECT_SEARCH^}.
12009 @item ^-u^/UNUSED^
12010 Output only unused symbols. This may be really useful if you give your
12011 main compilation unit on the command line, as @code{gnatxref} will then
12012 display every unused entity and 'with'ed package.
12013
12014 @ifclear vms
12015 @item -v
12016 Instead of producing the default output, @code{gnatxref} will generate a
12017 @file{tags} file that can be used by vi. For examples how to use this
12018 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12019 to the standard output, thus you will have to redirect it to a file.
12020 @end ifclear
12021
12022 @end table
12023
12024 @noindent
12025 All these switches may be in any order on the command line, and may even
12026 appear after the file names. They need not be separated by spaces, thus
12027 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12028 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12029
12030 @node Switches for gnatfind
12031 @section @code{gnatfind} Switches
12032
12033 @noindent
12034 The command line for @code{gnatfind} is:
12035
12036 @smallexample
12037 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12038 @c       @r{[}@var{file1} @var{file2} @dots{}]
12039 @c Expanding @ovar macro inline (explanation in macro def comments)
12040 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12041       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12042 @end smallexample
12043
12044 @noindent
12045 where
12046
12047 @table @var
12048 @item pattern
12049 An entity will be output only if it matches the regular expression found
12050 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12051
12052 Omitting the pattern is equivalent to specifying @samp{*}, which
12053 will match any entity. Note that if you do not provide a pattern, you
12054 have to provide both a sourcefile and a line.
12055
12056 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12057 for matching purposes. At the current time there is no support for
12058 8-bit codes other than Latin-1, or for wide characters in identifiers.
12059
12060 @item sourcefile
12061 @code{gnatfind} will look for references, bodies or declarations
12062 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12063 and column @var{column}. See @ref{Examples of gnatfind Usage}
12064 for syntax examples.
12065
12066 @item line
12067 is a decimal integer identifying the line number containing
12068 the reference to the entity (or entities) to be located.
12069
12070 @item column
12071 is a decimal integer identifying the exact location on the
12072 line of the first character of the identifier for the
12073 entity reference. Columns are numbered from 1.
12074
12075 @item file1 file2 @dots{}
12076 The search will be restricted to these source files. If none are given, then
12077 the search will be done for every library file in the search path.
12078 These file must appear only after the pattern or sourcefile.
12079
12080 These file names are considered to be regular expressions, so for instance
12081 specifying @file{source*.adb} is the same as giving every file in the current
12082 directory whose name starts with @file{source} and whose extension is
12083 @file{adb}.
12084
12085 The location of the spec of the entity will always be displayed, even if it
12086 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12087 occurrences of the entity in the separate units of the ones given on the
12088 command line will also be displayed.
12089
12090 Note that if you specify at least one file in this part, @code{gnatfind} may
12091 sometimes not be able to find the body of the subprograms.
12092
12093 @end table
12094
12095 @noindent
12096 At least one of 'sourcefile' or 'pattern' has to be present on
12097 the command line.
12098
12099 The following switches are available:
12100 @table @option
12101 @c !sort!
12102
12103 @cindex @option{--version} @command{gnatfind}
12104 Display Copyright and version, then exit disregarding all other options.
12105
12106 @item --help
12107 @cindex @option{--help} @command{gnatfind}
12108 If @option{--version} was not used, display usage, then exit disregarding
12109 all other options.
12110
12111 @item ^-a^/ALL_FILES^
12112 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12113 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12114 the read-only files found in the library search path. Otherwise, these files
12115 will be ignored. This option can be used to protect Gnat sources or your own
12116 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12117 much faster, and their output much smaller. Read-only here refers to access
12118 or permission status in the file system for the current user.
12119
12120 @item -aIDIR
12121 @cindex @option{-aIDIR} (@command{gnatfind})
12122 When looking for source files also look in directory DIR. The order in which
12123 source file search is undertaken is the same as for @command{gnatmake}.
12124
12125 @item -aODIR
12126 @cindex @option{-aODIR} (@command{gnatfind})
12127 When searching for library and object files, look in directory
12128 DIR. The order in which library files are searched is the same as for
12129 @command{gnatmake}.
12130
12131 @item -nostdinc
12132 @cindex @option{-nostdinc} (@command{gnatfind})
12133 Do not look for sources in the system default directory.
12134
12135 @item -nostdlib
12136 @cindex @option{-nostdlib} (@command{gnatfind})
12137 Do not look for library files in the system default directory.
12138
12139 @item --ext=@var{extension}
12140 @cindex @option{--ext} (@command{gnatfind})
12141 Specify an alternate ali file extension. The default is @code{ali} and other
12142 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12143 switch. Note that if this switch overrides the default, which means that only
12144 the new extension will be considered.
12145
12146 @item --RTS=@var{rts-path}
12147 @cindex @option{--RTS} (@command{gnatfind})
12148 Specifies the default location of the runtime library. Same meaning as the
12149 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12150
12151 @item ^-d^/DERIVED_TYPE_INFORMATION^
12152 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12153 If this switch is set, then @code{gnatfind} will output the parent type
12154 reference for each matching derived types.
12155
12156 @item ^-e^/EXPRESSIONS^
12157 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12158 By default, @code{gnatfind} accept the simple regular expression set for
12159 @samp{pattern}. If this switch is set, then the pattern will be
12160 considered as full Unix-style regular expression.
12161
12162 @item ^-f^/FULL_PATHNAME^
12163 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12164 If this switch is set, the output file names will be preceded by their
12165 directory (if the file was found in the search path). If this switch is
12166 not set, the directory will not be printed.
12167
12168 @item ^-g^/IGNORE_LOCALS^
12169 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12170 If this switch is set, information is output only for library-level
12171 entities, ignoring local entities. The use of this switch may accelerate
12172 @code{gnatfind} and @code{gnatxref}.
12173
12174 @item -IDIR
12175 @cindex @option{-IDIR} (@command{gnatfind})
12176 Equivalent to @samp{-aODIR -aIDIR}.
12177
12178 @item -pFILE
12179 @cindex @option{-pFILE} (@command{gnatfind})
12180 Specify a project file (@pxref{GNAT Project Manager}) to use.
12181 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12182 project file in the current directory.
12183
12184 If a project file is either specified or found by the tools, then the content
12185 of the source directory and object directory lines are added as if they
12186 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12187 @samp{^-aO^/OBJECT_SEARCH^}.
12188
12189 @item ^-r^/REFERENCES^
12190 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12191 By default, @code{gnatfind} will output only the information about the
12192 declaration, body or type completion of the entities. If this switch is
12193 set, the @code{gnatfind} will locate every reference to the entities in
12194 the files specified on the command line (or in every file in the search
12195 path if no file is given on the command line).
12196
12197 @item ^-s^/PRINT_LINES^
12198 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12199 If this switch is set, then @code{gnatfind} will output the content
12200 of the Ada source file lines were the entity was found.
12201
12202 @item ^-t^/TYPE_HIERARCHY^
12203 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12204 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12205 the specified type. It act like -d option but recursively from parent
12206 type to parent type. When this switch is set it is not possible to
12207 specify more than one file.
12208
12209 @end table
12210
12211 @noindent
12212 All these switches may be in any order on the command line, and may even
12213 appear after the file names. They need not be separated by spaces, thus
12214 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12215 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12216
12217 As stated previously, gnatfind will search in every directory in the
12218 search path. You can force it to look only in the current directory if
12219 you specify @code{*} at the end of the command line.
12220
12221 @node Project Files for gnatxref and gnatfind
12222 @section Project Files for @command{gnatxref} and @command{gnatfind}
12223
12224 @noindent
12225 Project files allow a programmer to specify how to compile its
12226 application, where to find sources, etc.  These files are used
12227 @ifclear vms
12228 primarily by GPS, but they can also be used
12229 @end ifclear
12230 by the two tools
12231 @code{gnatxref} and @code{gnatfind}.
12232
12233 A project file name must end with @file{.gpr}. If a single one is
12234 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12235 extract the information from it. If multiple project files are found, none of
12236 them is read, and you have to use the @samp{-p} switch to specify the one
12237 you want to use.
12238
12239 The following lines can be included, even though most of them have default
12240 values which can be used in most cases.
12241 The lines can be entered in any order in the file.
12242 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12243 each line. If you have multiple instances, only the last one is taken into
12244 account.
12245
12246 @table @code
12247 @item src_dir=DIR
12248 [default: @code{"^./^[]^"}]
12249 specifies a directory where to look for source files. Multiple @code{src_dir}
12250 lines can be specified and they will be searched in the order they
12251 are specified.
12252
12253 @item obj_dir=DIR
12254 [default: @code{"^./^[]^"}]
12255 specifies a directory where to look for object and library files. Multiple
12256 @code{obj_dir} lines can be specified, and they will be searched in the order
12257 they are specified
12258
12259 @item comp_opt=SWITCHES
12260 [default: @code{""}]
12261 creates a variable which can be referred to subsequently by using
12262 the @code{$@{comp_opt@}} notation. This is intended to store the default
12263 switches given to @command{gnatmake} and @command{gcc}.
12264
12265 @item bind_opt=SWITCHES
12266 [default: @code{""}]
12267 creates a variable which can be referred to subsequently by using
12268 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12269 switches given to @command{gnatbind}.
12270
12271 @item link_opt=SWITCHES
12272 [default: @code{""}]
12273 creates a variable which can be referred to subsequently by using
12274 the @samp{$@{link_opt@}} notation. This is intended to store the default
12275 switches given to @command{gnatlink}.
12276
12277 @item main=EXECUTABLE
12278 [default: @code{""}]
12279 specifies the name of the executable for the application. This variable can
12280 be referred to in the following lines by using the @samp{$@{main@}} notation.
12281
12282 @ifset vms
12283 @item comp_cmd=COMMAND
12284 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12285 @end ifset
12286 @ifclear vms
12287 @item comp_cmd=COMMAND
12288 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12289 @end ifclear
12290 specifies the command used to compile a single file in the application.
12291
12292 @ifset vms
12293 @item make_cmd=COMMAND
12294 [default: @code{"GNAT MAKE $@{main@}
12295 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12296 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12297 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12298 @end ifset
12299 @ifclear vms
12300 @item make_cmd=COMMAND
12301 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12302 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12303 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12304 @end ifclear
12305 specifies the command used to recompile the whole application.
12306
12307 @item run_cmd=COMMAND
12308 [default: @code{"$@{main@}"}]
12309 specifies the command used to run the application.
12310
12311 @item debug_cmd=COMMAND
12312 [default: @code{"gdb $@{main@}"}]
12313 specifies the command used to debug the application
12314
12315 @end table
12316
12317 @noindent
12318 @command{gnatxref} and @command{gnatfind} only take into account the
12319 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12320
12321 @node Regular Expressions in gnatfind and gnatxref
12322 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12323
12324 @noindent
12325 As specified in the section about @command{gnatfind}, the pattern can be a
12326 regular expression. Actually, there are to set of regular expressions
12327 which are recognized by the program:
12328
12329 @table @code
12330 @item globbing patterns
12331 These are the most usual regular expression. They are the same that you
12332 generally used in a Unix shell command line, or in a DOS session.
12333
12334 Here is a more formal grammar:
12335 @smallexample
12336 @group
12337 @iftex
12338 @leftskip=.5cm
12339 @end iftex
12340 regexp ::= term
12341 term   ::= elmt            -- matches elmt
12342 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12343 term   ::= *               -- any string of 0 or more characters
12344 term   ::= ?               -- matches any character
12345 term   ::= [char @{char@}]   -- matches any character listed
12346 term   ::= [char - char]   -- matches any character in range
12347 @end group
12348 @end smallexample
12349
12350 @item full regular expression
12351 The second set of regular expressions is much more powerful. This is the
12352 type of regular expressions recognized by utilities such a @file{grep}.
12353
12354 The following is the form of a regular expression, expressed in Ada
12355 reference manual style BNF is as follows
12356
12357 @smallexample
12358 @iftex
12359 @leftskip=.5cm
12360 @end iftex
12361 @group
12362 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12363
12364 term ::= item @{item@}       -- concatenation (item then item)
12365
12366 item ::= elmt              -- match elmt
12367 item ::= elmt *            -- zero or more elmt's
12368 item ::= elmt +            -- one or more elmt's
12369 item ::= elmt ?            -- matches elmt or nothing
12370 @end group
12371 @group
12372 elmt ::= nschar            -- matches given character
12373 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12374 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12375 elmt ::= [char - char]     -- matches chars in given range
12376 elmt ::= \ char            -- matches given character
12377 elmt ::= .                 -- matches any single character
12378 elmt ::= ( regexp )        -- parens used for grouping
12379
12380 char ::= any character, including special characters
12381 nschar ::= any character except ()[].*+?^^^
12382 @end group
12383 @end smallexample
12384
12385 Following are a few examples:
12386
12387 @table @samp
12388 @item abcde|fghi
12389 will match any of the two strings @samp{abcde} and @samp{fghi},
12390
12391 @item abc*d
12392 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12393 @samp{abcccd}, and so on,
12394
12395 @item [a-z]+
12396 will match any string which has only lowercase characters in it (and at
12397 least one character.
12398
12399 @end table
12400 @end table
12401
12402 @node Examples of gnatxref Usage
12403 @section Examples of @code{gnatxref} Usage
12404
12405 @subsection General Usage
12406
12407 @noindent
12408 For the following examples, we will consider the following units:
12409
12410 @smallexample @c ada
12411 @group
12412 @cartouche
12413 main.ads:
12414 1: with Bar;
12415 2: package Main is
12416 3:     procedure Foo (B : in Integer);
12417 4:     C : Integer;
12418 5: private
12419 6:     D : Integer;
12420 7: end Main;
12421
12422 main.adb:
12423 1: package body Main is
12424 2:     procedure Foo (B : in Integer) is
12425 3:     begin
12426 4:        C := B;
12427 5:        D := B;
12428 6:        Bar.Print (B);
12429 7:        Bar.Print (C);
12430 8:     end Foo;
12431 9: end Main;
12432
12433 bar.ads:
12434 1: package Bar is
12435 2:     procedure Print (B : Integer);
12436 3: end bar;
12437 @end cartouche
12438 @end group
12439 @end smallexample
12440
12441 @table @code
12442
12443 @noindent
12444 The first thing to do is to recompile your application (for instance, in
12445 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12446 the cross-referencing information.
12447 You can then issue any of the following commands:
12448
12449 @item gnatxref main.adb
12450 @code{gnatxref} generates cross-reference information for main.adb
12451 and every unit 'with'ed by main.adb.
12452
12453 The output would be:
12454 @smallexample
12455 @iftex
12456 @leftskip=0cm
12457 @end iftex
12458 B                                                      Type: Integer
12459   Decl: bar.ads           2:22
12460 B                                                      Type: Integer
12461   Decl: main.ads          3:20
12462   Body: main.adb          2:20
12463   Ref:  main.adb          4:13     5:13     6:19
12464 Bar                                                    Type: Unit
12465   Decl: bar.ads           1:9
12466   Ref:  main.adb          6:8      7:8
12467        main.ads           1:6
12468 C                                                      Type: Integer
12469   Decl: main.ads          4:5
12470   Modi: main.adb          4:8
12471   Ref:  main.adb          7:19
12472 D                                                      Type: Integer
12473   Decl: main.ads          6:5
12474   Modi: main.adb          5:8
12475 Foo                                                    Type: Unit
12476   Decl: main.ads          3:15
12477   Body: main.adb          2:15
12478 Main                                                    Type: Unit
12479   Decl: main.ads          2:9
12480   Body: main.adb          1:14
12481 Print                                                   Type: Unit
12482   Decl: bar.ads           2:15
12483   Ref:  main.adb          6:12     7:12
12484 @end smallexample
12485
12486 @noindent
12487 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12488 its body is in main.adb, line 1, column 14 and is not referenced any where.
12489
12490 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12491 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12492
12493 @item gnatxref package1.adb package2.ads
12494 @code{gnatxref} will generates cross-reference information for
12495 package1.adb, package2.ads and any other package 'with'ed by any
12496 of these.
12497
12498 @end table
12499
12500 @ifclear vms
12501 @subsection Using gnatxref with vi
12502
12503 @code{gnatxref} can generate a tags file output, which can be used
12504 directly from @command{vi}. Note that the standard version of @command{vi}
12505 will not work properly with overloaded symbols. Consider using another
12506 free implementation of @command{vi}, such as @command{vim}.
12507
12508 @smallexample
12509 $ gnatxref -v gnatfind.adb > tags
12510 @end smallexample
12511
12512 @noindent
12513 will generate the tags file for @code{gnatfind} itself (if the sources
12514 are in the search path!).
12515
12516 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12517 (replacing @var{entity} by whatever you are looking for), and vi will
12518 display a new file with the corresponding declaration of entity.
12519 @end ifclear
12520
12521 @node Examples of gnatfind Usage
12522 @section Examples of @code{gnatfind} Usage
12523
12524 @table @code
12525
12526 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12527 Find declarations for all entities xyz referenced at least once in
12528 main.adb. The references are search in every library file in the search
12529 path.
12530
12531 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12532 switch is set)
12533
12534 The output will look like:
12535 @smallexample
12536 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12537 ^directory/^[directory]^main.adb:24:10: xyz <= body
12538 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12539 @end smallexample
12540
12541 @noindent
12542 that is to say, one of the entities xyz found in main.adb is declared at
12543 line 12 of main.ads (and its body is in main.adb), and another one is
12544 declared at line 45 of foo.ads
12545
12546 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12547 This is the same command as the previous one, instead @code{gnatfind} will
12548 display the content of the Ada source file lines.
12549
12550 The output will look like:
12551
12552 @smallexample
12553 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12554    procedure xyz;
12555 ^directory/^[directory]^main.adb:24:10: xyz <= body
12556    procedure xyz is
12557 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12558    xyz : Integer;
12559 @end smallexample
12560
12561 @noindent
12562 This can make it easier to find exactly the location your are looking
12563 for.
12564
12565 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12566 Find references to all entities containing an x that are
12567 referenced on line 123 of main.ads.
12568 The references will be searched only in main.ads and foo.adb.
12569
12570 @item gnatfind main.ads:123
12571 Find declarations and bodies for all entities that are referenced on
12572 line 123 of main.ads.
12573
12574 This is the same as @code{gnatfind "*":main.adb:123}.
12575
12576 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12577 Find the declaration for the entity referenced at column 45 in
12578 line 123 of file main.adb in directory mydir. Note that it
12579 is usual to omit the identifier name when the column is given,
12580 since the column position identifies a unique reference.
12581
12582 The column has to be the beginning of the identifier, and should not
12583 point to any character in the middle of the identifier.
12584
12585 @end table
12586
12587 @c *********************************
12588 @node The GNAT Pretty-Printer gnatpp
12589 @chapter The GNAT Pretty-Printer @command{gnatpp}
12590 @findex gnatpp
12591 @cindex Pretty-Printer
12592
12593 @noindent
12594 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12595 for source reformatting / pretty-printing.
12596 It takes an Ada source file as input and generates a reformatted
12597 version as output.
12598 You can specify various style directives via switches; e.g.,
12599 identifier case conventions, rules of indentation, and comment layout.
12600
12601 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12602 tree for the input source and thus requires the input to be syntactically and
12603 semantically legal.
12604 If this condition is not met, @command{gnatpp} will terminate with an
12605 error message; no output file will be generated.
12606
12607 If the source files presented to @command{gnatpp} contain
12608 preprocessing directives, then the output file will
12609 correspond to the generated source after all
12610 preprocessing is carried out. There is no way
12611 using @command{gnatpp} to obtain pretty printed files that
12612 include the preprocessing directives.
12613
12614 If the compilation unit
12615 contained in the input source depends semantically upon units located
12616 outside the current directory, you have to provide the source search path
12617 when invoking @command{gnatpp}, if these units are contained in files with
12618 names that do not follow the GNAT file naming rules, you have to provide
12619 the configuration file describing the corresponding naming scheme;
12620 see the description of the @command{gnatpp}
12621 switches below. Another possibility is to use a project file and to
12622 call @command{gnatpp} through the @command{gnat} driver
12623
12624 The @command{gnatpp} command has the form
12625
12626 @smallexample
12627 @c $ gnatpp @ovar{switches} @var{filename}
12628 @c Expanding @ovar macro inline (explanation in macro def comments)
12629 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12630 @end smallexample
12631
12632 @noindent
12633 where
12634 @itemize @bullet
12635 @item
12636 @var{switches} is an optional sequence of switches defining such properties as
12637 the formatting rules, the source search path, and the destination for the
12638 output source file
12639
12640 @item
12641 @var{filename} is the name (including the extension) of the source file to
12642 reformat; ``wildcards'' or several file names on the same gnatpp command are
12643 allowed.  The file name may contain path information; it does not have to
12644 follow the GNAT file naming rules
12645
12646 @item
12647 @samp{@var{gcc_switches}} is a list of switches for
12648 @command{gcc}. They will be passed on to all compiler invocations made by
12649 @command{gnatelim} to generate the ASIS trees. Here you can provide
12650 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12651 use the @option{-gnatec} switch to set the configuration file etc.
12652 @end itemize
12653
12654 @menu
12655 * Switches for gnatpp::
12656 * Formatting Rules::
12657 @end menu
12658
12659 @node Switches for gnatpp
12660 @section Switches for @command{gnatpp}
12661
12662 @noindent
12663 The following subsections describe the various switches accepted by
12664 @command{gnatpp}, organized by category.
12665
12666 @ifclear vms
12667 You specify a switch by supplying a name and generally also a value.
12668 In many cases the values for a switch with a given name are incompatible with
12669 each other
12670 (for example the switch that controls the casing of a reserved word may have
12671 exactly one value: upper case, lower case, or
12672 mixed case) and thus exactly one such switch can be in effect for an
12673 invocation of @command{gnatpp}.
12674 If more than one is supplied, the last one is used.
12675 However, some values for the same switch are mutually compatible.
12676 You may supply several such switches to @command{gnatpp}, but then
12677 each must be specified in full, with both the name and the value.
12678 Abbreviated forms (the name appearing once, followed by each value) are
12679 not permitted.
12680 For example, to set
12681 the alignment of the assignment delimiter both in declarations and in
12682 assignment statements, you must write @option{-A2A3}
12683 (or @option{-A2 -A3}), but not @option{-A23}.
12684 @end ifclear
12685
12686 @ifset vms
12687 In many cases the set of options for a given qualifier are incompatible with
12688 each other (for example the qualifier that controls the casing of a reserved
12689 word may have exactly one option, which specifies either upper case, lower
12690 case, or mixed case), and thus exactly one such option can be in effect for
12691 an invocation of @command{gnatpp}.
12692 If more than one is supplied, the last one is used.
12693 However, some qualifiers have options that are mutually compatible,
12694 and then you may then supply several such options when invoking
12695 @command{gnatpp}.
12696 @end ifset
12697
12698 In most cases, it is obvious whether or not the
12699 ^values for a switch with a given name^options for a given qualifier^
12700 are compatible with each other.
12701 When the semantics might not be evident, the summaries below explicitly
12702 indicate the effect.
12703
12704 @menu
12705 * Alignment Control::
12706 * Casing Control::
12707 * Construct Layout Control::
12708 * General Text Layout Control::
12709 * Other Formatting Options::
12710 * Setting the Source Search Path::
12711 * Output File Control::
12712 * Other gnatpp Switches::
12713 @end menu
12714
12715 @node Alignment Control
12716 @subsection Alignment Control
12717 @cindex Alignment control in @command{gnatpp}
12718
12719 @noindent
12720 Programs can be easier to read if certain constructs are vertically aligned.
12721 By default all alignments are set ON.
12722 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12723 OFF, and then use one or more of the other
12724 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12725 to activate alignment for specific constructs.
12726
12727 @table @option
12728 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12729
12730 @ifset vms
12731 @item /ALIGN=ON
12732 Set all alignments to ON
12733 @end ifset
12734
12735 @item ^-A0^/ALIGN=OFF^
12736 Set all alignments to OFF
12737
12738 @item ^-A1^/ALIGN=COLONS^
12739 Align @code{:} in declarations
12740
12741 @item ^-A2^/ALIGN=DECLARATIONS^
12742 Align @code{:=} in initializations in declarations
12743
12744 @item ^-A3^/ALIGN=STATEMENTS^
12745 Align @code{:=} in assignment statements
12746
12747 @item ^-A4^/ALIGN=ARROWS^
12748 Align @code{=>} in associations
12749
12750 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12751 Align @code{at} keywords in the component clauses in record
12752 representation clauses
12753 @end table
12754
12755 @noindent
12756 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12757 is allowed.
12758
12759 @node Casing Control
12760 @subsection Casing Control
12761 @cindex Casing control in @command{gnatpp}
12762
12763 @noindent
12764 @command{gnatpp} allows you to specify the casing for reserved words,
12765 pragma names, attribute designators and identifiers.
12766 For identifiers you may define a
12767 general rule for name casing but also override this rule
12768 via a set of dictionary files.
12769
12770 Three types of casing are supported: lower case, upper case, and mixed case.
12771 Lower and upper case are self-explanatory (but since some letters in
12772 Latin1 and other GNAT-supported character sets
12773 exist only in lower-case form, an upper case conversion will have no
12774 effect on them.)
12775 ``Mixed case'' means that the first letter, and also each letter immediately
12776 following an underscore, are converted to their uppercase forms;
12777 all the other letters are converted to their lowercase forms.
12778
12779 @table @option
12780 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12781 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12782 Attribute designators are lower case
12783
12784 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12785 Attribute designators are upper case
12786
12787 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12788 Attribute designators are mixed case (this is the default)
12789
12790 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12791 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12792 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12793 lower case (this is the default)
12794
12795 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12796 Keywords are upper case
12797
12798 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12799 @item ^-nD^/NAME_CASING=AS_DECLARED^
12800 Name casing for defining occurrences are as they appear in the source file
12801 (this is the default)
12802
12803 @item ^-nU^/NAME_CASING=UPPER_CASE^
12804 Names are in upper case
12805
12806 @item ^-nL^/NAME_CASING=LOWER_CASE^
12807 Names are in lower case
12808
12809 @item ^-nM^/NAME_CASING=MIXED_CASE^
12810 Names are in mixed case
12811
12812 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12813 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12814 Pragma names are lower case
12815
12816 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12817 Pragma names are upper case
12818
12819 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12820 Pragma names are mixed case (this is the default)
12821
12822 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12823 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12824 Use @var{file} as a @emph{dictionary file} that defines
12825 the casing for a set of specified names,
12826 thereby overriding the effect on these names by
12827 any explicit or implicit
12828 ^-n^/NAME_CASING^ switch.
12829 To supply more than one dictionary file,
12830 use ^several @option{-D} switches^a list of files as options^.
12831
12832 @noindent
12833 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12834 to define the casing for the Ada predefined names and
12835 the names declared in the GNAT libraries.
12836
12837 @item ^-D-^/SPECIFIC_CASING^
12838 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12839 Do not use the default dictionary file;
12840 instead, use the casing
12841 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12842 dictionary file(s)
12843 @end table
12844
12845 @noindent
12846 The structure of a dictionary file, and details on the conventions
12847 used in the default dictionary file, are defined in @ref{Name Casing}.
12848
12849 The @option{^-D-^/SPECIFIC_CASING^} and
12850 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12851 compatible.
12852
12853 @node Construct Layout Control
12854 @subsection Construct Layout Control
12855 @cindex Layout control in @command{gnatpp}
12856
12857 @noindent
12858 This group of @command{gnatpp} switches controls the layout of comments and
12859 complex syntactic constructs.  See @ref{Formatting Comments} for details
12860 on their effect.
12861
12862 @table @option
12863 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
12864 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
12865 All the comments remain unchanged
12866
12867 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
12868 GNAT-style comment line indentation (this is the default).
12869
12870 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
12871 Reference-manual comment line indentation.
12872
12873 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
12874 GNAT-style comment beginning
12875
12876 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
12877 Reformat comment blocks
12878
12879 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
12880 Keep unchanged special form comments
12881
12882 Reformat comment blocks
12883
12884 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
12885 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
12886 GNAT-style layout (this is the default)
12887
12888 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
12889 Compact layout
12890
12891 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
12892 Uncompact layout
12893
12894 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
12895 @item ^-N^/NOTABS^
12896 All the VT characters are removed from the comment text. All the HT characters
12897 are expanded with the sequences of space characters to get to the next tab
12898 stops.
12899
12900 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
12901 @item ^--no-separate-is^/NO_SEPARATE_IS^
12902 Do not place the keyword @code{is} on a separate line in a subprogram body in
12903 case if the spec occupies more then one line.
12904
12905 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
12906 @item ^--separate-label^/SEPARATE_LABEL^
12907 Place statement label(s) on a separate line, with the following statement
12908 on the next line.
12909
12910 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
12911 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
12912 Place the keyword @code{loop} in FOR and WHILE loop statements and the
12913 keyword @code{then} in IF statements on a separate line.
12914
12915 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
12916 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
12917 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
12918 keyword @code{then} in IF statements on a separate line. This option is
12919 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
12920
12921 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
12922 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
12923 Start each USE clause in a context clause from a separate line.
12924
12925 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
12926 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
12927 Use a separate line for a loop or block statement name, but do not use an extra
12928 indentation level for the statement itself.
12929
12930 @end table
12931
12932 @ifclear vms
12933 @noindent
12934 The @option{-c1} and @option{-c2} switches are incompatible.
12935 The @option{-c3} and @option{-c4} switches are compatible with each other and
12936 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
12937 the other comment formatting switches.
12938
12939 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
12940 @end ifclear
12941
12942 @ifset vms
12943 @noindent
12944 For the @option{/COMMENTS_LAYOUT} qualifier:
12945 @itemize @bullet
12946 @item
12947 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
12948 @item
12949 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
12950 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
12951 @end itemize
12952
12953 @noindent
12954 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
12955 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
12956 @end ifset
12957
12958 @node General Text Layout Control
12959 @subsection General Text Layout Control
12960
12961 @noindent
12962 These switches allow control over line length and indentation.
12963
12964 @table @option
12965 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
12966 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
12967 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
12968
12969 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
12970 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
12971 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
12972
12973 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
12974 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
12975 Indentation level for continuation lines (relative to the line being
12976 continued), @var{nnn} from 1@dots{}9.
12977 The default
12978 value is one less then the (normal) indentation level, unless the
12979 indentation is set to 1 (in which case the default value for continuation
12980 line indentation is also 1)
12981 @end table
12982
12983 @node Other Formatting Options
12984 @subsection Other Formatting Options
12985
12986 @noindent
12987 These switches control the inclusion of missing end/exit labels, and
12988 the indentation level in @b{case} statements.
12989
12990 @table @option
12991 @item ^-e^/NO_MISSED_LABELS^
12992 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
12993 Do not insert missing end/exit labels. An end label is the name of
12994 a construct that may optionally be repeated at the end of the
12995 construct's declaration;
12996 e.g., the names of packages, subprograms, and tasks.
12997 An exit label is the name of a loop that may appear as target
12998 of an exit statement within the loop.
12999 By default, @command{gnatpp} inserts these end/exit labels when
13000 they are absent from the original source. This option suppresses such
13001 insertion, so that the formatted source reflects the original.
13002
13003 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13004 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13005 Insert a Form Feed character after a pragma Page.
13006
13007 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13008 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13009 Do not use an additional indentation level for @b{case} alternatives
13010 and variants if there are @var{nnn} or more (the default
13011 value is 10).
13012 If @var{nnn} is 0, an additional indentation level is
13013 used for @b{case} alternatives and variants regardless of their number.
13014 @end table
13015
13016 @node Setting the Source Search Path
13017 @subsection Setting the Source Search Path
13018
13019 @noindent
13020 To define the search path for the input source file, @command{gnatpp}
13021 uses the same switches as the GNAT compiler, with the same effects.
13022
13023 @table @option
13024 @item ^-I^/SEARCH=^@var{dir}
13025 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13026 The same as the corresponding gcc switch
13027
13028 @item ^-I-^/NOCURRENT_DIRECTORY^
13029 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13030 The same as the corresponding gcc switch
13031
13032 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13033 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13034 The same as the corresponding gcc switch
13035
13036 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13037 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13038 The same as the corresponding gcc switch
13039
13040 @end table
13041
13042 @node Output File Control
13043 @subsection Output File Control
13044
13045 @noindent
13046 By default the output is sent to the file whose name is obtained by appending
13047 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13048 (if the file with this name already exists, it is unconditionally overwritten).
13049 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13050 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13051 as output file.
13052 The output may be redirected by the following switches:
13053
13054 @table @option
13055 @item ^-pipe^/STANDARD_OUTPUT^
13056 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13057 Send the output to @code{Standard_Output}
13058
13059 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13060 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13061 Write the output into @var{output_file}.
13062 If @var{output_file} already exists, @command{gnatpp} terminates without
13063 reading or processing the input file.
13064
13065 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13066 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13067 Write the output into @var{output_file}, overwriting the existing file
13068 (if one is present).
13069
13070 @item ^-r^/REPLACE^
13071 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13072 Replace the input source file with the reformatted output, and copy the
13073 original input source into the file whose name is obtained by appending the
13074 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13075 If a file with this name already exists, @command{gnatpp} terminates without
13076 reading or processing the input file.
13077
13078 @item ^-rf^/OVERRIDING_REPLACE^
13079 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13080 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13081 already exists, it is overwritten.
13082
13083 @item ^-rnb^/REPLACE_NO_BACKUP^
13084 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13085 Replace the input source file with the reformatted output without
13086 creating any backup copy of the input source.
13087
13088 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13089 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13090 Specifies the format of the reformatted output file. The @var{xxx}
13091 ^string specified with the switch^option^ may be either
13092 @itemize @bullet
13093 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13094 @item ``@option{^crlf^CRLF^}''
13095 the same as @option{^crlf^CRLF^}
13096 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13097 @item ``@option{^lf^LF^}''
13098 the same as @option{^unix^UNIX^}
13099 @end itemize
13100
13101 @item ^-W^/RESULT_ENCODING=^@var{e}
13102 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13103 Specify the wide character encoding method used to write the code in the
13104 result file
13105 @var{e} is one of the following:
13106
13107 @itemize @bullet
13108
13109 @item ^h^HEX^
13110 Hex encoding
13111
13112 @item ^u^UPPER^
13113 Upper half encoding
13114
13115 @item ^s^SHIFT_JIS^
13116 Shift/JIS encoding
13117
13118 @item ^e^EUC^
13119 EUC encoding
13120
13121 @item ^8^UTF8^
13122 UTF-8 encoding
13123
13124 @item ^b^BRACKETS^
13125 Brackets encoding (default value)
13126 @end itemize
13127
13128 @end table
13129
13130 @noindent
13131 Options @option{^-pipe^/STANDARD_OUTPUT^},
13132 @option{^-o^/OUTPUT^} and
13133 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13134 contains only one file to reformat.
13135 Option
13136 @option{^--eol^/END_OF_LINE^}
13137 and
13138 @option{^-W^/RESULT_ENCODING^}
13139 cannot be used together
13140 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13141
13142 @node Other gnatpp Switches
13143 @subsection Other @code{gnatpp} Switches
13144
13145 @noindent
13146 The additional @command{gnatpp} switches are defined in this subsection.
13147
13148 @table @option
13149 @item ^-files @var{filename}^/FILES=@var{filename}^
13150 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13151 Take the argument source files from the specified file. This file should be an
13152 ordinary text file containing file names separated by spaces or
13153 line breaks. You can use this switch more than once in the same call to
13154 @command{gnatpp}. You also can combine this switch with an explicit list of
13155 files.
13156
13157 @item ^-v^/VERBOSE^
13158 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13159 Verbose mode;
13160 @command{gnatpp} generates version information and then
13161 a trace of the actions it takes to produce or obtain the ASIS tree.
13162
13163 @item ^-w^/WARNINGS^
13164 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13165 Warning mode;
13166 @command{gnatpp} generates a warning whenever it cannot provide
13167 a required layout in the result source.
13168 @end table
13169
13170 @node Formatting Rules
13171 @section Formatting Rules
13172
13173 @noindent
13174 The following subsections show how @command{gnatpp} treats ``white space'',
13175 comments, program layout, and name casing.
13176 They provide the detailed descriptions of the switches shown above.
13177
13178 @menu
13179 * White Space and Empty Lines::
13180 * Formatting Comments::
13181 * Construct Layout::
13182 * Name Casing::
13183 @end menu
13184
13185 @node White Space and Empty Lines
13186 @subsection White Space and Empty Lines
13187
13188 @noindent
13189 @command{gnatpp} does not have an option to control space characters.
13190 It will add or remove spaces according to the style illustrated by the
13191 examples in the @cite{Ada Reference Manual}.
13192
13193 The only format effectors
13194 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13195 that will appear in the output file are platform-specific line breaks,
13196 and also format effectors within (but not at the end of) comments.
13197 In particular, each horizontal tab character that is not inside
13198 a comment will be treated as a space and thus will appear in the
13199 output file as zero or more spaces depending on
13200 the reformatting of the line in which it appears.
13201 The only exception is a Form Feed character, which is inserted after a
13202 pragma @code{Page} when @option{-ff} is set.
13203
13204 The output file will contain no lines with trailing ``white space'' (spaces,
13205 format effectors).
13206
13207 Empty lines in the original source are preserved
13208 only if they separate declarations or statements.
13209 In such contexts, a
13210 sequence of two or more empty lines is replaced by exactly one empty line.
13211 Note that a blank line will be removed if it separates two ``comment blocks''
13212 (a comment block is a sequence of whole-line comments).
13213 In order to preserve a visual separation between comment blocks, use an
13214 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13215 Likewise, if for some reason you wish to have a sequence of empty lines,
13216 use a sequence of empty comments instead.
13217
13218 @node Formatting Comments
13219 @subsection Formatting Comments
13220
13221 @noindent
13222 Comments in Ada code are of two kinds:
13223 @itemize @bullet
13224 @item
13225 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13226 ``white space'') on a line
13227
13228 @item
13229 an @emph{end-of-line comment}, which follows some other Ada lexical element
13230 on the same line.
13231 @end itemize
13232
13233 @noindent
13234 The indentation of a whole-line comment is that of either
13235 the preceding or following line in
13236 the formatted source, depending on switch settings as will be described below.
13237
13238 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13239 between the end of the preceding Ada lexical element and the beginning
13240 of the comment as appear in the original source,
13241 unless either the comment has to be split to
13242 satisfy the line length limitation, or else the next line contains a
13243 whole line comment that is considered a continuation of this end-of-line
13244 comment (because it starts at the same position).
13245 In the latter two
13246 cases, the start of the end-of-line comment is moved right to the nearest
13247 multiple of the indentation level.
13248 This may result in a ``line overflow'' (the right-shifted comment extending
13249 beyond the maximum line length), in which case the comment is split as
13250 described below.
13251
13252 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13253 (GNAT-style comment line indentation)
13254 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13255 (reference-manual comment line indentation).
13256 With reference-manual style, a whole-line comment is indented as if it
13257 were a declaration or statement at the same place
13258 (i.e., according to the indentation of the preceding line(s)).
13259 With GNAT style, a whole-line comment that is immediately followed by an
13260 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13261 word @b{begin}, is indented based on the construct that follows it.
13262
13263 For example:
13264 @smallexample @c ada
13265 @cartouche
13266 if A then
13267     null;
13268        -- some comment
13269 else
13270    null;
13271 end if;
13272 @end cartouche
13273 @end smallexample
13274
13275 @noindent
13276 Reference-manual indentation produces:
13277
13278 @smallexample @c ada
13279 @cartouche
13280 if A then
13281    null;
13282    --  some comment
13283 else
13284    null;
13285 end if;
13286 @end cartouche
13287 @end smallexample
13288
13289 @noindent
13290 while GNAT-style indentation produces:
13291
13292 @smallexample @c ada
13293 @cartouche
13294 if A then
13295    null;
13296 --  some comment
13297 else
13298    null;
13299 end if;
13300 @end cartouche
13301 @end smallexample
13302
13303 @noindent
13304 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13305 (GNAT style comment beginning) has the following
13306 effect:
13307
13308 @itemize @bullet
13309 @item
13310 For each whole-line comment that does not end with two hyphens,
13311 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13312 to ensure that there are at least two spaces between these hyphens and the
13313 first non-blank character of the comment.
13314 @end itemize
13315
13316 @noindent
13317 For an end-of-line comment, if in the original source the next line is a
13318 whole-line comment that starts at the same position
13319 as the end-of-line comment,
13320 then the whole-line comment (and all whole-line comments
13321 that follow it and that start at the same position)
13322 will start at this position in the output file.
13323
13324 @noindent
13325 That is, if in the original source we have:
13326
13327 @smallexample @c ada
13328 @cartouche
13329 begin
13330 A := B + C;            --  B must be in the range Low1..High1
13331                        --  C must be in the range Low2..High2
13332              --B+C will be in the range Low1+Low2..High1+High2
13333 X := X + 1;
13334 @end cartouche
13335 @end smallexample
13336
13337 @noindent
13338 Then in the formatted source we get
13339
13340 @smallexample @c ada
13341 @cartouche
13342 begin
13343    A := B + C;            --  B must be in the range Low1..High1
13344                           --  C must be in the range Low2..High2
13345    --  B+C will be in the range Low1+Low2..High1+High2
13346    X := X + 1;
13347 @end cartouche
13348 @end smallexample
13349
13350 @noindent
13351 A comment that exceeds the line length limit will be split.
13352 Unless switch
13353 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13354 the line belongs to a reformattable block, splitting the line generates a
13355 @command{gnatpp} warning.
13356 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13357 comments may be reformatted in typical
13358 word processor style (that is, moving words between lines and putting as
13359 many words in a line as possible).
13360
13361 @noindent
13362 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13363 that has a special format (that is, a character that is neither a letter nor digit
13364 not white space nor line break immediately following the leading @code{--} of
13365 the comment) should be without any change moved from the argument source
13366 into reformatted source. This switch allows to preserve comments that are used
13367 as a special marks in the code (e.g.@: SPARK annotation).
13368
13369 @node Construct Layout
13370 @subsection Construct Layout
13371
13372 @noindent
13373 In several cases the suggested layout in the Ada Reference Manual includes
13374 an extra level of indentation that many programmers prefer to avoid. The
13375 affected cases include:
13376
13377 @itemize @bullet
13378
13379 @item Record type declaration (RM 3.8)
13380
13381 @item Record representation clause (RM 13.5.1)
13382
13383 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13384
13385 @item Block statement in case if a block has a statement identifier (RM 5.6)
13386 @end itemize
13387
13388 @noindent
13389 In compact mode (when GNAT style layout or compact layout is set),
13390 the pretty printer uses one level of indentation instead
13391 of two. This is achieved in the record definition and record representation
13392 clause cases by putting the @code{record} keyword on the same line as the
13393 start of the declaration or representation clause, and in the block and loop
13394 case by putting the block or loop header on the same line as the statement
13395 identifier.
13396
13397 @noindent
13398 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13399 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13400 layout on the one hand, and uncompact layout
13401 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13402 can be illustrated by the following examples:
13403
13404 @iftex
13405 @cartouche
13406 @multitable @columnfractions .5 .5
13407 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13408
13409 @item
13410 @smallexample @c ada
13411 type q is record
13412    a : integer;
13413    b : integer;
13414 end record;
13415 @end smallexample
13416 @tab
13417 @smallexample @c ada
13418 type q is
13419    record
13420       a : integer;
13421       b : integer;
13422    end record;
13423 @end smallexample
13424
13425 @item
13426 @smallexample @c ada
13427 for q use record
13428    a at 0 range  0 .. 31;
13429    b at 4 range  0 .. 31;
13430 end record;
13431 @end smallexample
13432 @tab
13433 @smallexample @c ada
13434 for q use
13435    record
13436       a at 0 range  0 .. 31;
13437       b at 4 range  0 .. 31;
13438    end record;
13439 @end smallexample
13440
13441 @item
13442 @smallexample @c ada
13443 Block : declare
13444    A : Integer := 3;
13445 begin
13446    Proc (A, A);
13447 end Block;
13448 @end smallexample
13449 @tab
13450 @smallexample @c ada
13451 Block :
13452    declare
13453       A : Integer := 3;
13454    begin
13455       Proc (A, A);
13456    end Block;
13457 @end smallexample
13458
13459 @item
13460 @smallexample @c ada
13461 Clear : for J in 1 .. 10 loop
13462    A (J) := 0;
13463 end loop Clear;
13464 @end smallexample
13465 @tab
13466 @smallexample @c ada
13467 Clear :
13468    for J in 1 .. 10 loop
13469       A (J) := 0;
13470    end loop Clear;
13471 @end smallexample
13472 @end multitable
13473 @end cartouche
13474 @end iftex
13475
13476 @ifnottex
13477 @smallexample
13478 @cartouche
13479 GNAT style, compact layout              Uncompact layout
13480
13481 type q is record                        type q is
13482    a : integer;                            record
13483    b : integer;                               a : integer;
13484 end record;                                   b : integer;
13485                                            end record;
13486
13487 for q use record                        for q use
13488    a at 0 range  0 .. 31;                  record
13489    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13490 end record;                                   b at 4 range  0 .. 31;
13491                                            end record;
13492
13493 Block : declare                         Block :
13494    A : Integer := 3;                       declare
13495 begin                                         A : Integer := 3;
13496    Proc (A, A);                            begin
13497 end Block;                                    Proc (A, A);
13498                                            end Block;
13499
13500 Clear : for J in 1 .. 10 loop           Clear :
13501    A (J) := 0;                             for J in 1 .. 10 loop
13502 end loop Clear;                               A (J) := 0;
13503                                            end loop Clear;
13504 @end cartouche
13505 @end smallexample
13506 @end ifnottex
13507
13508 @noindent
13509 A further difference between GNAT style layout and compact layout is that
13510 GNAT style layout inserts empty lines as separation for
13511 compound statements, return statements and bodies.
13512
13513 Note that the layout specified by
13514 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13515 for named block and loop statements overrides the layout defined by these
13516 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13517 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13518 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13519
13520 @node Name Casing
13521 @subsection Name Casing
13522
13523 @noindent
13524 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13525 the same casing as the corresponding defining identifier.
13526
13527 You control the casing for defining occurrences via the
13528 @option{^-n^/NAME_CASING^} switch.
13529 @ifclear vms
13530 With @option{-nD} (``as declared'', which is the default),
13531 @end ifclear
13532 @ifset vms
13533 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13534 @end ifset
13535 defining occurrences appear exactly as in the source file
13536 where they are declared.
13537 The other ^values for this switch^options for this qualifier^ ---
13538 @option{^-nU^UPPER_CASE^},
13539 @option{^-nL^LOWER_CASE^},
13540 @option{^-nM^MIXED_CASE^} ---
13541 result in
13542 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13543 If @command{gnatpp} changes the casing of a defining
13544 occurrence, it analogously changes the casing of all the
13545 usage occurrences of this name.
13546
13547 If the defining occurrence of a name is not in the source compilation unit
13548 currently being processed by @command{gnatpp}, the casing of each reference to
13549 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13550 switch (subject to the dictionary file mechanism described below).
13551 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13552 had affected the
13553 casing for the defining occurrence of the name.
13554
13555 Some names may need to be spelled with casing conventions that are not
13556 covered by the upper-, lower-, and mixed-case transformations.
13557 You can arrange correct casing by placing such names in a
13558 @emph{dictionary file},
13559 and then supplying a @option{^-D^/DICTIONARY^} switch.
13560 The casing of names from dictionary files overrides
13561 any @option{^-n^/NAME_CASING^} switch.
13562
13563 To handle the casing of Ada predefined names and the names from GNAT libraries,
13564 @command{gnatpp} assumes a default dictionary file.
13565 The name of each predefined entity is spelled with the same casing as is used
13566 for the entity in the @cite{Ada Reference Manual}.
13567 The name of each entity in the GNAT libraries is spelled with the same casing
13568 as is used in the declaration of that entity.
13569
13570 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13571 default dictionary file.
13572 Instead, the casing for predefined and GNAT-defined names will be established
13573 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13574 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13575 will appear as just shown,
13576 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13577 To ensure that even such names are rendered in uppercase,
13578 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13579 (or else, less conveniently, place these names in upper case in a dictionary
13580 file).
13581
13582 A dictionary file is
13583 a plain text file; each line in this file can be either a blank line
13584 (containing only space characters and ASCII.HT characters), an Ada comment
13585 line, or the specification of exactly one @emph{casing schema}.
13586
13587 A casing schema is a string that has the following syntax:
13588
13589 @smallexample
13590 @cartouche
13591   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13592
13593   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13594 @end cartouche
13595 @end smallexample
13596
13597 @noindent
13598 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13599 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13600
13601 The casing schema string can be followed by white space and/or an Ada-style
13602 comment; any amount of white space is allowed before the string.
13603
13604 If a dictionary file is passed as
13605 @ifclear vms
13606 the value of a @option{-D@var{file}} switch
13607 @end ifclear
13608 @ifset vms
13609 an option to the @option{/DICTIONARY} qualifier
13610 @end ifset
13611 then for every
13612 simple name and every identifier, @command{gnatpp} checks if the dictionary
13613 defines the casing for the name or for some of its parts (the term ``subword''
13614 is used below to denote the part of a name which is delimited by ``_'' or by
13615 the beginning or end of the word and which does not contain any ``_'' inside):
13616
13617 @itemize @bullet
13618 @item
13619 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13620 the casing defined by the dictionary; no subwords are checked for this word
13621
13622 @item
13623 for every subword @command{gnatpp} checks if the dictionary contains the
13624 corresponding string of the form @code{*@var{simple_identifier}*},
13625 and if it does, the casing of this @var{simple_identifier} is used
13626 for this subword
13627
13628 @item
13629 if the whole name does not contain any ``_'' inside, and if for this name
13630 the dictionary contains two entries - one of the form @var{identifier},
13631 and another - of the form *@var{simple_identifier}*, then the first one
13632 is applied to define the casing of this name
13633
13634 @item
13635 if more than one dictionary file is passed as @command{gnatpp} switches, each
13636 dictionary adds new casing exceptions and overrides all the existing casing
13637 exceptions set by the previous dictionaries
13638
13639 @item
13640 when @command{gnatpp} checks if the word or subword is in the dictionary,
13641 this check is not case sensitive
13642 @end itemize
13643
13644 @noindent
13645 For example, suppose we have the following source to reformat:
13646
13647 @smallexample @c ada
13648 @cartouche
13649 procedure test is
13650    name1 : integer := 1;
13651    name4_name3_name2 : integer := 2;
13652    name2_name3_name4 : Boolean;
13653    name1_var : Float;
13654 begin
13655    name2_name3_name4 := name4_name3_name2 > name1;
13656 end;
13657 @end cartouche
13658 @end smallexample
13659
13660 @noindent
13661 And suppose we have two dictionaries:
13662
13663 @smallexample
13664 @cartouche
13665 @i{dict1:}
13666    NAME1
13667    *NaMe3*
13668    *Name1*
13669 @end cartouche
13670
13671 @cartouche
13672 @i{dict2:}
13673   *NAME3*
13674 @end cartouche
13675 @end smallexample
13676
13677 @noindent
13678 If @command{gnatpp} is called with the following switches:
13679
13680 @smallexample
13681 @ifclear vms
13682 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13683 @end ifclear
13684 @ifset vms
13685 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13686 @end ifset
13687 @end smallexample
13688
13689 @noindent
13690 then we will get the following name casing in the @command{gnatpp} output:
13691
13692 @smallexample @c ada
13693 @cartouche
13694 procedure Test is
13695    NAME1             : Integer := 1;
13696    Name4_NAME3_Name2 : Integer := 2;
13697    Name2_NAME3_Name4 : Boolean;
13698    Name1_Var         : Float;
13699 begin
13700    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13701 end Test;
13702 @end cartouche
13703 @end smallexample
13704
13705 @c *********************************
13706 @node The GNAT Metric Tool gnatmetric
13707 @chapter The GNAT Metric Tool @command{gnatmetric}
13708 @findex gnatmetric
13709 @cindex Metric tool
13710
13711 @noindent
13712 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13713 for computing various program metrics.
13714 It takes an Ada source file as input and generates a file containing the
13715 metrics data as output. Various switches control which
13716 metrics are computed and output.
13717
13718 @command{gnatmetric} generates and uses the ASIS
13719 tree for the input source and thus requires the input to be syntactically and
13720 semantically legal.
13721 If this condition is not met, @command{gnatmetric} will generate
13722 an error message; no metric information for this file will be
13723 computed and reported.
13724
13725 If the compilation unit contained in the input source depends semantically
13726 upon units in files located outside the current directory, you have to provide
13727 the source search path when invoking @command{gnatmetric}.
13728 If it depends semantically upon units that are contained
13729 in files with names that do not follow the GNAT file naming rules, you have to
13730 provide the configuration file describing the corresponding naming scheme (see
13731 the description of the @command{gnatmetric} switches below.)
13732 Alternatively, you may use a project file and invoke @command{gnatmetric}
13733 through the @command{gnat} driver.
13734
13735 The @command{gnatmetric} command has the form
13736
13737 @smallexample
13738 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13739 @c Expanding @ovar macro inline (explanation in macro def comments)
13740 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13741 @end smallexample
13742
13743 @noindent
13744 where
13745 @itemize @bullet
13746 @item
13747 @var{switches} specify the metrics to compute and define the destination for
13748 the output
13749
13750 @item
13751 Each @var{filename} is the name (including the extension) of a source
13752 file to process. ``Wildcards'' are allowed, and
13753 the file name may contain path information.
13754 If no @var{filename} is supplied, then the @var{switches} list must contain
13755 at least one
13756 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13757 Including both a @option{-files} switch and one or more
13758 @var{filename} arguments is permitted.
13759
13760 @item
13761 @samp{@var{gcc_switches}} is a list of switches for
13762 @command{gcc}. They will be passed on to all compiler invocations made by
13763 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13764 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13765 and use the @option{-gnatec} switch to set the configuration file.
13766 @end itemize
13767
13768 @menu
13769 * Switches for gnatmetric::
13770 @end menu
13771
13772 @node Switches for gnatmetric
13773 @section Switches for @command{gnatmetric}
13774
13775 @noindent
13776 The following subsections describe the various switches accepted by
13777 @command{gnatmetric}, organized by category.
13778
13779 @menu
13780 * Output Files Control::
13781 * Disable Metrics For Local Units::
13782 * Specifying a set of metrics to compute::
13783 * Other gnatmetric Switches::
13784 * Generate project-wide metrics::
13785 @end menu
13786
13787 @node Output Files Control
13788 @subsection Output File Control
13789 @cindex Output file control in @command{gnatmetric}
13790
13791 @noindent
13792 @command{gnatmetric} has two output formats. It can generate a
13793 textual (human-readable) form, and also XML. By default only textual
13794 output is generated.
13795
13796 When generating the output in textual form, @command{gnatmetric} creates
13797 for each Ada source file a corresponding text file
13798 containing the computed metrics, except for the case when the set of metrics
13799 specified by gnatmetric parameters consists only of metrics that are computed
13800 for the whole set of analyzed sources, but not for each Ada source.
13801 By default, this file is placed in the same directory as where the source
13802 file is located, and its name is obtained
13803 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13804 input file.
13805
13806 All the output information generated in XML format is placed in a single
13807 file. By default this file is placed in the current directory and has the
13808 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13809
13810 Some of the computed metrics are summed over the units passed to
13811 @command{gnatmetric}; for example, the total number of lines of code.
13812 By default this information is sent to @file{stdout}, but a file
13813 can be specified with the @option{-og} switch.
13814
13815 The following switches control the @command{gnatmetric} output:
13816
13817 @table @option
13818 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13819 @item ^-x^/XML^
13820 Generate the XML output
13821
13822 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13823 @item ^-xs^/XSD^
13824 Generate the XML output and the XML schema file that describes the structure
13825 of the XML metric report, this schema is assigned to the XML file. The schema
13826 file has the same name as the XML output file with @file{.xml} suffix replaced
13827 with @file{.xsd}
13828
13829 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13830 @item ^-nt^/NO_TEXT^
13831 Do not generate the output in text form (implies @option{^-x^/XML^})
13832
13833 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13834 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13835 Put text files with detailed metrics into @var{output_dir}
13836
13837 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13838 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13839 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13840 in the name of the output file.
13841
13842 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13843 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13844 Put global metrics into @var{file_name}
13845
13846 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13847 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13848 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13849
13850 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
13851 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
13852 Use ``short'' source file names in the output.  (The @command{gnatmetric}
13853 output includes the name(s) of the Ada source file(s) from which the metrics
13854 are computed.  By default each name includes the absolute path. The
13855 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
13856 to exclude all directory information from the file names that are output.)
13857
13858 @end table
13859
13860 @node Disable Metrics For Local Units
13861 @subsection Disable Metrics For Local Units
13862 @cindex Disable Metrics For Local Units in @command{gnatmetric}
13863
13864 @noindent
13865 @command{gnatmetric} relies on the GNAT compilation model @minus{}
13866 one compilation
13867 unit per one source file. It computes line metrics for the whole source
13868 file, and it also computes syntax
13869 and complexity metrics for the file's outermost unit.
13870
13871 By default, @command{gnatmetric} will also compute all metrics for certain
13872 kinds of locally declared program units:
13873
13874 @itemize @bullet
13875 @item
13876 subprogram (and generic subprogram) bodies;
13877
13878 @item
13879 package (and generic package) specs and bodies;
13880
13881 @item
13882 task object and type specifications and bodies;
13883
13884 @item
13885 protected object and type specifications and bodies.
13886 @end itemize
13887
13888 @noindent
13889 These kinds of entities will be referred to as
13890 @emph{eligible local program units}, or simply @emph{eligible local units},
13891 @cindex Eligible local unit (for @command{gnatmetric})
13892 in the discussion below.
13893
13894 Note that a subprogram declaration, generic instantiation,
13895 or renaming declaration only receives metrics
13896 computation when it appear as the outermost entity
13897 in a source file.
13898
13899 Suppression of metrics computation for eligible local units can be
13900 obtained via the following switch:
13901
13902 @table @option
13903 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
13904 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
13905 Do not compute detailed metrics for eligible local program units
13906
13907 @end table
13908
13909 @node Specifying a set of metrics to compute
13910 @subsection Specifying a set of metrics to compute
13911
13912 @noindent
13913 By default all the metrics are computed and reported. The switches
13914 described in this subsection allow you to control, on an individual
13915 basis, whether metrics are computed and
13916 reported. If at least one positive metric
13917 switch is specified (that is, a switch that defines that a given
13918 metric or set of metrics is to be computed), then only
13919 explicitly specified metrics are reported.
13920
13921 @menu
13922 * Line Metrics Control::
13923 * Syntax Metrics Control::
13924 * Complexity Metrics Control::
13925 * Object-Oriented Metrics Control::
13926 @end menu
13927
13928 @node Line Metrics Control
13929 @subsubsection Line Metrics Control
13930 @cindex Line metrics control in @command{gnatmetric}
13931
13932 @noindent
13933 For any (legal) source file, and for each of its
13934 eligible local program units, @command{gnatmetric} computes the following
13935 metrics:
13936
13937 @itemize @bullet
13938 @item
13939 the total number of lines;
13940
13941 @item
13942 the total number of code lines (i.e., non-blank lines that are not comments)
13943
13944 @item
13945 the number of comment lines
13946
13947 @item
13948 the number of code lines containing end-of-line comments;
13949
13950 @item
13951 the comment percentage: the ratio between the number of lines that contain
13952 comments and the number of all non-blank lines, expressed as a percentage;
13953
13954 @item
13955 the number of empty lines and lines containing only space characters and/or
13956 format effectors (blank lines)
13957
13958 @item
13959 the average number of code lines in subprogram bodies, task bodies, entry
13960 bodies and statement sequences in package bodies (this metric is only computed
13961 across the whole set of the analyzed units)
13962
13963 @end itemize
13964
13965 @noindent
13966 @command{gnatmetric} sums the values of the line metrics for all the
13967 files being processed and then generates the cumulative results. The tool
13968 also computes for all the files being processed the average number of code
13969 lines in bodies.
13970
13971 You can use the following switches to select the specific line metrics
13972 to be computed and reported.
13973
13974 @table @option
13975 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
13976
13977 @ifclear vms
13978 @cindex @option{--no-lines@var{x}}
13979 @end ifclear
13980
13981 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
13982 Report all the line metrics
13983
13984 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
13985 Do not report any of line metrics
13986
13987 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
13988 Report the number of all lines
13989
13990 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
13991 Do not report the number of all lines
13992
13993 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
13994 Report the number of code lines
13995
13996 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
13997 Do not report the number of code lines
13998
13999 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14000 Report the number of comment lines
14001
14002 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14003 Do not report the number of comment lines
14004
14005 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14006 Report the number of code lines containing
14007 end-of-line comments
14008
14009 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14010 Do not report the number of code lines containing
14011 end-of-line comments
14012
14013 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14014 Report the comment percentage in the program text
14015
14016 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14017 Do not report the comment percentage in the program text
14018
14019 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14020 Report the number of blank lines
14021
14022 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14023 Do not report the number of blank lines
14024
14025 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14026 Report the average number of code lines in subprogram bodies, task bodies,
14027 entry bodies and statement sequences in package bodies. The metric is computed
14028 and reported for the whole set of processed Ada sources only.
14029
14030 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14031 Do not report the average number of code lines in subprogram bodies,
14032 task bodies, entry bodies and statement sequences in package bodies.
14033
14034 @end table
14035
14036 @node Syntax Metrics Control
14037 @subsubsection Syntax Metrics Control
14038 @cindex Syntax metrics control in @command{gnatmetric}
14039
14040 @noindent
14041 @command{gnatmetric} computes various syntactic metrics for the
14042 outermost unit and for each eligible local unit:
14043
14044 @table @emph
14045 @item LSLOC (``Logical Source Lines Of Code'')
14046 The total number of declarations and the total number of statements
14047
14048 @item Maximal static nesting level of inner program units
14049 According to
14050 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14051 package, a task unit, a protected unit, a
14052 protected entry, a generic unit, or an explicitly declared subprogram other
14053 than an enumeration literal.''
14054
14055 @item Maximal nesting level of composite syntactic constructs
14056 This corresponds to the notion of the
14057 maximum nesting level in the GNAT built-in style checks
14058 (@pxref{Style Checking})
14059 @end table
14060
14061 @noindent
14062 For the outermost unit in the file, @command{gnatmetric} additionally computes
14063 the following metrics:
14064
14065 @table @emph
14066 @item Public subprograms
14067 This metric is computed for package specs. It is the
14068 number of subprograms and generic subprograms declared in the visible
14069 part (including the visible part of nested packages, protected objects, and
14070 protected types).
14071
14072 @item All subprograms
14073 This metric is computed for bodies and subunits. The
14074 metric is equal to a total number of subprogram bodies in the compilation
14075 unit.
14076 Neither generic instantiations nor renamings-as-a-body nor body stubs
14077 are counted. Any subprogram body is counted, independently of its nesting
14078 level and enclosing constructs. Generic bodies and bodies of protected
14079 subprograms are counted in the same way as ``usual'' subprogram bodies.
14080
14081 @item Public types
14082 This metric is computed for package specs and
14083 generic package declarations. It is the total number of types
14084 that can be referenced from outside this compilation unit, plus the
14085 number of types from all the visible parts of all the visible generic
14086 packages. Generic formal types are not counted.  Only types, not subtypes,
14087 are included.
14088
14089 @noindent
14090 Along with the total number of public types, the following
14091 types are counted and reported separately:
14092
14093 @itemize @bullet
14094 @item
14095 Abstract types
14096
14097 @item
14098 Root tagged types (abstract, non-abstract, private, non-private). Type
14099 extensions are @emph{not} counted
14100
14101 @item
14102 Private types (including private extensions)
14103
14104 @item
14105 Task types
14106
14107 @item
14108 Protected types
14109
14110 @end itemize
14111
14112 @item All types
14113 This metric is computed for any compilation unit. It is equal to the total
14114 number of the declarations of different types given in the compilation unit.
14115 The private and the corresponding full type declaration are counted as one
14116 type declaration. Incomplete type declarations and generic formal types
14117 are not counted.
14118 No distinction is made among different kinds of types (abstract,
14119 private etc.); the total number of types is computed and reported.
14120
14121 @end table
14122
14123 @noindent
14124 By default, all the syntax metrics are computed and reported. You can use the
14125 following switches to select specific syntax metrics.
14126
14127 @table @option
14128
14129 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14130
14131 @ifclear vms
14132 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14133 @end ifclear
14134
14135 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14136 Report all the syntax metrics
14137
14138 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14139 Do not report any of syntax metrics
14140
14141 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14142 Report the total number of declarations
14143
14144 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14145 Do not report the total number of declarations
14146
14147 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14148 Report the total number of statements
14149
14150 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14151 Do not report the total number of statements
14152
14153 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14154 Report the number of public subprograms in a compilation unit
14155
14156 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14157 Do not report the number of public subprograms in a compilation unit
14158
14159 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14160 Report the number of all the subprograms in a compilation unit
14161
14162 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14163 Do not report the number of all the subprograms in a compilation unit
14164
14165 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14166 Report the number of public types in a compilation unit
14167
14168 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14169 Do not report the number of public types in a compilation unit
14170
14171 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14172 Report the number of all the types in a compilation unit
14173
14174 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14175 Do not report the number of all the types in a compilation unit
14176
14177 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14178 Report the maximal program unit nesting level
14179
14180 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14181 Do not report the maximal program unit nesting level
14182
14183 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14184 Report the maximal construct nesting level
14185
14186 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14187 Do not report the maximal construct nesting level
14188
14189 @end table
14190
14191 @node Complexity Metrics Control
14192 @subsubsection Complexity Metrics Control
14193 @cindex Complexity metrics control in @command{gnatmetric}
14194
14195 @noindent
14196 For a program unit that is an executable body (a subprogram body (including
14197 generic bodies), task body, entry body or a package body containing
14198 its own statement sequence) @command{gnatmetric} computes the following
14199 complexity metrics:
14200
14201 @itemize @bullet
14202 @item
14203 McCabe cyclomatic complexity;
14204
14205 @item
14206 McCabe essential complexity;
14207
14208 @item
14209 maximal loop nesting level
14210
14211 @end itemize
14212
14213 @noindent
14214 The McCabe complexity metrics are defined
14215 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14216
14217 According to McCabe, both control statements and short-circuit control forms
14218 should be taken into account when computing cyclomatic complexity. For each
14219 body, we compute three metric values:
14220
14221 @itemize @bullet
14222 @item
14223 the complexity introduced by control
14224 statements only, without taking into account short-circuit forms,
14225
14226 @item
14227 the complexity introduced by short-circuit control forms only, and
14228
14229 @item
14230 the total
14231 cyclomatic complexity, which is the sum of these two values.
14232 @end itemize
14233
14234 @noindent
14235 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14236 the code in the exception handlers and in all the nested program units.
14237
14238 By default, all the complexity metrics are computed and reported.
14239 For more fine-grained control you can use
14240 the following switches:
14241
14242 @table @option
14243 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14244
14245 @ifclear vms
14246 @cindex @option{--no-complexity@var{x}}
14247 @end ifclear
14248
14249 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14250 Report all the complexity metrics
14251
14252 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14253 Do not report any of complexity metrics
14254
14255 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14256 Report the McCabe Cyclomatic Complexity
14257
14258 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14259 Do not report the McCabe Cyclomatic Complexity
14260
14261 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14262 Report the Essential Complexity
14263
14264 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14265 Do not report the Essential Complexity
14266
14267 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14268 Report maximal loop nesting level
14269
14270 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14271 Do not report maximal loop nesting level
14272
14273 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14274 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14275 task bodies, entry bodies and statement sequences in package bodies.
14276 The metric is computed and reported for whole set of processed Ada sources
14277 only.
14278
14279 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14280 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14281 bodies, task bodies, entry bodies and statement sequences in package bodies
14282
14283 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14284 @item ^-ne^/NO_EXITS_AS_GOTOS^
14285 Do not consider @code{exit} statements as @code{goto}s when
14286 computing Essential Complexity
14287
14288 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14289 Report the extra exit points for subprogram bodies. As an exit point, this
14290 metric counts @code{return} statements and raise statements in case when the
14291 raised exception is not handled in the same body. In case of a function this
14292 metric subtracts 1 from the number of exit points, because a function body
14293 must contain at least one @code{return} statement.
14294
14295 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14296 Do not report the extra exit points for subprogram bodies
14297 @end table
14298
14299
14300 @node Object-Oriented Metrics Control
14301 @subsubsection Object-Oriented Metrics Control
14302 @cindex Object-Oriented metrics control in @command{gnatmetric}
14303
14304 @noindent
14305 @cindex Coupling metrics (in in @command{gnatmetric})
14306 Coupling metrics are object-oriented metrics that measure the
14307 dependencies between a given class (or a group of classes) and the
14308 ``external world'' (that is, the other classes in the program). In this
14309 subsection the term ``class'' is used in its
14310 traditional object-oriented programming sense
14311 (an instantiable module that contains data and/or method members).
14312 A @emph{category} (of classes)
14313 is a group of closely related classes that are reused and/or
14314 modified together.
14315
14316 A class @code{K}'s @emph{efferent coupling} is the number of classes
14317 that @code{K} depends upon.
14318 A category's efferent coupling is the number of classes outside the
14319 category that the classes inside the category depend upon.
14320
14321 A class @code{K}'s @emph{afferent coupling} is the number of classes
14322 that depend upon @code{K}.
14323 A category's afferent coupling is the number of classes outside the
14324 category that depend on classes belonging to the category.
14325
14326 Ada's implementation of the object-oriented paradigm does not use the
14327 traditional class notion, so the definition of the coupling
14328 metrics for Ada maps the class and class category notions
14329 onto Ada constructs.
14330
14331 For the coupling metrics, several kinds of modules -- a library package,
14332 a library generic package, and a library generic package instantiation --
14333 that define a tagged type or an interface type are
14334 considered to be a class. A category consists of a library package (or
14335 a library generic package) that defines a tagged or an interface type,
14336 together with all its descendant (generic) packages that define tagged
14337 or interface types. For any package counted as a class,
14338 its body and subunits (if any) are considered
14339 together with its spec when counting the dependencies, and coupling
14340 metrics are reported for spec units only. For dependencies
14341 between classes, the Ada semantic dependencies are considered.
14342 For coupling metrics, only dependencies on units that are considered as
14343 classes, are considered.
14344
14345 When computing coupling metrics, @command{gnatmetric} counts only
14346 dependencies between units that are arguments of the gnatmetric call.
14347 Coupling metrics are program-wide (or project-wide) metrics, so to
14348 get a valid result, you should call @command{gnatmetric} for
14349 the whole set of sources that make up your program. It can be done
14350 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14351 option (see See @ref{The GNAT Driver and Project Files} for details.
14352
14353 By default, all the coupling metrics are disabled. You can use the following
14354 switches to specify the coupling metrics to be computed and reported:
14355
14356 @table @option
14357
14358 @ifclear vms
14359 @cindex @option{--package@var{x}} (@command{gnatmetric})
14360 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14361 @cindex @option{--category@var{x}} (@command{gnatmetric})
14362 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14363 @end ifclear
14364
14365 @ifset vms
14366 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14367 @end ifset
14368
14369 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14370 Report all the coupling metrics
14371
14372 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14373 Do not report any of  metrics
14374
14375 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14376 Report package efferent coupling
14377
14378 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14379 Do not report package efferent coupling
14380
14381 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14382 Report package afferent coupling
14383
14384 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14385 Do not report package afferent coupling
14386
14387 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14388 Report category efferent coupling
14389
14390 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14391 Do not report category efferent coupling
14392
14393 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14394 Report category afferent coupling
14395
14396 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14397 Do not report category afferent coupling
14398
14399 @end table
14400
14401 @node Other gnatmetric Switches
14402 @subsection Other @code{gnatmetric} Switches
14403
14404 @noindent
14405 Additional @command{gnatmetric} switches are as follows:
14406
14407 @table @option
14408 @item ^-files @var{filename}^/FILES=@var{filename}^
14409 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14410 Take the argument source files from the specified file. This file should be an
14411 ordinary text file containing file names separated by spaces or
14412 line breaks. You can use this switch more than once in the same call to
14413 @command{gnatmetric}. You also can combine this switch with
14414 an explicit list of files.
14415
14416 @item ^-v^/VERBOSE^
14417 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14418 Verbose mode;
14419 @command{gnatmetric} generates version information and then
14420 a trace of sources being processed.
14421
14422 @item ^-dv^/DEBUG_OUTPUT^
14423 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
14424 Debug mode;
14425 @command{gnatmetric} generates various messages useful to understand what
14426 happens during the metrics computation
14427
14428 @item ^-q^/QUIET^
14429 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14430 Quiet mode.
14431 @end table
14432
14433 @node Generate project-wide metrics
14434 @subsection Generate project-wide metrics
14435
14436 In order to compute metrics on all units of a given project, you can use
14437 the @command{gnat} driver along with the @option{-P} option:
14438 @smallexample
14439    gnat metric -Pproj
14440 @end smallexample
14441
14442 @noindent
14443 If the project @code{proj} depends upon other projects, you can compute
14444 the metrics on the project closure using the @option{-U} option:
14445 @smallexample
14446    gnat metric -Pproj -U
14447 @end smallexample
14448
14449 @noindent
14450 Finally, if not all the units are relevant to a particular main
14451 program in the project closure, you can generate metrics for the set
14452 of units needed to create a given main program (unit closure) using
14453 the @option{-U} option followed by the name of the main unit:
14454 @smallexample
14455    gnat metric -Pproj -U main
14456 @end smallexample
14457
14458
14459 @c ***********************************
14460 @node File Name Krunching Using gnatkr
14461 @chapter File Name Krunching Using @code{gnatkr}
14462 @findex gnatkr
14463
14464 @noindent
14465 This chapter discusses the method used by the compiler to shorten
14466 the default file names chosen for Ada units so that they do not
14467 exceed the maximum length permitted. It also describes the
14468 @code{gnatkr} utility that can be used to determine the result of
14469 applying this shortening.
14470 @menu
14471 * About gnatkr::
14472 * Using gnatkr::
14473 * Krunching Method::
14474 * Examples of gnatkr Usage::
14475 @end menu
14476
14477 @node About gnatkr
14478 @section About @code{gnatkr}
14479
14480 @noindent
14481 The default file naming rule in GNAT
14482 is that the file name must be derived from
14483 the unit name. The exact default rule is as follows:
14484 @itemize @bullet
14485 @item
14486 Take the unit name and replace all dots by hyphens.
14487 @item
14488 If such a replacement occurs in the
14489 second character position of a name, and the first character is
14490 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14491 then replace the dot by the character
14492 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14493 instead of a minus.
14494 @end itemize
14495 The reason for this exception is to avoid clashes
14496 with the standard names for children of System, Ada, Interfaces,
14497 and GNAT, which use the prefixes
14498 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14499 respectively.
14500
14501 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14502 switch of the compiler activates a ``krunching''
14503 circuit that limits file names to nn characters (where nn is a decimal
14504 integer). For example, using OpenVMS,
14505 where the maximum file name length is
14506 39, the value of nn is usually set to 39, but if you want to generate
14507 a set of files that would be usable if ported to a system with some
14508 different maximum file length, then a different value can be specified.
14509 The default value of 39 for OpenVMS need not be specified.
14510
14511 The @code{gnatkr} utility can be used to determine the krunched name for
14512 a given file, when krunched to a specified maximum length.
14513
14514 @node Using gnatkr
14515 @section Using @code{gnatkr}
14516
14517 @noindent
14518 The @code{gnatkr} command has the form
14519
14520 @ifclear vms
14521 @smallexample
14522 @c $ gnatkr @var{name} @ovar{length}
14523 @c Expanding @ovar macro inline (explanation in macro def comments)
14524 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14525 @end smallexample
14526 @end ifclear
14527
14528 @ifset vms
14529 @smallexample
14530 $ gnatkr @var{name} /COUNT=nn
14531 @end smallexample
14532 @end ifset
14533
14534 @noindent
14535 @var{name} is the uncrunched file name, derived from the name of the unit
14536 in the standard manner described in the previous section (i.e., in particular
14537 all dots are replaced by hyphens). The file name may or may not have an
14538 extension (defined as a suffix of the form period followed by arbitrary
14539 characters other than period). If an extension is present then it will
14540 be preserved in the output. For example, when krunching @file{hellofile.ads}
14541 to eight characters, the result will be hellofil.ads.
14542
14543 Note: for compatibility with previous versions of @code{gnatkr} dots may
14544 appear in the name instead of hyphens, but the last dot will always be
14545 taken as the start of an extension. So if @code{gnatkr} is given an argument
14546 such as @file{Hello.World.adb} it will be treated exactly as if the first
14547 period had been a hyphen, and for example krunching to eight characters
14548 gives the result @file{hellworl.adb}.
14549
14550 Note that the result is always all lower case (except on OpenVMS where it is
14551 all upper case). Characters of the other case are folded as required.
14552
14553 @var{length} represents the length of the krunched name. The default
14554 when no argument is given is ^8^39^ characters. A length of zero stands for
14555 unlimited, in other words do not chop except for system files where the
14556 implied crunching length is always eight characters.
14557
14558 @noindent
14559 The output is the krunched name. The output has an extension only if the
14560 original argument was a file name with an extension.
14561
14562 @node Krunching Method
14563 @section Krunching Method
14564
14565 @noindent
14566 The initial file name is determined by the name of the unit that the file
14567 contains. The name is formed by taking the full expanded name of the
14568 unit and replacing the separating dots with hyphens and
14569 using ^lowercase^uppercase^
14570 for all letters, except that a hyphen in the second character position is
14571 replaced by a ^tilde^dollar sign^ if the first character is
14572 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14573 The extension is @code{.ads} for a
14574 spec and @code{.adb} for a body.
14575 Krunching does not affect the extension, but the file name is shortened to
14576 the specified length by following these rules:
14577
14578 @itemize @bullet
14579 @item
14580 The name is divided into segments separated by hyphens, tildes or
14581 underscores and all hyphens, tildes, and underscores are
14582 eliminated. If this leaves the name short enough, we are done.
14583
14584 @item
14585 If the name is too long, the longest segment is located (left-most
14586 if there are two of equal length), and shortened by dropping
14587 its last character. This is repeated until the name is short enough.
14588
14589 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14590 to fit the name into 8 characters as required by some operating systems.
14591
14592 @smallexample
14593 our-strings-wide_fixed 22
14594 our strings wide fixed 19
14595 our string  wide fixed 18
14596 our strin   wide fixed 17
14597 our stri    wide fixed 16
14598 our stri    wide fixe  15
14599 our str     wide fixe  14
14600 our str     wid  fixe  13
14601 our str     wid  fix   12
14602 ou  str     wid  fix   11
14603 ou  st      wid  fix   10
14604 ou  st      wi   fix   9
14605 ou  st      wi   fi    8
14606 Final file name: oustwifi.adb
14607 @end smallexample
14608
14609 @item
14610 The file names for all predefined units are always krunched to eight
14611 characters. The krunching of these predefined units uses the following
14612 special prefix replacements:
14613
14614 @table @file
14615 @item ada-
14616 replaced by @file{^a^A^-}
14617
14618 @item gnat-
14619 replaced by @file{^g^G^-}
14620
14621 @item interfaces-
14622 replaced by @file{^i^I^-}
14623
14624 @item system-
14625 replaced by @file{^s^S^-}
14626 @end table
14627
14628 These system files have a hyphen in the second character position. That
14629 is why normal user files replace such a character with a
14630 ^tilde^dollar sign^, to
14631 avoid confusion with system file names.
14632
14633 As an example of this special rule, consider
14634 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14635
14636 @smallexample
14637 ada-strings-wide_fixed 22
14638 a-  strings wide fixed 18
14639 a-  string  wide fixed 17
14640 a-  strin   wide fixed 16
14641 a-  stri    wide fixed 15
14642 a-  stri    wide fixe  14
14643 a-  str     wide fixe  13
14644 a-  str     wid  fixe  12
14645 a-  str     wid  fix   11
14646 a-  st      wid  fix   10
14647 a-  st      wi   fix   9
14648 a-  st      wi   fi    8
14649 Final file name: a-stwifi.adb
14650 @end smallexample
14651 @end itemize
14652
14653 Of course no file shortening algorithm can guarantee uniqueness over all
14654 possible unit names, and if file name krunching is used then it is your
14655 responsibility to ensure that no name clashes occur. The utility
14656 program @code{gnatkr} is supplied for conveniently determining the
14657 krunched name of a file.
14658
14659 @node Examples of gnatkr Usage
14660 @section Examples of @code{gnatkr} Usage
14661
14662 @smallexample
14663 @iftex
14664 @leftskip=0cm
14665 @end iftex
14666 @ifclear vms
14667 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14668 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14669 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14670 $ gnatkr grandparent-parent-child     --> grparchi
14671 @end ifclear
14672 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14673 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14674 @end smallexample
14675
14676 @node Preprocessing Using gnatprep
14677 @chapter Preprocessing Using @code{gnatprep}
14678 @findex gnatprep
14679
14680 @noindent
14681 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14682 preprocessing.
14683 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14684 special GNAT features.
14685 For further discussion of conditional compilation in general, see
14686 @ref{Conditional Compilation}.
14687
14688 @menu
14689 * Preprocessing Symbols::
14690 * Using gnatprep::
14691 * Switches for gnatprep::
14692 * Form of Definitions File::
14693 * Form of Input Text for gnatprep::
14694 @end menu
14695
14696 @node Preprocessing Symbols
14697 @section Preprocessing Symbols
14698
14699 @noindent
14700 Preprocessing symbols are defined in definition files and referred to in
14701 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14702 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14703 all characters need to be in the ASCII set (no accented letters).
14704
14705 @node Using gnatprep
14706 @section Using @code{gnatprep}
14707
14708 @noindent
14709 To call @code{gnatprep} use
14710
14711 @smallexample
14712 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14713 @c Expanding @ovar macro inline (explanation in macro def comments)
14714 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14715 @end smallexample
14716
14717 @noindent
14718 where
14719 @table @var
14720 @item switches
14721 is an optional sequence of switches as described in the next section.
14722
14723 @item infile
14724 is the full name of the input file, which is an Ada source
14725 file containing preprocessor directives.
14726
14727 @item outfile
14728 is the full name of the output file, which is an Ada source
14729 in standard Ada form. When used with GNAT, this file name will
14730 normally have an ads or adb suffix.
14731
14732 @item deffile
14733 is the full name of a text file containing definitions of
14734 preprocessing symbols to be referenced by the preprocessor. This argument is
14735 optional, and can be replaced by the use of the @option{-D} switch.
14736
14737 @end table
14738
14739 @node Switches for gnatprep
14740 @section Switches for @code{gnatprep}
14741
14742 @table @option
14743 @c !sort!
14744
14745 @item ^-b^/BLANK_LINES^
14746 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14747 Causes both preprocessor lines and the lines deleted by
14748 preprocessing to be replaced by blank lines in the output source file,
14749 preserving line numbers in the output file.
14750
14751 @item ^-c^/COMMENTS^
14752 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14753 Causes both preprocessor lines and the lines deleted
14754 by preprocessing to be retained in the output source as comments marked
14755 with the special string @code{"--! "}. This option will result in line numbers
14756 being preserved in the output file.
14757
14758 @item ^-C^/REPLACE_IN_COMMENTS^
14759 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14760 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14761 If this option is specified, then comments are scanned and any $symbol
14762 substitutions performed as in program text. This is particularly useful
14763 when structured comments are used (e.g., when writing programs in the
14764 SPARK dialect of Ada). Note that this switch is not available when
14765 doing integrated preprocessing (it would be useless in this context
14766 since comments are ignored by the compiler in any case).
14767
14768 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14769 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14770 Defines a new preprocessing symbol, associated with value. If no value is given
14771 on the command line, then symbol is considered to be @code{True}. This switch
14772 can be used in place of a definition file.
14773
14774 @ifset vms
14775 @item /REMOVE
14776 @cindex @option{/REMOVE} (@command{gnatprep})
14777 This is the default setting which causes lines deleted by preprocessing
14778 to be entirely removed from the output file.
14779 @end ifset
14780
14781 @item ^-r^/REFERENCE^
14782 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14783 Causes a @code{Source_Reference} pragma to be generated that
14784 references the original input file, so that error messages will use
14785 the file name of this original file. The use of this switch implies
14786 that preprocessor lines are not to be removed from the file, so its
14787 use will force @option{^-b^/BLANK_LINES^} mode if
14788 @option{^-c^/COMMENTS^}
14789 has not been specified explicitly.
14790
14791 Note that if the file to be preprocessed contains multiple units, then
14792 it will be necessary to @code{gnatchop} the output file from
14793 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14794 in the preprocessed file, it will be respected by
14795 @code{gnatchop ^-r^/REFERENCE^}
14796 so that the final chopped files will correctly refer to the original
14797 input source file for @code{gnatprep}.
14798
14799 @item ^-s^/SYMBOLS^
14800 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14801 Causes a sorted list of symbol names and values to be
14802 listed on the standard output file.
14803
14804 @item ^-u^/UNDEFINED^
14805 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14806 Causes undefined symbols to be treated as having the value FALSE in the context
14807 of a preprocessor test. In the absence of this option, an undefined symbol in
14808 a @code{#if} or @code{#elsif} test will be treated as an error.
14809
14810 @end table
14811
14812 @ifclear vms
14813 @noindent
14814 Note: if neither @option{-b} nor @option{-c} is present,
14815 then preprocessor lines and
14816 deleted lines are completely removed from the output, unless -r is
14817 specified, in which case -b is assumed.
14818 @end ifclear
14819
14820 @node Form of Definitions File
14821 @section Form of Definitions File
14822
14823 @noindent
14824 The definitions file contains lines of the form
14825
14826 @smallexample
14827 symbol := value
14828 @end smallexample
14829
14830 @noindent
14831 where symbol is a preprocessing symbol, and value is one of the following:
14832
14833 @itemize @bullet
14834 @item
14835 Empty, corresponding to a null substitution
14836 @item
14837 A string literal using normal Ada syntax
14838 @item
14839 Any sequence of characters from the set
14840 (letters, digits, period, underline).
14841 @end itemize
14842
14843 @noindent
14844 Comment lines may also appear in the definitions file, starting with
14845 the usual @code{--},
14846 and comments may be added to the definitions lines.
14847
14848 @node Form of Input Text for gnatprep
14849 @section Form of Input Text for @code{gnatprep}
14850
14851 @noindent
14852 The input text may contain preprocessor conditional inclusion lines,
14853 as well as general symbol substitution sequences.
14854
14855 The preprocessor conditional inclusion commands have the form
14856
14857 @smallexample
14858 @group
14859 @cartouche
14860 #if @i{expression} @r{[}then@r{]}
14861    lines
14862 #elsif @i{expression} @r{[}then@r{]}
14863    lines
14864 #elsif @i{expression} @r{[}then@r{]}
14865    lines
14866 @dots{}
14867 #else
14868    lines
14869 #end if;
14870 @end cartouche
14871 @end group
14872 @end smallexample
14873
14874 @noindent
14875 In this example, @i{expression} is defined by the following grammar:
14876 @smallexample
14877 @i{expression} ::=  <symbol>
14878 @i{expression} ::=  <symbol> = "<value>"
14879 @i{expression} ::=  <symbol> = <symbol>
14880 @i{expression} ::=  <symbol> 'Defined
14881 @i{expression} ::=  not @i{expression}
14882 @i{expression} ::=  @i{expression} and @i{expression}
14883 @i{expression} ::=  @i{expression} or @i{expression}
14884 @i{expression} ::=  @i{expression} and then @i{expression}
14885 @i{expression} ::=  @i{expression} or else @i{expression}
14886 @i{expression} ::=  ( @i{expression} )
14887 @end smallexample
14888
14889 The following restriction exists: it is not allowed to have "and" or "or"
14890 following "not" in the same expression without parentheses. For example, this
14891 is not allowed:
14892
14893 @smallexample
14894    not X or Y
14895 @end smallexample
14896
14897 This should be one of the following:
14898
14899 @smallexample
14900    (not X) or Y
14901    not (X or Y)
14902 @end smallexample
14903
14904 @noindent
14905 For the first test (@i{expression} ::= <symbol>) the symbol must have
14906 either the value true or false, that is to say the right-hand of the
14907 symbol definition must be one of the (case-insensitive) literals
14908 @code{True} or @code{False}. If the value is true, then the
14909 corresponding lines are included, and if the value is false, they are
14910 excluded.
14911
14912 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14913 the symbol has been defined in the definition file or by a @option{-D}
14914 switch on the command line. Otherwise, the test is false.
14915
14916 The equality tests are case insensitive, as are all the preprocessor lines.
14917
14918 If the symbol referenced is not defined in the symbol definitions file,
14919 then the effect depends on whether or not switch @option{-u}
14920 is specified. If so, then the symbol is treated as if it had the value
14921 false and the test fails. If this switch is not specified, then
14922 it is an error to reference an undefined symbol. It is also an error to
14923 reference a symbol that is defined with a value other than @code{True}
14924 or @code{False}.
14925
14926 The use of the @code{not} operator inverts the sense of this logical test.
14927 The @code{not} operator cannot be combined with the @code{or} or @code{and}
14928 operators, without parentheses. For example, "if not X or Y then" is not
14929 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
14930
14931 The @code{then} keyword is optional as shown
14932
14933 The @code{#} must be the first non-blank character on a line, but
14934 otherwise the format is free form. Spaces or tabs may appear between
14935 the @code{#} and the keyword. The keywords and the symbols are case
14936 insensitive as in normal Ada code. Comments may be used on a
14937 preprocessor line, but other than that, no other tokens may appear on a
14938 preprocessor line. Any number of @code{elsif} clauses can be present,
14939 including none at all. The @code{else} is optional, as in Ada.
14940
14941 The @code{#} marking the start of a preprocessor line must be the first
14942 non-blank character on the line, i.e., it must be preceded only by
14943 spaces or horizontal tabs.
14944
14945 Symbol substitution outside of preprocessor lines is obtained by using
14946 the sequence
14947
14948 @smallexample
14949 $symbol
14950 @end smallexample
14951
14952 @noindent
14953 anywhere within a source line, except in a comment or within a
14954 string literal. The identifier
14955 following the @code{$} must match one of the symbols defined in the symbol
14956 definition file, and the result is to substitute the value of the
14957 symbol in place of @code{$symbol} in the output file.
14958
14959 Note that although the substitution of strings within a string literal
14960 is not possible, it is possible to have a symbol whose defined value is
14961 a string literal. So instead of setting XYZ to @code{hello} and writing:
14962
14963 @smallexample
14964 Header : String := "$XYZ";
14965 @end smallexample
14966
14967 @noindent
14968 you should set XYZ to @code{"hello"} and write:
14969
14970 @smallexample
14971 Header : String := $XYZ;
14972 @end smallexample
14973
14974 @noindent
14975 and then the substitution will occur as desired.
14976
14977 @ifset vms
14978 @node The GNAT Run-Time Library Builder gnatlbr
14979 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
14980 @findex gnatlbr
14981 @cindex Library builder
14982
14983 @noindent
14984 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
14985 supplied configuration pragmas.
14986
14987 @menu
14988 * Running gnatlbr::
14989 * Switches for gnatlbr::
14990 * Examples of gnatlbr Usage::
14991 @end menu
14992
14993 @node Running gnatlbr
14994 @section Running @code{gnatlbr}
14995
14996 @noindent
14997 The @code{gnatlbr} command has the form
14998
14999 @smallexample
15000 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
15001 @end smallexample
15002
15003 @node Switches for gnatlbr
15004 @section Switches for @code{gnatlbr}
15005
15006 @noindent
15007 @code{gnatlbr} recognizes the following switches:
15008
15009 @table @option
15010 @c !sort!
15011 @item /CREATE=directory
15012 @cindex @code{/CREATE} (@code{gnatlbr})
15013 Create the new run-time library in the specified directory.
15014
15015 @item /SET=directory
15016 @cindex @code{/SET} (@code{gnatlbr})
15017 Make the library in the specified directory the current run-time library.
15018
15019 @item /DELETE=directory
15020 @cindex @code{/DELETE} (@code{gnatlbr})
15021 Delete the run-time library in the specified directory.
15022
15023 @item /CONFIG=file
15024 @cindex @code{/CONFIG} (@code{gnatlbr})
15025 With /CREATE: Use the configuration pragmas in the specified file when
15026 building the library.
15027
15028 With /SET: Use the configuration pragmas in the specified file when
15029 compiling.
15030
15031 @end table
15032
15033 @node Examples of gnatlbr Usage
15034 @section Example of @code{gnatlbr} Usage
15035
15036 @smallexample
15037 Contents of VAXFLOAT.ADC:
15038 pragma Float_Representation (VAX_Float);
15039
15040 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15041
15042 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15043
15044 @end smallexample
15045 @end ifset
15046
15047 @node The GNAT Library Browser gnatls
15048 @chapter The GNAT Library Browser @code{gnatls}
15049 @findex gnatls
15050 @cindex Library browser
15051
15052 @noindent
15053 @code{gnatls} is a tool that outputs information about compiled
15054 units. It gives the relationship between objects, unit names and source
15055 files. It can also be used to check the source dependencies of a unit
15056 as well as various characteristics.
15057
15058 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15059 driver (see @ref{The GNAT Driver and Project Files}).
15060
15061 @menu
15062 * Running gnatls::
15063 * Switches for gnatls::
15064 * Examples of gnatls Usage::
15065 @end menu
15066
15067 @node Running gnatls
15068 @section Running @code{gnatls}
15069
15070 @noindent
15071 The @code{gnatls} command has the form
15072
15073 @smallexample
15074 $ gnatls switches @var{object_or_ali_file}
15075 @end smallexample
15076
15077 @noindent
15078 The main argument is the list of object or @file{ali} files
15079 (@pxref{The Ada Library Information Files})
15080 for which information is requested.
15081
15082 In normal mode, without additional option, @code{gnatls} produces a
15083 four-column listing. Each line represents information for a specific
15084 object. The first column gives the full path of the object, the second
15085 column gives the name of the principal unit in this object, the third
15086 column gives the status of the source and the fourth column gives the
15087 full path of the source representing this unit.
15088 Here is a simple example of use:
15089
15090 @smallexample
15091 $ gnatls *.o
15092 ^./^[]^demo1.o            demo1            DIF demo1.adb
15093 ^./^[]^demo2.o            demo2             OK demo2.adb
15094 ^./^[]^hello.o            h1                OK hello.adb
15095 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15096 ^./^[]^instr.o            instr             OK instr.adb
15097 ^./^[]^tef.o              tef              DIF tef.adb
15098 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15099 ^./^[]^tgef.o             tgef             DIF tgef.adb
15100 @end smallexample
15101
15102 @noindent
15103 The first line can be interpreted as follows: the main unit which is
15104 contained in
15105 object file @file{demo1.o} is demo1, whose main source is in
15106 @file{demo1.adb}. Furthermore, the version of the source used for the
15107 compilation of demo1 has been modified (DIF). Each source file has a status
15108 qualifier which can be:
15109
15110 @table @code
15111 @item OK (unchanged)
15112 The version of the source file used for the compilation of the
15113 specified unit corresponds exactly to the actual source file.
15114
15115 @item MOK (slightly modified)
15116 The version of the source file used for the compilation of the
15117 specified unit differs from the actual source file but not enough to
15118 require recompilation. If you use gnatmake with the qualifier
15119 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15120 MOK will not be recompiled.
15121
15122 @item DIF (modified)
15123 No version of the source found on the path corresponds to the source
15124 used to build this object.
15125
15126 @item ??? (file not found)
15127 No source file was found for this unit.
15128
15129 @item HID (hidden,  unchanged version not first on PATH)
15130 The version of the source that corresponds exactly to the source used
15131 for compilation has been found on the path but it is hidden by another
15132 version of the same source that has been modified.
15133
15134 @end table
15135
15136 @node Switches for gnatls
15137 @section Switches for @code{gnatls}
15138
15139 @noindent
15140 @code{gnatls} recognizes the following switches:
15141
15142 @table @option
15143 @c !sort!
15144 @cindex @option{--version} @command{gnatls}
15145 Display Copyright and version, then exit disregarding all other options.
15146
15147 @item --help
15148 @cindex @option{--help} @command{gnatls}
15149 If @option{--version} was not used, display usage, then exit disregarding
15150 all other options.
15151
15152 @item ^-a^/ALL_UNITS^
15153 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15154 Consider all units, including those of the predefined Ada library.
15155 Especially useful with @option{^-d^/DEPENDENCIES^}.
15156
15157 @item ^-d^/DEPENDENCIES^
15158 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15159 List sources from which specified units depend on.
15160
15161 @item ^-h^/OUTPUT=OPTIONS^
15162 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15163 Output the list of options.
15164
15165 @item ^-o^/OUTPUT=OBJECTS^
15166 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15167 Only output information about object files.
15168
15169 @item ^-s^/OUTPUT=SOURCES^
15170 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15171 Only output information about source files.
15172
15173 @item ^-u^/OUTPUT=UNITS^
15174 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15175 Only output information about compilation units.
15176
15177 @item ^-files^/FILES^=@var{file}
15178 @cindex @option{^-files^/FILES^} (@code{gnatls})
15179 Take as arguments the files listed in text file @var{file}.
15180 Text file @var{file} may contain empty lines that are ignored.
15181 Each nonempty line should contain the name of an existing file.
15182 Several such switches may be specified simultaneously.
15183
15184 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15185 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15186 @itemx ^-I^/SEARCH=^@var{dir}
15187 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15188 @itemx -nostdinc
15189 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15190 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15191 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15192 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15193 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15194 flags (@pxref{Switches for gnatmake}).
15195
15196 @item --RTS=@var{rts-path}
15197 @cindex @option{--RTS} (@code{gnatls})
15198 Specifies the default location of the runtime library. Same meaning as the
15199 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15200
15201 @item ^-v^/OUTPUT=VERBOSE^
15202 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15203 Verbose mode. Output the complete source, object and project paths. Do not use
15204 the default column layout but instead use long format giving as much as
15205 information possible on each requested units, including special
15206 characteristics such as:
15207
15208 @table @code
15209 @item  Preelaborable
15210 The unit is preelaborable in the Ada sense.
15211
15212 @item No_Elab_Code
15213 No elaboration code has been produced by the compiler for this unit.
15214
15215 @item Pure
15216 The unit is pure in the Ada sense.
15217
15218 @item Elaborate_Body
15219 The unit contains a pragma Elaborate_Body.
15220
15221 @item Remote_Types
15222 The unit contains a pragma Remote_Types.
15223
15224 @item Shared_Passive
15225 The unit contains a pragma Shared_Passive.
15226
15227 @item Predefined
15228 This unit is part of the predefined environment and cannot be modified
15229 by the user.
15230
15231 @item Remote_Call_Interface
15232 The unit contains a pragma Remote_Call_Interface.
15233
15234 @end table
15235
15236 @end table
15237
15238 @node Examples of gnatls Usage
15239 @section Example of @code{gnatls} Usage
15240 @ifclear vms
15241
15242 @noindent
15243 Example of using the verbose switch. Note how the source and
15244 object paths are affected by the -I switch.
15245
15246 @smallexample
15247 $ gnatls -v -I.. demo1.o
15248
15249 GNATLS 5.03w (20041123-34)
15250 Copyright 1997-2004 Free Software Foundation, Inc.
15251
15252 Source Search Path:
15253    <Current_Directory>
15254    ../
15255    /home/comar/local/adainclude/
15256
15257 Object Search Path:
15258    <Current_Directory>
15259    ../
15260    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15261
15262 Project Search Path:
15263    <Current_Directory>
15264    /home/comar/local/lib/gnat/
15265
15266 ./demo1.o
15267    Unit =>
15268      Name   => demo1
15269      Kind   => subprogram body
15270      Flags  => No_Elab_Code
15271      Source => demo1.adb    modified
15272 @end smallexample
15273
15274 @noindent
15275 The following is an example of use of the dependency list.
15276 Note the use of the -s switch
15277 which gives a straight list of source files. This can be useful for
15278 building specialized scripts.
15279
15280 @smallexample
15281 $ gnatls -d demo2.o
15282 ./demo2.o   demo2        OK demo2.adb
15283                          OK gen_list.ads
15284                          OK gen_list.adb
15285                          OK instr.ads
15286                          OK instr-child.ads
15287
15288 $ gnatls -d -s -a demo1.o
15289 demo1.adb
15290 /home/comar/local/adainclude/ada.ads
15291 /home/comar/local/adainclude/a-finali.ads
15292 /home/comar/local/adainclude/a-filico.ads
15293 /home/comar/local/adainclude/a-stream.ads
15294 /home/comar/local/adainclude/a-tags.ads
15295 gen_list.ads
15296 gen_list.adb
15297 /home/comar/local/adainclude/gnat.ads
15298 /home/comar/local/adainclude/g-io.ads
15299 instr.ads
15300 /home/comar/local/adainclude/system.ads
15301 /home/comar/local/adainclude/s-exctab.ads
15302 /home/comar/local/adainclude/s-finimp.ads
15303 /home/comar/local/adainclude/s-finroo.ads
15304 /home/comar/local/adainclude/s-secsta.ads
15305 /home/comar/local/adainclude/s-stalib.ads
15306 /home/comar/local/adainclude/s-stoele.ads
15307 /home/comar/local/adainclude/s-stratt.ads
15308 /home/comar/local/adainclude/s-tasoli.ads
15309 /home/comar/local/adainclude/s-unstyp.ads
15310 /home/comar/local/adainclude/unchconv.ads
15311 @end smallexample
15312 @end ifclear
15313
15314 @ifset vms
15315 @smallexample
15316 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15317
15318 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15319 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15320 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15321 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15322 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15323 demo1.adb
15324 gen_list.ads
15325 gen_list.adb
15326 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15327 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15328 instr.ads
15329 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15330 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15331 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15332 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15333 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15334 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15335 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15336 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15337 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15338 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15339 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15340 @end smallexample
15341 @end ifset
15342
15343 @node Cleaning Up Using gnatclean
15344 @chapter Cleaning Up Using @code{gnatclean}
15345 @findex gnatclean
15346 @cindex Cleaning tool
15347
15348 @noindent
15349 @code{gnatclean} is a tool that allows the deletion of files produced by the
15350 compiler, binder and linker, including ALI files, object files, tree files,
15351 expanded source files, library files, interface copy source files, binder
15352 generated files and executable files.
15353
15354 @menu
15355 * Running gnatclean::
15356 * Switches for gnatclean::
15357 @c * Examples of gnatclean Usage::
15358 @end menu
15359
15360 @node Running gnatclean
15361 @section Running @code{gnatclean}
15362
15363 @noindent
15364 The @code{gnatclean} command has the form:
15365
15366 @smallexample
15367 $ gnatclean switches @var{names}
15368 @end smallexample
15369
15370 @noindent
15371 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15372 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15373 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15374
15375 @noindent
15376 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15377 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15378 the linker. In informative-only mode, specified by switch
15379 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15380 normal mode is listed, but no file is actually deleted.
15381
15382 @node Switches for gnatclean
15383 @section Switches for @code{gnatclean}
15384
15385 @noindent
15386 @code{gnatclean} recognizes the following switches:
15387
15388 @table @option
15389 @c !sort!
15390 @cindex @option{--version} @command{gnatclean}
15391 Display Copyright and version, then exit disregarding all other options.
15392
15393 @item --help
15394 @cindex @option{--help} @command{gnatclean}
15395 If @option{--version} was not used, display usage, then exit disregarding
15396 all other options.
15397
15398 @item ^--subdirs^/SUBDIRS^=subdir
15399 Actual object directory of each project file is the subdirectory subdir of the
15400 object directory specified or defauted in the project file.
15401
15402 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15403 By default, shared library projects are not allowed to import static library
15404 projects. When this switch is used on the command line, this restriction is
15405 relaxed.
15406
15407 @item ^-c^/COMPILER_FILES_ONLY^
15408 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15409 Only attempt to delete the files produced by the compiler, not those produced
15410 by the binder or the linker. The files that are not to be deleted are library
15411 files, interface copy files, binder generated files and executable files.
15412
15413 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15414 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15415 Indicate that ALI and object files should normally be found in directory
15416 @var{dir}.
15417
15418 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15419 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15420 When using project files, if some errors or warnings are detected during
15421 parsing and verbose mode is not in effect (no use of switch
15422 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15423 file, rather than its simple file name.
15424
15425 @item ^-h^/HELP^
15426 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15427 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15428
15429 @item ^-n^/NODELETE^
15430 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15431 Informative-only mode. Do not delete any files. Output the list of the files
15432 that would have been deleted if this switch was not specified.
15433
15434 @item ^-P^/PROJECT_FILE=^@var{project}
15435 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15436 Use project file @var{project}. Only one such switch can be used.
15437 When cleaning a project file, the files produced by the compilation of the
15438 immediate sources or inherited sources of the project files are to be
15439 deleted. This is not depending on the presence or not of executable names
15440 on the command line.
15441
15442 @item ^-q^/QUIET^
15443 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15444 Quiet output. If there are no errors, do not output anything, except in
15445 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15446 (switch ^-n^/NODELETE^).
15447
15448 @item ^-r^/RECURSIVE^
15449 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15450 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15451 clean all imported and extended project files, recursively. If this switch
15452 is not specified, only the files related to the main project file are to be
15453 deleted. This switch has no effect if no project file is specified.
15454
15455 @item ^-v^/VERBOSE^
15456 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15457 Verbose mode.
15458
15459 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15460 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15461 Indicates the verbosity of the parsing of GNAT project files.
15462 @xref{Switches Related to Project Files}.
15463
15464 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15465 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15466 Indicates that external variable @var{name} has the value @var{value}.
15467 The Project Manager will use this value for occurrences of
15468 @code{external(name)} when parsing the project file.
15469 @xref{Switches Related to Project Files}.
15470
15471 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15472 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15473 When searching for ALI and object files, look in directory
15474 @var{dir}.
15475
15476 @item ^-I^/SEARCH=^@var{dir}
15477 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15478 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15479
15480 @item ^-I-^/NOCURRENT_DIRECTORY^
15481 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15482 @cindex Source files, suppressing search
15483 Do not look for ALI or object files in the directory
15484 where @code{gnatclean} was invoked.
15485
15486 @end table
15487
15488 @c @node Examples of gnatclean Usage
15489 @c @section Examples of @code{gnatclean} Usage
15490
15491 @ifclear vms
15492 @node GNAT and Libraries
15493 @chapter GNAT and Libraries
15494 @cindex Library, building, installing, using
15495
15496 @noindent
15497 This chapter describes how to build and use libraries with GNAT, and also shows
15498 how to recompile the GNAT run-time library. You should be familiar with the
15499 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15500 chapter.
15501
15502 @menu
15503 * Introduction to Libraries in GNAT::
15504 * General Ada Libraries::
15505 * Stand-alone Ada Libraries::
15506 * Rebuilding the GNAT Run-Time Library::
15507 @end menu
15508
15509 @node Introduction to Libraries in GNAT
15510 @section Introduction to Libraries in GNAT
15511
15512 @noindent
15513 A library is, conceptually, a collection of objects which does not have its
15514 own main thread of execution, but rather provides certain services to the
15515 applications that use it. A library can be either statically linked with the
15516 application, in which case its code is directly included in the application,
15517 or, on platforms that support it, be dynamically linked, in which case
15518 its code is shared by all applications making use of this library.
15519
15520 GNAT supports both types of libraries.
15521 In the static case, the compiled code can be provided in different ways. The
15522 simplest approach is to provide directly the set of objects resulting from
15523 compilation of the library source files. Alternatively, you can group the
15524 objects into an archive using whatever commands are provided by the operating
15525 system. For the latter case, the objects are grouped into a shared library.
15526
15527 In the GNAT environment, a library has three types of components:
15528 @itemize @bullet
15529 @item
15530 Source files.
15531 @item
15532 @file{ALI} files.
15533 @xref{The Ada Library Information Files}.
15534 @item
15535 Object files, an archive or a shared library.
15536 @end itemize
15537
15538 @noindent
15539 A GNAT library may expose all its source files, which is useful for
15540 documentation purposes. Alternatively, it may expose only the units needed by
15541 an external user to make use of the library. That is to say, the specs
15542 reflecting the library services along with all the units needed to compile
15543 those specs, which can include generic bodies or any body implementing an
15544 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15545 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15546
15547 All compilation units comprising an application, including those in a library,
15548 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15549 computes the elaboration order from the @file{ALI} files and this is why they
15550 constitute a mandatory part of GNAT libraries.
15551 @emph{Stand-alone libraries} are the exception to this rule because a specific
15552 library elaboration routine is produced independently of the application(s)
15553 using the library.
15554
15555 @node General Ada Libraries
15556 @section General Ada Libraries
15557
15558 @menu
15559 * Building a library::
15560 * Installing a library::
15561 * Using a library::
15562 @end menu
15563
15564 @node Building a library
15565 @subsection Building a library
15566
15567 @noindent
15568 The easiest way to build a library is to use the Project Manager,
15569 which supports a special type of project called a @emph{Library Project}
15570 (@pxref{Library Projects}).
15571
15572 A project is considered a library project, when two project-level attributes
15573 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15574 control different aspects of library configuration, additional optional
15575 project-level attributes can be specified:
15576 @table @code
15577 @item Library_Kind
15578 This attribute controls whether the library is to be static or dynamic
15579
15580 @item Library_Version
15581 This attribute specifies the library version; this value is used
15582 during dynamic linking of shared libraries to determine if the currently
15583 installed versions of the binaries are compatible.
15584
15585 @item Library_Options
15586 @item Library_GCC
15587 These attributes specify additional low-level options to be used during
15588 library generation, and redefine the actual application used to generate
15589 library.
15590 @end table
15591
15592 @noindent
15593 The GNAT Project Manager takes full care of the library maintenance task,
15594 including recompilation of the source files for which objects do not exist
15595 or are not up to date, assembly of the library archive, and installation of
15596 the library (i.e., copying associated source, object and @file{ALI} files
15597 to the specified location).
15598
15599 Here is a simple library project file:
15600 @smallexample @c ada
15601 project My_Lib is
15602    for Source_Dirs use ("src1", "src2");
15603    for Object_Dir use "obj";
15604    for Library_Name use "mylib";
15605    for Library_Dir use "lib";
15606    for Library_Kind use "dynamic";
15607 end My_lib;
15608 @end smallexample
15609
15610 @noindent
15611 and the compilation command to build and install the library:
15612
15613 @smallexample @c ada
15614   $ gnatmake -Pmy_lib
15615 @end smallexample
15616
15617 @noindent
15618 It is not entirely trivial to perform manually all the steps required to
15619 produce a library. We recommend that you use the GNAT Project Manager
15620 for this task. In special cases where this is not desired, the necessary
15621 steps are discussed below.
15622
15623 There are various possibilities for compiling the units that make up the
15624 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15625 with a conventional script. For simple libraries, it is also possible to create
15626 a dummy main program which depends upon all the packages that comprise the
15627 interface of the library. This dummy main program can then be given to
15628 @command{gnatmake}, which will ensure that all necessary objects are built.
15629
15630 After this task is accomplished, you should follow the standard procedure
15631 of the underlying operating system to produce the static or shared library.
15632
15633 Here is an example of such a dummy program:
15634 @smallexample @c ada
15635 @group
15636 with My_Lib.Service1;
15637 with My_Lib.Service2;
15638 with My_Lib.Service3;
15639 procedure My_Lib_Dummy is
15640 begin
15641    null;
15642 end;
15643 @end group
15644 @end smallexample
15645
15646 @noindent
15647 Here are the generic commands that will build an archive or a shared library.
15648
15649 @smallexample
15650 # compiling the library
15651 $ gnatmake -c my_lib_dummy.adb
15652
15653 # we don't need the dummy object itself
15654 $ rm my_lib_dummy.o my_lib_dummy.ali
15655
15656 # create an archive with the remaining objects
15657 $ ar rc libmy_lib.a *.o
15658 # some systems may require "ranlib" to be run as well
15659
15660 # or create a shared library
15661 $ gcc -shared -o libmy_lib.so *.o
15662 # some systems may require the code to have been compiled with -fPIC
15663
15664 # remove the object files that are now in the library
15665 $ rm *.o
15666
15667 # Make the ALI files read-only so that gnatmake will not try to
15668 # regenerate the objects that are in the library
15669 $ chmod -w *.ali
15670 @end smallexample
15671
15672 @noindent
15673 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15674 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15675 be accessed by the directive @option{-l@var{xxx}} at link time.
15676
15677 @node Installing a library
15678 @subsection Installing a library
15679 @cindex @code{ADA_PROJECT_PATH}
15680 @cindex @code{GPR_PROJECT_PATH}
15681
15682 @noindent
15683 If you use project files, library installation is part of the library build
15684 process (@pxref{Installing a library with project files}).
15685
15686 When project files are not an option, it is also possible, but not recommended,
15687 to install the library so that the sources needed to use the library are on the
15688 Ada source path and the ALI files & libraries be on the Ada Object path (see
15689 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15690 administrator can place general-purpose libraries in the default compiler
15691 paths, by specifying the libraries' location in the configuration files
15692 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15693 must be located in the GNAT installation tree at the same place as the gcc spec
15694 file. The location of the gcc spec file can be determined as follows:
15695 @smallexample
15696 $ gcc -v
15697 @end smallexample
15698
15699 @noindent
15700 The configuration files mentioned above have a simple format: each line
15701 must contain one unique directory name.
15702 Those names are added to the corresponding path
15703 in their order of appearance in the file. The names can be either absolute
15704 or relative; in the latter case, they are relative to where theses files
15705 are located.
15706
15707 The files @file{ada_source_path} and @file{ada_object_path} might not be
15708 present in a
15709 GNAT installation, in which case, GNAT will look for its run-time library in
15710 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15711 objects and @file{ALI} files). When the files exist, the compiler does not
15712 look in @file{adainclude} and @file{adalib}, and thus the
15713 @file{ada_source_path} file
15714 must contain the location for the GNAT run-time sources (which can simply
15715 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15716 contain the location for the GNAT run-time objects (which can simply
15717 be @file{adalib}).
15718
15719 You can also specify a new default path to the run-time library at compilation
15720 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15721 the run-time library you want your program to be compiled with. This switch is
15722 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15723 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15724
15725 It is possible to install a library before or after the standard GNAT
15726 library, by reordering the lines in the configuration files. In general, a
15727 library must be installed before the GNAT library if it redefines
15728 any part of it.
15729
15730 @node Using a library
15731 @subsection Using a library
15732
15733 @noindent Once again, the project facility greatly simplifies the use of
15734 libraries. In this context, using a library is just a matter of adding a
15735 @code{with} clause in the user project. For instance, to make use of the
15736 library @code{My_Lib} shown in examples in earlier sections, you can
15737 write:
15738
15739 @smallexample @c projectfile
15740 with "my_lib";
15741 project My_Proj is
15742   @dots{}
15743 end My_Proj;
15744 @end smallexample
15745
15746 Even if you have a third-party, non-Ada library, you can still use GNAT's
15747 Project Manager facility to provide a wrapper for it. For example, the
15748 following project, when @code{with}ed by your main project, will link with the
15749 third-party library @file{liba.a}:
15750
15751 @smallexample @c projectfile
15752 @group
15753 project Liba is
15754    for Externally_Built use "true";
15755    for Source_Files use ();
15756    for Library_Dir use "lib";
15757    for Library_Name use "a";
15758    for Library_Kind use "static";
15759 end Liba;
15760 @end group
15761 @end smallexample
15762 This is an alternative to the use of @code{pragma Linker_Options}. It is
15763 especially interesting in the context of systems with several interdependent
15764 static libraries where finding a proper linker order is not easy and best be
15765 left to the tools having visibility over project dependence information.
15766
15767 @noindent
15768 In order to use an Ada library manually, you need to make sure that this
15769 library is on both your source and object path
15770 (see @ref{Search Paths and the Run-Time Library (RTL)}
15771 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15772 in an archive or a shared library, you need to specify the desired
15773 library at link time.
15774
15775 For example, you can use the library @file{mylib} installed in
15776 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15777
15778 @smallexample
15779 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15780   -largs -lmy_lib
15781 @end smallexample
15782
15783 @noindent
15784 This can be expressed more simply:
15785 @smallexample
15786 $ gnatmake my_appl
15787 @end smallexample
15788 @noindent
15789 when the following conditions are met:
15790 @itemize @bullet
15791 @item
15792 @file{/dir/my_lib_src} has been added by the user to the environment
15793 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15794 @file{ada_source_path}
15795 @item
15796 @file{/dir/my_lib_obj} has been added by the user to the environment
15797 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15798 @file{ada_object_path}
15799 @item
15800 a pragma @code{Linker_Options} has been added to one of the sources.
15801 For example:
15802
15803 @smallexample @c ada
15804 pragma Linker_Options ("-lmy_lib");
15805 @end smallexample
15806 @end itemize
15807
15808 @node Stand-alone Ada Libraries
15809 @section Stand-alone Ada Libraries
15810 @cindex Stand-alone library, building, using
15811
15812 @menu
15813 * Introduction to Stand-alone Libraries::
15814 * Building a Stand-alone Library::
15815 * Creating a Stand-alone Library to be used in a non-Ada context::
15816 * Restrictions in Stand-alone Libraries::
15817 @end menu
15818
15819 @node Introduction to Stand-alone Libraries
15820 @subsection Introduction to Stand-alone Libraries
15821
15822 @noindent
15823 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15824 necessary code to
15825 elaborate the Ada units that are included in the library. In contrast with
15826 an ordinary library, which consists of all sources, objects and @file{ALI}
15827 files of the
15828 library, a SAL may specify a restricted subset of compilation units
15829 to serve as a library interface. In this case, the fully
15830 self-sufficient set of files will normally consist of an objects
15831 archive, the sources of interface units' specs, and the @file{ALI}
15832 files of interface units.
15833 If an interface spec contains a generic unit or an inlined subprogram,
15834 the body's
15835 source must also be provided; if the units that must be provided in the source
15836 form depend on other units, the source and @file{ALI} files of those must
15837 also be provided.
15838
15839 The main purpose of a SAL is to minimize the recompilation overhead of client
15840 applications when a new version of the library is installed. Specifically,
15841 if the interface sources have not changed, client applications do not need to
15842 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15843 version, controlled by @code{Library_Version} attribute, is not changed,
15844 then the clients do not need to be relinked.
15845
15846 SALs also allow the library providers to minimize the amount of library source
15847 text exposed to the clients.  Such ``information hiding'' might be useful or
15848 necessary for various reasons.
15849
15850 Stand-alone libraries are also well suited to be used in an executable whose
15851 main routine is not written in Ada.
15852
15853 @node Building a Stand-alone Library
15854 @subsection Building a Stand-alone Library
15855
15856 @noindent
15857 GNAT's Project facility provides a simple way of building and installing
15858 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15859 To be a Stand-alone Library Project, in addition to the two attributes
15860 that make a project a Library Project (@code{Library_Name} and
15861 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15862 @code{Library_Interface} must be defined.  For example:
15863
15864 @smallexample @c projectfile
15865 @group
15866    for Library_Dir use "lib_dir";
15867    for Library_Name use "dummy";
15868    for Library_Interface use ("int1", "int1.child");
15869 @end group
15870 @end smallexample
15871
15872 @noindent
15873 Attribute @code{Library_Interface} has a non-empty string list value,
15874 each string in the list designating a unit contained in an immediate source
15875 of the project file.
15876
15877 When a Stand-alone Library is built, first the binder is invoked to build
15878 a package whose name depends on the library name
15879 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15880 This binder-generated package includes initialization and
15881 finalization procedures whose
15882 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15883 in the example
15884 above). The object corresponding to this package is included in the library.
15885
15886 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15887 calling of these procedures if a static SAL is built, or if a shared SAL
15888 is built
15889 with the project-level attribute @code{Library_Auto_Init} set to
15890 @code{"false"}.
15891
15892 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15893 (those that are listed in attribute @code{Library_Interface}) are copied to
15894 the Library Directory. As a consequence, only the Interface Units may be
15895 imported from Ada units outside of the library. If other units are imported,
15896 the binding phase will fail.
15897
15898 The attribute @code{Library_Src_Dir} may be specified for a
15899 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15900 single string value. Its value must be the path (absolute or relative to the
15901 project directory) of an existing directory. This directory cannot be the
15902 object directory or one of the source directories, but it can be the same as
15903 the library directory. The sources of the Interface
15904 Units of the library that are needed by an Ada client of the library will be
15905 copied to the designated directory, called the Interface Copy directory.
15906 These sources include the specs of the Interface Units, but they may also
15907 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15908 are used, or when there is a generic unit in the spec. Before the sources
15909 are copied to the Interface Copy directory, an attempt is made to delete all
15910 files in the Interface Copy directory.
15911
15912 Building stand-alone libraries by hand is somewhat tedious, but for those
15913 occasions when it is necessary here are the steps that you need to perform:
15914 @itemize @bullet
15915 @item
15916 Compile all library sources.
15917
15918 @item
15919 Invoke the binder with the switch @option{-n} (No Ada main program),
15920 with all the @file{ALI} files of the interfaces, and
15921 with the switch @option{-L} to give specific names to the @code{init}
15922 and @code{final} procedures.  For example:
15923 @smallexample
15924   gnatbind -n int1.ali int2.ali -Lsal1
15925 @end smallexample
15926
15927 @item
15928 Compile the binder generated file:
15929 @smallexample
15930   gcc -c b~int2.adb
15931 @end smallexample
15932
15933 @item
15934 Link the dynamic library with all the necessary object files,
15935 indicating to the linker the names of the @code{init} (and possibly
15936 @code{final}) procedures for automatic initialization (and finalization).
15937 The built library should be placed in a directory different from
15938 the object directory.
15939
15940 @item
15941 Copy the @code{ALI} files of the interface to the library directory,
15942 add in this copy an indication that it is an interface to a SAL
15943 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
15944 with letter ``P'') and make the modified copy of the @file{ALI} file
15945 read-only.
15946 @end itemize
15947
15948 @noindent
15949 Using SALs is not different from using other libraries
15950 (see @ref{Using a library}).
15951
15952 @node Creating a Stand-alone Library to be used in a non-Ada context
15953 @subsection Creating a Stand-alone Library to be used in a non-Ada context
15954
15955 @noindent
15956 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
15957 a non-Ada context.
15958
15959 The only extra step required is to ensure that library interface subprograms
15960 are compatible with the main program, by means of @code{pragma Export}
15961 or @code{pragma Convention}.
15962
15963 Here is an example of simple library interface for use with C main program:
15964
15965 @smallexample @c ada
15966 package My_Package is
15967
15968    procedure Do_Something;
15969    pragma Export (C, Do_Something, "do_something");
15970
15971    procedure Do_Something_Else;
15972    pragma Export (C, Do_Something_Else, "do_something_else");
15973
15974 end My_Package;
15975 @end smallexample
15976
15977 @noindent
15978 On the foreign language side, you must provide a ``foreign'' view of the
15979 library interface; remember that it should contain elaboration routines in
15980 addition to interface subprograms.
15981
15982 The example below shows the content of @code{mylib_interface.h} (note
15983 that there is no rule for the naming of this file, any name can be used)
15984 @smallexample
15985 /* the library elaboration procedure */
15986 extern void mylibinit (void);
15987
15988 /* the library finalization procedure */
15989 extern void mylibfinal (void);
15990
15991 /* the interface exported by the library */
15992 extern void do_something (void);
15993 extern void do_something_else (void);
15994 @end smallexample
15995
15996 @noindent
15997 Libraries built as explained above can be used from any program, provided
15998 that the elaboration procedures (named @code{mylibinit} in the previous
15999 example) are called before the library services are used. Any number of
16000 libraries can be used simultaneously, as long as the elaboration
16001 procedure of each library is called.
16002
16003 Below is an example of a C program that uses the @code{mylib} library.
16004
16005 @smallexample
16006 #include "mylib_interface.h"
16007
16008 int
16009 main (void)
16010 @{
16011    /* First, elaborate the library before using it */
16012    mylibinit ();
16013
16014    /* Main program, using the library exported entities */
16015    do_something ();
16016    do_something_else ();
16017
16018    /* Library finalization at the end of the program */
16019    mylibfinal ();
16020    return 0;
16021 @}
16022 @end smallexample
16023
16024 @noindent
16025 Note that invoking any library finalization procedure generated by
16026 @code{gnatbind} shuts down the Ada run-time environment.
16027 Consequently, the
16028 finalization of all Ada libraries must be performed at the end of the program.
16029 No call to these libraries or to the Ada run-time library should be made
16030 after the finalization phase.
16031
16032 @node Restrictions in Stand-alone Libraries
16033 @subsection Restrictions in Stand-alone Libraries
16034
16035 @noindent
16036 The pragmas listed below should be used with caution inside libraries,
16037 as they can create incompatibilities with other Ada libraries:
16038 @itemize @bullet
16039 @item pragma @code{Locking_Policy}
16040 @item pragma @code{Queuing_Policy}
16041 @item pragma @code{Task_Dispatching_Policy}
16042 @item pragma @code{Unreserve_All_Interrupts}
16043 @end itemize
16044
16045 @noindent
16046 When using a library that contains such pragmas, the user must make sure
16047 that all libraries use the same pragmas with the same values. Otherwise,
16048 @code{Program_Error} will
16049 be raised during the elaboration of the conflicting
16050 libraries. The usage of these pragmas and its consequences for the user
16051 should therefore be well documented.
16052
16053 Similarly, the traceback in the exception occurrence mechanism should be
16054 enabled or disabled in a consistent manner across all libraries.
16055 Otherwise, Program_Error will be raised during the elaboration of the
16056 conflicting libraries.
16057
16058 If the @code{Version} or @code{Body_Version}
16059 attributes are used inside a library, then you need to
16060 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16061 libraries, so that version identifiers can be properly computed.
16062 In practice these attributes are rarely used, so this is unlikely
16063 to be a consideration.
16064
16065 @node  Rebuilding the GNAT Run-Time Library
16066 @section Rebuilding the GNAT Run-Time Library
16067 @cindex GNAT Run-Time Library, rebuilding
16068 @cindex Building the GNAT Run-Time Library
16069 @cindex Rebuilding the GNAT Run-Time Library
16070 @cindex Run-Time Library, rebuilding
16071
16072 @noindent
16073 It may be useful to recompile the GNAT library in various contexts, the
16074 most important one being the use of partition-wide configuration pragmas
16075 such as @code{Normalize_Scalars}. A special Makefile called
16076 @code{Makefile.adalib} is provided to that effect and can be found in
16077 the directory containing the GNAT library. The location of this
16078 directory depends on the way the GNAT environment has been installed and can
16079 be determined by means of the command:
16080
16081 @smallexample
16082 $ gnatls -v
16083 @end smallexample
16084
16085 @noindent
16086 The last entry in the object search path usually contains the
16087 gnat library. This Makefile contains its own documentation and in
16088 particular the set of instructions needed to rebuild a new library and
16089 to use it.
16090
16091 @node Using the GNU make Utility
16092 @chapter Using the GNU @code{make} Utility
16093 @findex make
16094
16095 @noindent
16096 This chapter offers some examples of makefiles that solve specific
16097 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16098 make, make, GNU @code{make}}), nor does it try to replace the
16099 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16100
16101 All the examples in this section are specific to the GNU version of
16102 make. Although @command{make} is a standard utility, and the basic language
16103 is the same, these examples use some advanced features found only in
16104 @code{GNU make}.
16105
16106 @menu
16107 * Using gnatmake in a Makefile::
16108 * Automatically Creating a List of Directories::
16109 * Generating the Command Line Switches::
16110 * Overcoming Command Line Length Limits::
16111 @end menu
16112
16113 @node Using gnatmake in a Makefile
16114 @section Using gnatmake in a Makefile
16115 @findex makefile
16116 @cindex GNU make
16117
16118 @noindent
16119 Complex project organizations can be handled in a very powerful way by
16120 using GNU make combined with gnatmake. For instance, here is a Makefile
16121 which allows you to build each subsystem of a big project into a separate
16122 shared library. Such a makefile allows you to significantly reduce the link
16123 time of very big applications while maintaining full coherence at
16124 each step of the build process.
16125
16126 The list of dependencies are handled automatically by
16127 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16128 the appropriate directories.
16129
16130 Note that you should also read the example on how to automatically
16131 create the list of directories
16132 (@pxref{Automatically Creating a List of Directories})
16133 which might help you in case your project has a lot of subdirectories.
16134
16135 @smallexample
16136 @iftex
16137 @leftskip=0cm
16138 @font@heightrm=cmr8
16139 @heightrm
16140 @end iftex
16141 ## This Makefile is intended to be used with the following directory
16142 ## configuration:
16143 ##  - The sources are split into a series of csc (computer software components)
16144 ##    Each of these csc is put in its own directory.
16145 ##    Their name are referenced by the directory names.
16146 ##    They will be compiled into shared library (although this would also work
16147 ##    with static libraries
16148 ##  - The main program (and possibly other packages that do not belong to any
16149 ##    csc is put in the top level directory (where the Makefile is).
16150 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16151 ##                    \_ second_csc (sources) __ lib (will contain the library)
16152 ##                    \_ @dots{}
16153 ## Although this Makefile is build for shared library, it is easy to modify
16154 ## to build partial link objects instead (modify the lines with -shared and
16155 ## gnatlink below)
16156 ##
16157 ## With this makefile, you can change any file in the system or add any new
16158 ## file, and everything will be recompiled correctly (only the relevant shared
16159 ## objects will be recompiled, and the main program will be re-linked).
16160
16161 # The list of computer software component for your project. This might be
16162 # generated automatically.
16163 CSC_LIST=aa bb cc
16164
16165 # Name of the main program (no extension)
16166 MAIN=main
16167
16168 # If we need to build objects with -fPIC, uncomment the following line
16169 #NEED_FPIC=-fPIC
16170
16171 # The following variable should give the directory containing libgnat.so
16172 # You can get this directory through 'gnatls -v'. This is usually the last
16173 # directory in the Object_Path.
16174 GLIB=@dots{}
16175
16176 # The directories for the libraries
16177 # (This macro expands the list of CSC to the list of shared libraries, you
16178 # could simply use the expanded form:
16179 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16180 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16181
16182 $@{MAIN@}: objects $@{LIB_DIR@}
16183     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16184     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16185
16186 objects::
16187     # recompile the sources
16188     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16189
16190 # Note: In a future version of GNAT, the following commands will be simplified
16191 # by a new tool, gnatmlib
16192 $@{LIB_DIR@}:
16193     mkdir -p $@{dir $@@ @}
16194     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16195     cd $@{dir $@@ @} && cp -f ../*.ali .
16196
16197 # The dependencies for the modules
16198 # Note that we have to force the expansion of *.o, since in some cases
16199 # make won't be able to do it itself.
16200 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16201 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16202 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16203
16204 # Make sure all of the shared libraries are in the path before starting the
16205 # program
16206 run::
16207     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16208
16209 clean::
16210     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16211     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16212     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16213     $@{RM@} *.o *.ali $@{MAIN@}
16214 @end smallexample
16215
16216 @node Automatically Creating a List of Directories
16217 @section Automatically Creating a List of Directories
16218
16219 @noindent
16220 In most makefiles, you will have to specify a list of directories, and
16221 store it in a variable. For small projects, it is often easier to
16222 specify each of them by hand, since you then have full control over what
16223 is the proper order for these directories, which ones should be
16224 included.
16225
16226 However, in larger projects, which might involve hundreds of
16227 subdirectories, it might be more convenient to generate this list
16228 automatically.
16229
16230 The example below presents two methods. The first one, although less
16231 general, gives you more control over the list. It involves wildcard
16232 characters, that are automatically expanded by @command{make}. Its
16233 shortcoming is that you need to explicitly specify some of the
16234 organization of your project, such as for instance the directory tree
16235 depth, whether some directories are found in a separate tree, @enddots{}
16236
16237 The second method is the most general one. It requires an external
16238 program, called @command{find}, which is standard on all Unix systems. All
16239 the directories found under a given root directory will be added to the
16240 list.
16241
16242 @smallexample
16243 @iftex
16244 @leftskip=0cm
16245 @font@heightrm=cmr8
16246 @heightrm
16247 @end iftex
16248 # The examples below are based on the following directory hierarchy:
16249 # All the directories can contain any number of files
16250 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16251 #                       ->  ab
16252 #                       ->  ac
16253 #                ->  b  ->  ba  ->  baa
16254 #                       ->  bb
16255 #                       ->  bc
16256 # This Makefile creates a variable called DIRS, that can be reused any time
16257 # you need this list (see the other examples in this section)
16258
16259 # The root of your project's directory hierarchy
16260 ROOT_DIRECTORY=.
16261
16262 ####
16263 # First method: specify explicitly the list of directories
16264 # This allows you to specify any subset of all the directories you need.
16265 ####
16266
16267 DIRS := a/aa/ a/ab/ b/ba/
16268
16269 ####
16270 # Second method: use wildcards
16271 # Note that the argument(s) to wildcard below should end with a '/'.
16272 # Since wildcards also return file names, we have to filter them out
16273 # to avoid duplicate directory names.
16274 # We thus use make's @code{dir} and @code{sort} functions.
16275 # It sets DIRs to the following value (note that the directories aaa and baa
16276 # are not given, unless you change the arguments to wildcard).
16277 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16278 ####
16279
16280 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16281                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16282
16283 ####
16284 # Third method: use an external program
16285 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16286 # This is the most complete command: it sets DIRs to the following value:
16287 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16288 ####
16289
16290 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16291
16292 @end smallexample
16293
16294 @node Generating the Command Line Switches
16295 @section Generating the Command Line Switches
16296
16297 @noindent
16298 Once you have created the list of directories as explained in the
16299 previous section (@pxref{Automatically Creating a List of Directories}),
16300 you can easily generate the command line arguments to pass to gnatmake.
16301
16302 For the sake of completeness, this example assumes that the source path
16303 is not the same as the object path, and that you have two separate lists
16304 of directories.
16305
16306 @smallexample
16307 # see "Automatically creating a list of directories" to create
16308 # these variables
16309 SOURCE_DIRS=
16310 OBJECT_DIRS=
16311
16312 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16313 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16314
16315 all:
16316         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16317 @end smallexample
16318
16319 @node Overcoming Command Line Length Limits
16320 @section Overcoming Command Line Length Limits
16321
16322 @noindent
16323 One problem that might be encountered on big projects is that many
16324 operating systems limit the length of the command line. It is thus hard to give
16325 gnatmake the list of source and object directories.
16326
16327 This example shows how you can set up environment variables, which will
16328 make @command{gnatmake} behave exactly as if the directories had been
16329 specified on the command line, but have a much higher length limit (or
16330 even none on most systems).
16331
16332 It assumes that you have created a list of directories in your Makefile,
16333 using one of the methods presented in
16334 @ref{Automatically Creating a List of Directories}.
16335 For the sake of completeness, we assume that the object
16336 path (where the ALI files are found) is different from the sources patch.
16337
16338 Note a small trick in the Makefile below: for efficiency reasons, we
16339 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16340 expanded immediately by @code{make}. This way we overcome the standard
16341 make behavior which is to expand the variables only when they are
16342 actually used.
16343
16344 On Windows, if you are using the standard Windows command shell, you must
16345 replace colons with semicolons in the assignments to these variables.
16346
16347 @smallexample
16348 @iftex
16349 @leftskip=0cm
16350 @font@heightrm=cmr8
16351 @heightrm
16352 @end iftex
16353 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16354 # This is the same thing as putting the -I arguments on the command line.
16355 # (the equivalent of using -aI on the command line would be to define
16356 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16357 # You can of course have different values for these variables.
16358 #
16359 # Note also that we need to keep the previous values of these variables, since
16360 # they might have been set before running 'make' to specify where the GNAT
16361 # library is installed.
16362
16363 # see "Automatically creating a list of directories" to create these
16364 # variables
16365 SOURCE_DIRS=
16366 OBJECT_DIRS=
16367
16368 empty:=
16369 space:=$@{empty@} $@{empty@}
16370 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16371 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16372 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16373 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16374 export ADA_INCLUDE_PATH
16375 export ADA_OBJECT_PATH
16376
16377 all:
16378         gnatmake main_unit
16379 @end smallexample
16380 @end ifclear
16381
16382 @node Memory Management Issues
16383 @chapter Memory Management Issues
16384
16385 @noindent
16386 This chapter describes some useful memory pools provided in the GNAT library
16387 and in particular the GNAT Debug Pool facility, which can be used to detect
16388 incorrect uses of access values (including ``dangling references'').
16389 @ifclear vms
16390 It also describes the @command{gnatmem} tool, which can be used to track down
16391 ``memory leaks''.
16392 @end ifclear
16393
16394 @menu
16395 * Some Useful Memory Pools::
16396 * The GNAT Debug Pool Facility::
16397 @ifclear vms
16398 * The gnatmem Tool::
16399 @end ifclear
16400 @end menu
16401
16402 @node Some Useful Memory Pools
16403 @section Some Useful Memory Pools
16404 @findex Memory Pool
16405 @cindex storage, pool
16406
16407 @noindent
16408 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16409 storage pool. Allocations use the standard system call @code{malloc} while
16410 deallocations use the standard system call @code{free}. No reclamation is
16411 performed when the pool goes out of scope. For performance reasons, the
16412 standard default Ada allocators/deallocators do not use any explicit storage
16413 pools but if they did, they could use this storage pool without any change in
16414 behavior. That is why this storage pool is used  when the user
16415 manages to make the default implicit allocator explicit as in this example:
16416 @smallexample @c ada
16417    type T1 is access Something;
16418     -- no Storage pool is defined for T2
16419    type T2 is access Something_Else;
16420    for T2'Storage_Pool use T1'Storage_Pool;
16421    -- the above is equivalent to
16422    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16423 @end smallexample
16424
16425 @noindent
16426 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16427 pool. The allocation strategy is similar to @code{Pool_Local}'s
16428 except that the all
16429 storage allocated with this pool is reclaimed when the pool object goes out of
16430 scope. This pool provides a explicit mechanism similar to the implicit one
16431 provided by several Ada 83 compilers for allocations performed through a local
16432 access type and whose purpose was to reclaim memory when exiting the
16433 scope of a given local access. As an example, the following program does not
16434 leak memory even though it does not perform explicit deallocation:
16435
16436 @smallexample @c ada
16437 with System.Pool_Local;
16438 procedure Pooloc1 is
16439    procedure Internal is
16440       type A is access Integer;
16441       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16442       for A'Storage_Pool use X;
16443       v : A;
16444    begin
16445       for I in  1 .. 50 loop
16446          v := new Integer;
16447       end loop;
16448    end Internal;
16449 begin
16450    for I in  1 .. 100 loop
16451       Internal;
16452    end loop;
16453 end Pooloc1;
16454 @end smallexample
16455
16456 @noindent
16457 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16458 @code{Storage_Size} is specified for an access type.
16459 The whole storage for the pool is
16460 allocated at once, usually on the stack at the point where the access type is
16461 elaborated. It is automatically reclaimed when exiting the scope where the
16462 access type is defined. This package is not intended to be used directly by the
16463 user and it is implicitly used for each such declaration:
16464
16465 @smallexample @c ada
16466    type T1 is access Something;
16467    for T1'Storage_Size use 10_000;
16468 @end smallexample
16469
16470 @node The GNAT Debug Pool Facility
16471 @section The GNAT Debug Pool Facility
16472 @findex Debug Pool
16473 @cindex storage, pool, memory corruption
16474
16475 @noindent
16476 The use of unchecked deallocation and unchecked conversion can easily
16477 lead to incorrect memory references. The problems generated by such
16478 references are usually difficult to tackle because the symptoms can be
16479 very remote from the origin of the problem. In such cases, it is
16480 very helpful to detect the problem as early as possible. This is the
16481 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16482
16483 In order to use the GNAT specific debugging pool, the user must
16484 associate a debug pool object with each of the access types that may be
16485 related to suspected memory problems. See Ada Reference Manual 13.11.
16486 @smallexample @c ada
16487 type Ptr is access Some_Type;
16488 Pool : GNAT.Debug_Pools.Debug_Pool;
16489 for Ptr'Storage_Pool use Pool;
16490 @end smallexample
16491
16492 @noindent
16493 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16494 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16495 allow the user to redefine allocation and deallocation strategies. They
16496 also provide a checkpoint for each dereference, through the use of
16497 the primitive operation @code{Dereference} which is implicitly called at
16498 each dereference of an access value.
16499
16500 Once an access type has been associated with a debug pool, operations on
16501 values of the type may raise four distinct exceptions,
16502 which correspond to four potential kinds of memory corruption:
16503 @itemize @bullet
16504 @item
16505 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16506 @item
16507 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16508 @item
16509 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16510 @item
16511 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16512 @end itemize
16513
16514 @noindent
16515 For types associated with a Debug_Pool, dynamic allocation is performed using
16516 the standard GNAT allocation routine. References to all allocated chunks of
16517 memory are kept in an internal dictionary. Several deallocation strategies are
16518 provided, whereupon the user can choose to release the memory to the system,
16519 keep it allocated for further invalid access checks, or fill it with an easily
16520 recognizable pattern for debug sessions. The memory pattern is the old IBM
16521 hexadecimal convention: @code{16#DEADBEEF#}.
16522
16523 See the documentation in the file g-debpoo.ads for more information on the
16524 various strategies.
16525
16526 Upon each dereference, a check is made that the access value denotes a
16527 properly allocated memory location. Here is a complete example of use of
16528 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16529 @smallexample @c ada
16530 @iftex
16531 @leftskip=0cm
16532 @end iftex
16533 with Gnat.Io; use Gnat.Io;
16534 with Unchecked_Deallocation;
16535 with Unchecked_Conversion;
16536 with GNAT.Debug_Pools;
16537 with System.Storage_Elements;
16538 with Ada.Exceptions; use Ada.Exceptions;
16539 procedure Debug_Pool_Test is
16540
16541    type T is access Integer;
16542    type U is access all T;
16543
16544    P : GNAT.Debug_Pools.Debug_Pool;
16545    for T'Storage_Pool use P;
16546
16547    procedure Free is new Unchecked_Deallocation (Integer, T);
16548    function UC is new Unchecked_Conversion (U, T);
16549    A, B : aliased T;
16550
16551    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16552
16553 begin
16554    Info (P);
16555    A := new Integer;
16556    B := new Integer;
16557    B := A;
16558    Info (P);
16559    Free (A);
16560    begin
16561       Put_Line (Integer'Image(B.all));
16562    exception
16563       when E : others => Put_Line ("raised: " & Exception_Name (E));
16564    end;
16565    begin
16566       Free (B);
16567    exception
16568       when E : others => Put_Line ("raised: " & Exception_Name (E));
16569    end;
16570    B := UC(A'Access);
16571    begin
16572       Put_Line (Integer'Image(B.all));
16573    exception
16574       when E : others => Put_Line ("raised: " & Exception_Name (E));
16575    end;
16576    begin
16577       Free (B);
16578    exception
16579       when E : others => Put_Line ("raised: " & Exception_Name (E));
16580    end;
16581    Info (P);
16582 end Debug_Pool_Test;
16583 @end smallexample
16584
16585 @noindent
16586 The debug pool mechanism provides the following precise diagnostics on the
16587 execution of this erroneous program:
16588 @smallexample
16589 Debug Pool info:
16590   Total allocated bytes :  0
16591   Total deallocated bytes :  0
16592   Current Water Mark:  0
16593   High Water Mark:  0
16594
16595 Debug Pool info:
16596   Total allocated bytes :  8
16597   Total deallocated bytes :  0
16598   Current Water Mark:  8
16599   High Water Mark:  8
16600
16601 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16602 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16603 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16604 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16605 Debug Pool info:
16606   Total allocated bytes :  8
16607   Total deallocated bytes :  4
16608   Current Water Mark:  4
16609   High Water Mark:  8
16610 @end smallexample
16611
16612 @ifclear vms
16613 @node The gnatmem Tool
16614 @section The @command{gnatmem} Tool
16615 @findex gnatmem
16616
16617 @noindent
16618 The @code{gnatmem} utility monitors dynamic allocation and
16619 deallocation activity in a program, and displays information about
16620 incorrect deallocations and possible sources of memory leaks.
16621 It is designed to work in association with a static runtime library
16622 only and in this context provides three types of information:
16623 @itemize @bullet
16624 @item
16625 General information concerning memory management, such as the total
16626 number of allocations and deallocations, the amount of allocated
16627 memory and the high water mark, i.e.@: the largest amount of allocated
16628 memory in the course of program execution.
16629
16630 @item
16631 Backtraces for all incorrect deallocations, that is to say deallocations
16632 which do not correspond to a valid allocation.
16633
16634 @item
16635 Information on each allocation that is potentially the origin of a memory
16636 leak.
16637 @end itemize
16638
16639 @menu
16640 * Running gnatmem::
16641 * Switches for gnatmem::
16642 * Example of gnatmem Usage::
16643 @end menu
16644
16645 @node Running gnatmem
16646 @subsection Running @code{gnatmem}
16647
16648 @noindent
16649 @code{gnatmem} makes use of the output created by the special version of
16650 allocation and deallocation routines that record call information. This
16651 allows to obtain accurate dynamic memory usage history at a minimal cost to
16652 the execution speed. Note however, that @code{gnatmem} is not supported on
16653 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16654 Solaris and Windows NT/2000/XP (x86).
16655
16656 @noindent
16657 The @code{gnatmem} command has the form
16658
16659 @smallexample
16660 @c    $ gnatmem @ovar{switches} user_program
16661 @c Expanding @ovar macro inline (explanation in macro def comments)
16662       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16663 @end smallexample
16664
16665 @noindent
16666 The program must have been linked with the instrumented version of the
16667 allocation and deallocation routines. This is done by linking with the
16668 @file{libgmem.a} library. For correct symbolic backtrace information,
16669 the user program should be compiled with debugging options
16670 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16671
16672 @smallexample
16673 $ gnatmake -g my_program -largs -lgmem
16674 @end smallexample
16675
16676 @noindent
16677 As library @file{libgmem.a} contains an alternate body for package
16678 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16679 when an executable is linked with library @file{libgmem.a}. It is then not
16680 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16681
16682 @noindent
16683 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16684 This file contains information about all allocations and deallocations
16685 performed by the program. It is produced by the instrumented allocations and
16686 deallocations routines and will be used by @code{gnatmem}.
16687
16688 In order to produce symbolic backtrace information for allocations and
16689 deallocations performed by the GNAT run-time library, you need to use a
16690 version of that library that has been compiled with the @option{-g} switch
16691 (see @ref{Rebuilding the GNAT Run-Time Library}).
16692
16693 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16694 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16695 @option{-i} switch, gnatmem will assume that this file can be found in the
16696 current directory. For example, after you have executed @file{my_program},
16697 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16698
16699 @smallexample
16700 $ gnatmem my_program
16701 @end smallexample
16702
16703 @noindent
16704 This will produce the output with the following format:
16705
16706 *************** debut cc
16707 @smallexample
16708 $ gnatmem my_program
16709
16710 Global information
16711 ------------------
16712    Total number of allocations        :  45
16713    Total number of deallocations      :   6
16714    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16715    High Water Mark                    :  11.40 Kilobytes
16716
16717 .
16718 .
16719 .
16720 Allocation Root # 2
16721 -------------------
16722  Number of non freed allocations    :  11
16723  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16724  High Water Mark                    :   1.27 Kilobytes
16725  Backtrace                          :
16726    my_program.adb:23 my_program.alloc
16727 .
16728 .
16729 .
16730 @end smallexample
16731
16732 The first block of output gives general information. In this case, the
16733 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16734 Unchecked_Deallocation routine occurred.
16735
16736 @noindent
16737 Subsequent paragraphs display  information on all allocation roots.
16738 An allocation root is a specific point in the execution of the program
16739 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16740 construct. This root is represented by an execution backtrace (or subprogram
16741 call stack). By default the backtrace depth for allocations roots is 1, so
16742 that a root corresponds exactly to a source location. The backtrace can
16743 be made deeper, to make the root more specific.
16744
16745 @node Switches for gnatmem
16746 @subsection Switches for @code{gnatmem}
16747
16748 @noindent
16749 @code{gnatmem} recognizes the following switches:
16750
16751 @table @option
16752
16753 @item -q
16754 @cindex @option{-q} (@code{gnatmem})
16755 Quiet. Gives the minimum output needed to identify the origin of the
16756 memory leaks. Omits statistical information.
16757
16758 @item @var{N}
16759 @cindex @var{N} (@code{gnatmem})
16760 N is an integer literal (usually between 1 and 10) which controls the
16761 depth of the backtraces defining allocation root. The default value for
16762 N is 1. The deeper the backtrace, the more precise the localization of
16763 the root. Note that the total number of roots can depend on this
16764 parameter. This parameter must be specified @emph{before} the name of the
16765 executable to be analyzed, to avoid ambiguity.
16766
16767 @item -b n
16768 @cindex @option{-b} (@code{gnatmem})
16769 This switch has the same effect as just depth parameter.
16770
16771 @item -i @var{file}
16772 @cindex @option{-i} (@code{gnatmem})
16773 Do the @code{gnatmem} processing starting from @file{file}, rather than
16774 @file{gmem.out} in the current directory.
16775
16776 @item -m n
16777 @cindex @option{-m} (@code{gnatmem})
16778 This switch causes @code{gnatmem} to mask the allocation roots that have less
16779 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16780 examine even the roots that didn't result in leaks.
16781
16782 @item -s order
16783 @cindex @option{-s} (@code{gnatmem})
16784 This switch causes @code{gnatmem} to sort the allocation roots according to the
16785 specified order of sort criteria, each identified by a single letter. The
16786 currently supported criteria are @code{n, h, w} standing respectively for
16787 number of unfreed allocations, high watermark, and final watermark
16788 corresponding to a specific root. The default order is @code{nwh}.
16789
16790 @end table
16791
16792 @node Example of gnatmem Usage
16793 @subsection Example of @code{gnatmem} Usage
16794
16795 @noindent
16796 The following example shows the use of @code{gnatmem}
16797 on a simple memory-leaking program.
16798 Suppose that we have the following Ada program:
16799
16800 @smallexample @c ada
16801 @group
16802 @cartouche
16803 with Unchecked_Deallocation;
16804 procedure Test_Gm is
16805
16806    type T is array (1..1000) of Integer;
16807    type Ptr is access T;
16808    procedure Free is new Unchecked_Deallocation (T, Ptr);
16809    A : Ptr;
16810
16811    procedure My_Alloc is
16812    begin
16813       A := new T;
16814    end My_Alloc;
16815
16816    procedure My_DeAlloc is
16817       B : Ptr := A;
16818    begin
16819       Free (B);
16820    end My_DeAlloc;
16821
16822 begin
16823    My_Alloc;
16824    for I in 1 .. 5 loop
16825       for J in I .. 5 loop
16826          My_Alloc;
16827       end loop;
16828       My_Dealloc;
16829    end loop;
16830 end;
16831 @end cartouche
16832 @end group
16833 @end smallexample
16834
16835 @noindent
16836 The program needs to be compiled with debugging option and linked with
16837 @code{gmem} library:
16838
16839 @smallexample
16840 $ gnatmake -g test_gm -largs -lgmem
16841 @end smallexample
16842
16843 @noindent
16844 Then we execute the program as usual:
16845
16846 @smallexample
16847 $ test_gm
16848 @end smallexample
16849
16850 @noindent
16851 Then @code{gnatmem} is invoked simply with
16852 @smallexample
16853 $ gnatmem test_gm
16854 @end smallexample
16855
16856 @noindent
16857 which produces the following output (result may vary on different platforms):
16858
16859 @smallexample
16860 Global information
16861 ------------------
16862    Total number of allocations        :  18
16863    Total number of deallocations      :   5
16864    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16865    High Water Mark                    :  56.90 Kilobytes
16866
16867 Allocation Root # 1
16868 -------------------
16869  Number of non freed allocations    :  11
16870  Final Water Mark (non freed mem)   :  42.97 Kilobytes
16871  High Water Mark                    :  46.88 Kilobytes
16872  Backtrace                          :
16873    test_gm.adb:11 test_gm.my_alloc
16874
16875 Allocation Root # 2
16876 -------------------
16877  Number of non freed allocations    :   1
16878  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16879  High Water Mark                    :  10.02 Kilobytes
16880  Backtrace                          :
16881    s-secsta.adb:81 system.secondary_stack.ss_init
16882
16883 Allocation Root # 3
16884 -------------------
16885  Number of non freed allocations    :   1
16886  Final Water Mark (non freed mem)   :  12 Bytes
16887  High Water Mark                    :  12 Bytes
16888  Backtrace                          :
16889    s-secsta.adb:181 system.secondary_stack.ss_init
16890 @end smallexample
16891
16892 @noindent
16893 Note that the GNAT run time contains itself a certain number of
16894 allocations that have no  corresponding deallocation,
16895 as shown here for root #2 and root
16896 #3. This is a normal behavior when the number of non-freed allocations
16897 is one, it allocates dynamic data structures that the run time needs for
16898 the complete lifetime of the program. Note also that there is only one
16899 allocation root in the user program with a single line back trace:
16900 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16901 program shows that 'My_Alloc' is called at 2 different points in the
16902 source (line 21 and line 24). If those two allocation roots need to be
16903 distinguished, the backtrace depth parameter can be used:
16904
16905 @smallexample
16906 $ gnatmem 3 test_gm
16907 @end smallexample
16908
16909 @noindent
16910 which will give the following output:
16911
16912 @smallexample
16913 Global information
16914 ------------------
16915    Total number of allocations        :  18
16916    Total number of deallocations      :   5
16917    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16918    High Water Mark                    :  56.90 Kilobytes
16919
16920 Allocation Root # 1
16921 -------------------
16922  Number of non freed allocations    :  10
16923  Final Water Mark (non freed mem)   :  39.06 Kilobytes
16924  High Water Mark                    :  42.97 Kilobytes
16925  Backtrace                          :
16926    test_gm.adb:11 test_gm.my_alloc
16927    test_gm.adb:24 test_gm
16928    b_test_gm.c:52 main
16929
16930 Allocation Root # 2
16931 -------------------
16932  Number of non freed allocations    :   1
16933  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16934  High Water Mark                    :  10.02 Kilobytes
16935  Backtrace                          :
16936    s-secsta.adb:81  system.secondary_stack.ss_init
16937    s-secsta.adb:283 <system__secondary_stack___elabb>
16938    b_test_gm.c:33   adainit
16939
16940 Allocation Root # 3
16941 -------------------
16942  Number of non freed allocations    :   1
16943  Final Water Mark (non freed mem)   :   3.91 Kilobytes
16944  High Water Mark                    :   3.91 Kilobytes
16945  Backtrace                          :
16946    test_gm.adb:11 test_gm.my_alloc
16947    test_gm.adb:21 test_gm
16948    b_test_gm.c:52 main
16949
16950 Allocation Root # 4
16951 -------------------
16952  Number of non freed allocations    :   1
16953  Final Water Mark (non freed mem)   :  12 Bytes
16954  High Water Mark                    :  12 Bytes
16955  Backtrace                          :
16956    s-secsta.adb:181 system.secondary_stack.ss_init
16957    s-secsta.adb:283 <system__secondary_stack___elabb>
16958    b_test_gm.c:33   adainit
16959 @end smallexample
16960
16961 @noindent
16962 The allocation root #1 of the first example has been split in 2 roots #1
16963 and #3 thanks to the more precise associated backtrace.
16964
16965 @end ifclear
16966
16967 @node Stack Related Facilities
16968 @chapter Stack Related Facilities
16969
16970 @noindent
16971 This chapter describes some useful tools associated with stack
16972 checking and analysis. In
16973 particular, it deals with dynamic and static stack usage measurements.
16974
16975 @menu
16976 * Stack Overflow Checking::
16977 * Static Stack Usage Analysis::
16978 * Dynamic Stack Usage Analysis::
16979 @end menu
16980
16981 @node Stack Overflow Checking
16982 @section Stack Overflow Checking
16983 @cindex Stack Overflow Checking
16984 @cindex -fstack-check
16985
16986 @noindent
16987 For most operating systems, @command{gcc} does not perform stack overflow
16988 checking by default. This means that if the main environment task or
16989 some other task exceeds the available stack space, then unpredictable
16990 behavior will occur. Most native systems offer some level of protection by
16991 adding a guard page at the end of each task stack. This mechanism is usually
16992 not enough for dealing properly with stack overflow situations because
16993 a large local variable could ``jump'' above the guard page.
16994 Furthermore, when the
16995 guard page is hit, there may not be any space left on the stack for executing
16996 the exception propagation code. Enabling stack checking avoids
16997 such situations.
16998
16999 To activate stack checking, compile all units with the gcc option
17000 @option{-fstack-check}. For example:
17001
17002 @smallexample
17003 gcc -c -fstack-check package1.adb
17004 @end smallexample
17005
17006 @noindent
17007 Units compiled with this option will generate extra instructions to check
17008 that any use of the stack (for procedure calls or for declaring local
17009 variables in declare blocks) does not exceed the available stack space.
17010 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17011
17012 For declared tasks, the stack size is controlled by the size
17013 given in an applicable @code{Storage_Size} pragma or by the value specified
17014 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17015 the default size as defined in the GNAT runtime otherwise.
17016
17017 For the environment task, the stack size depends on
17018 system defaults and is unknown to the compiler. Stack checking
17019 may still work correctly if a fixed
17020 size stack is allocated, but this cannot be guaranteed.
17021 @ifclear vms
17022 To ensure that a clean exception is signalled for stack
17023 overflow, set the environment variable
17024 @env{GNAT_STACK_LIMIT} to indicate the maximum
17025 stack area that can be used, as in:
17026 @cindex GNAT_STACK_LIMIT
17027
17028 @smallexample
17029 SET GNAT_STACK_LIMIT 1600
17030 @end smallexample
17031
17032 @noindent
17033 The limit is given in kilobytes, so the above declaration would
17034 set the stack limit of the environment task to 1.6 megabytes.
17035 Note that the only purpose of this usage is to limit the amount
17036 of stack used by the environment task. If it is necessary to
17037 increase the amount of stack for the environment task, then this
17038 is an operating systems issue, and must be addressed with the
17039 appropriate operating systems commands.
17040 @end ifclear
17041 @ifset vms
17042 To have a fixed size stack in the environment task, the stack must be put
17043 in the P0 address space and its size specified.  Use these switches to
17044 create a p0 image:
17045
17046 @smallexample
17047 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17048 @end smallexample
17049
17050 @noindent
17051 The quotes are required to keep case.  The number after @samp{STACK=} is the
17052 size of the environmental task stack in pagelets (512 bytes).  In this example
17053 the stack size is about 2 megabytes.
17054
17055 @noindent
17056 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17057 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17058 more details about the @option{/p0image} qualifier and the @option{stack}
17059 option.
17060 @end ifset
17061
17062 @node Static Stack Usage Analysis
17063 @section Static Stack Usage Analysis
17064 @cindex Static Stack Usage Analysis
17065 @cindex -fstack-usage
17066
17067 @noindent
17068 A unit compiled with @option{-fstack-usage} will generate an extra file
17069 that specifies
17070 the maximum amount of stack used, on a per-function basis.
17071 The file has the same
17072 basename as the target object file with a @file{.su} extension.
17073 Each line of this file is made up of three fields:
17074
17075 @itemize
17076 @item
17077 The name of the function.
17078 @item
17079 A number of bytes.
17080 @item
17081 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17082 @end itemize
17083
17084 The second field corresponds to the size of the known part of the function
17085 frame.
17086
17087 The qualifier @code{static} means that the function frame size
17088 is purely static.
17089 It usually means that all local variables have a static size.
17090 In this case, the second field is a reliable measure of the function stack
17091 utilization.
17092
17093 The qualifier @code{dynamic} means that the function frame size is not static.
17094 It happens mainly when some local variables have a dynamic size. When this
17095 qualifier appears alone, the second field is not a reliable measure
17096 of the function stack analysis. When it is qualified with  @code{bounded}, it
17097 means that the second field is a reliable maximum of the function stack
17098 utilization.
17099
17100 @node Dynamic Stack Usage Analysis
17101 @section Dynamic Stack Usage Analysis
17102
17103 @noindent
17104 It is possible to measure the maximum amount of stack used by a task, by
17105 adding a switch to @command{gnatbind}, as:
17106
17107 @smallexample
17108 $ gnatbind -u0 file
17109 @end smallexample
17110
17111 @noindent
17112 With this option, at each task termination, its stack usage is  output on
17113 @file{stderr}.
17114 It is not always convenient to output the stack usage when the program
17115 is still running. Hence, it is possible to delay this output until program
17116 termination. for a given number of tasks specified as the argument of the
17117 @option{-u} option. For instance:
17118
17119 @smallexample
17120 $ gnatbind -u100 file
17121 @end smallexample
17122
17123 @noindent
17124 will buffer the stack usage information of the first 100 tasks to terminate and
17125 output this info at program termination. Results are displayed in four
17126 columns:
17127
17128 @noindent
17129 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17130
17131 @noindent
17132 where:
17133
17134 @table @emph
17135 @item Index
17136 is a number associated with each task.
17137
17138 @item Task Name
17139 is the name of the task analyzed.
17140
17141 @item Stack Size
17142 is the maximum size for the stack.
17143
17144 @item Stack Usage
17145 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17146 is not entirely analyzed, and it's not possible to know exactly how
17147 much has actually been used. The report thus contains the theoretical stack usage
17148 (Value) and the possible variation (Variation) around this value.
17149
17150 @end table
17151
17152 @noindent
17153 The environment task stack, e.g., the stack that contains the main unit, is
17154 only processed when the environment variable GNAT_STACK_LIMIT is set.
17155
17156
17157 @c *********************************
17158 @c *            GNATCHECK          *
17159 @c *********************************
17160 @node Verifying Properties Using gnatcheck
17161 @chapter Verifying Properties Using @command{gnatcheck}
17162 @findex gnatcheck
17163 @cindex @command{gnatcheck}
17164
17165 @noindent
17166 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17167 of Ada source files according to a given set of semantic rules.
17168 @cindex ASIS
17169
17170 In order to check compliance with a given rule, @command{gnatcheck} has to
17171 semantically analyze the Ada sources.
17172 Therefore, checks can only be performed on
17173 legal Ada units. Moreover, when a unit depends semantically upon units located
17174 outside the current directory, the source search path has to be provided when
17175 calling @command{gnatcheck}, either through a specified project file or
17176 through @command{gnatcheck} switches as described below.
17177
17178 A number of rules are predefined in @command{gnatcheck} and are described
17179 later in this chapter.
17180 You can also add new rules, by modifying the @command{gnatcheck} code and
17181 rebuilding the tool. In order to add a simple rule making some local checks,
17182 a small amount of straightforward ASIS-based programming is usually needed.
17183
17184 Project support for @command{gnatcheck} is provided by the GNAT
17185 driver (see @ref{The GNAT Driver and Project Files}).
17186
17187 Invoking @command{gnatcheck} on the command line has the form:
17188
17189 @smallexample
17190 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
17191 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17192 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17193 @c Expanding @ovar macro inline (explanation in macro def comments)
17194 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
17195       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17196       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17197 @end smallexample
17198
17199 @noindent
17200 where
17201 @itemize @bullet
17202 @item
17203 @var{switches} specify the general tool options
17204
17205 @item
17206 Each @var{filename} is the name (including the extension) of a source
17207 file to process. ``Wildcards'' are allowed, and
17208 the file name may contain path information.
17209
17210 @item
17211 Each @var{arg_list_filename} is the name (including the extension) of a text
17212 file containing the names of the source files to process, separated by spaces
17213 or line breaks.
17214
17215 @item
17216 @var{gcc_switches} is a list of switches for
17217 @command{gcc}. They will be passed on to all compiler invocations made by
17218 @command{gnatcheck} to generate the ASIS trees. Here you can provide
17219 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17220 and use the @option{-gnatec} switch to set the configuration file.
17221
17222 @item
17223 @var{rule_options} is a list of options for controlling a set of
17224 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
17225 @end itemize
17226
17227 @noindent
17228 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
17229 supplied.
17230
17231 @menu
17232 * Format of the Report File::
17233 * General gnatcheck Switches::
17234 * gnatcheck Rule Options::
17235 * Adding the Results of Compiler Checks to gnatcheck Output::
17236 * Project-Wide Checks::
17237 * Rule exemption::
17238 * Predefined Rules::
17239 * Example of gnatcheck Usage::
17240 @end menu
17241
17242 @node Format of the Report File
17243 @section Format of the Report File
17244 @cindex Report file (for @code{gnatcheck})
17245
17246 @noindent
17247 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
17248 rule violations.
17249 It also creates a text file  that
17250 contains the complete report of the last gnatcheck run. By default this file
17251 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
17252 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
17253 name and/or location of the report file. This report contains:
17254 @itemize @bullet
17255 @item date and time of @command{gnatcheck} run, the version of
17256 the tool that has generated this report and the full parameters
17257 of the  @command{gnatcheck} invocation;
17258 @item list of enabled rules;
17259 @item total number of detected violations;
17260 @item list of source files where rule violations have been detected;
17261 @item list of source files where no violations have been detected.
17262 @end itemize
17263
17264 @node General gnatcheck Switches
17265 @section General @command{gnatcheck} Switches
17266
17267 @noindent
17268 The following switches control the general @command{gnatcheck} behavior
17269
17270 @table @option
17271 @c !sort!
17272 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
17273 @item ^-a^/ALL^
17274 Process all units including those with read-only ALI files such as
17275 those from the GNAT Run-Time library.
17276
17277 @ifclear vms
17278 @ignore
17279 @cindex @option{-d} (@command{gnatcheck})
17280 @item -d
17281 Debug mode
17282 @end ignore
17283
17284 @cindex @option{-dd} (@command{gnatcheck})
17285 @item -dd
17286 Progress indicator mode (for use in GPS).
17287 @end ifclear
17288
17289 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
17290 @item ^-h^/HELP^
17291 List the predefined and user-defined rules. For more details see
17292 @ref{Predefined Rules}.
17293
17294 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
17295 @item ^-l^/LOCS^
17296 Use full source locations references in the report file. For a construct from
17297 a generic instantiation a full source location is a chain from the location
17298 of this construct in the generic unit to the place where this unit is
17299 instantiated.
17300
17301 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
17302 @item ^-log^/LOG^
17303 Duplicate all the output sent to @file{stderr} into a log file. The log file
17304 is named @file{gnatcheck.log} and is located in the current directory.
17305
17306 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
17307 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
17308 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
17309 the range 0@dots{}1000;
17310 the default value is 500. Zero means that there is no limitation on
17311 the number of diagnostic messages to be output.
17312
17313 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
17314 @item ^-q^/QUIET^
17315 Quiet mode. All the diagnostics about rule violations are placed in the
17316 @command{gnatcheck} report file only, without duplication on @file{stdout}.
17317
17318 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
17319 @item ^-s^/SHORT^
17320 Short format of the report file (no version information, no list of applied
17321 rules, no list of checked sources is included)
17322
17323 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
17324 @item ^--include-file^/INCLUDE_FILE^
17325 Append the content of the specified text file to the report file
17326
17327 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
17328 @item ^-t^/TIME^
17329 Print out execution time.
17330
17331 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
17332 @item ^-v^/VERBOSE^
17333 Verbose mode; @command{gnatcheck} generates version information and then
17334 a trace of sources being processed.
17335
17336 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
17337 @item ^-o ^/OUTPUT=^@var{report_file}
17338 Set name of report file file to @var{report_file} .
17339
17340 @end table
17341
17342 @node gnatcheck Rule Options
17343 @section @command{gnatcheck} Rule Options
17344
17345 @noindent
17346 The following options control the processing performed by
17347 @command{gnatcheck}.
17348
17349 @table @option
17350 @cindex @option{+ALL} (@command{gnatcheck})
17351 @item +ALL
17352 Turn all the rule checks ON.
17353
17354 @cindex @option{-ALL} (@command{gnatcheck})
17355 @item -ALL
17356 Turn all the rule checks OFF.
17357
17358 @cindex @option{+R} (@command{gnatcheck})
17359 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
17360 Turn on the check for a specified rule with the specified parameter, if any.
17361 @var{rule_id} must be the identifier of one of the currently implemented rules
17362 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
17363 are not case-sensitive. The @var{param} item must
17364 be a string representing a valid parameter(s) for the specified rule.
17365 If it contains any space characters then this string must be enclosed in
17366 quotation marks.
17367
17368 @cindex @option{-R} (@command{gnatcheck})
17369 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
17370 Turn off the check for a specified rule with the specified parameter, if any.
17371
17372 @cindex @option{-from} (@command{gnatcheck})
17373 @item -from=@var{rule_option_filename}
17374 Read the rule options from the text file @var{rule_option_filename}, referred
17375 to as a ``coding standard file'' below.
17376
17377 @end table
17378
17379 @noindent
17380 The default behavior is that all the rule checks are disabled.
17381
17382 A coding standard file is a text file that contains a set of rule options
17383 described above.
17384 @cindex Coding standard file (for @code{gnatcheck})
17385 The file may contain empty lines and Ada-style comments (comment
17386 lines and end-of-line comments). There can be several rule options on a
17387 single line (separated by a space).
17388
17389 A coding standard file may reference other coding standard files by including
17390 more @option{-from=@var{rule_option_filename}}
17391 options, each such option being replaced with the content of the
17392 corresponding coding standard file during processing. In case a
17393 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
17394 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
17395 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
17396 processing fails with an error message.
17397
17398
17399 @node Adding the Results of Compiler Checks to gnatcheck Output
17400 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
17401
17402 @noindent
17403 The @command{gnatcheck} tool can include in the generated diagnostic messages
17404 and in
17405 the report file the results of the checks performed by the compiler. Though
17406 disabled by default, this effect may be obtained by using @option{+R} with
17407 the following rule identifiers and parameters:
17408
17409 @table @option
17410 @item Restrictions
17411 To record restrictions violations (which are performed by the compiler if the
17412 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
17413 use the @code{Restrictions} rule
17414 with the same parameters as pragma
17415 @code{Restrictions} or @code{Restriction_Warnings}.
17416
17417 @item Style_Checks
17418 To record compiler style checks (@pxref{Style Checking}), use the
17419 @code{Style_Checks} rule.
17420 This rule takes a parameter in one of the following forms:
17421 @itemize
17422 @item
17423 @code{All_Checks},
17424 which enables the standard style checks corresponding to the @option{-gnatyy}
17425 GNAT style check option, or
17426
17427 @item
17428 a string with the same
17429 structure and semantics as the @code{string_LITERAL} parameter of the
17430 GNAT pragma @code{Style_Checks}
17431 (for further information about this pragma,
17432 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
17433 @end itemize
17434
17435 @noindent
17436 For example, the
17437 @code{+RStyle_Checks:O} rule option activates
17438 the compiler style check that corresponds to
17439 @code{-gnatyO} style check option.
17440
17441 @item Warnings
17442 To record compiler warnings (@pxref{Warning Message Control}), use the
17443 @code{Warnings} rule with a parameter that is a valid
17444 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
17445 (for further information about this pragma,
17446 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
17447 Note that in case of gnatcheck
17448 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
17449 all the specific warnings, but not suppresses the warning mode,
17450 and 'e' parameter, corresponding to @option{-gnatwe} that means
17451 "treat warnings as errors", does not have any effect.
17452
17453 @end table
17454
17455 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
17456 option with the corresponding restriction name as a parameter. @code{-R} is
17457 not available for @code{Style_Checks} and @code{Warnings} options, to disable
17458 warnings and style checks, use the corresponding warning and style options.
17459
17460 @node Project-Wide Checks
17461 @section Project-Wide Checks
17462 @cindex Project-wide checks (for @command{gnatcheck})
17463
17464 @noindent
17465 In order to perform checks on all units of a given project, you can use
17466 the GNAT driver along with the @option{-P} option:
17467 @smallexample
17468    gnat check -Pproj -rules -from=my_rules
17469 @end smallexample
17470
17471 @noindent
17472 If the project @code{proj} depends upon other projects, you can perform
17473 checks on the project closure using the @option{-U} option:
17474 @smallexample
17475    gnat check -Pproj -U -rules -from=my_rules
17476 @end smallexample
17477
17478 @noindent
17479 Finally, if not all the units are relevant to a particular main
17480 program in the project closure, you can perform checks for the set
17481 of units needed to create a given main program (unit closure) using
17482 the @option{-U} option followed by the name of the main unit:
17483 @smallexample
17484    gnat check -Pproj -U main -rules -from=my_rules
17485 @end smallexample
17486
17487
17488 @node Rule exemption
17489 @section Rule exemption
17490 @cindex Rule exemption (for @command{gnatcheck})
17491
17492 @noindent
17493 One of the most useful applications of @command{gnatcheck} is to
17494 automate the enforcement of project-specific coding standards,
17495 for example in safety-critical systems where particular features
17496 must be restricted in order to simplify the certification effort.
17497 However, it may sometimes be appropriate to violate a coding standard rule,
17498 and in such cases the rationale for the violation should be provided
17499 in the source program itself so that the individuals
17500 reviewing or maintaining the program can immediately understand the intent.
17501
17502 The @command{gnatcheck} tool supports this practice with the notion of
17503 a ``rule exemption'' covering a specific source code section. Normally
17504 rule violation messages are issued both on @file{stderr}
17505 and in a report file. In contrast, exempted violations are not listed on
17506 @file{stderr}; thus users invoking @command{gnatcheck} interactively
17507 (e.g. in its GPS interface) do not need to pay attention to known and
17508 justified violations. However, exempted violations along with their
17509 justification are documented in a special section of the report file that
17510 @command{gnatcheck} generates.
17511
17512 @menu
17513 * Using pragma Annotate to Control Rule Exemption::
17514 * gnatcheck Annotations Rules::
17515 @end menu
17516
17517 @node Using pragma Annotate to Control Rule Exemption
17518 @subsection Using pragma @code{Annotate} to Control Rule Exemption
17519 @cindex Using pragma Annotate to control rule exemption
17520
17521 @noindent
17522 Rule exemption is controlled by pragma @code{Annotate} when its first
17523 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
17524 exemption control annotations is as follows:
17525
17526 @smallexample @c ada
17527 @group
17528 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
17529
17530 @i{exemption_control} ::= Exempt_On | Exempt_Off
17531
17532 @i{Rule_Name}         ::= string_literal
17533
17534 @i{justification}     ::= string_literal
17535 @end group
17536 @end smallexample
17537
17538 @noindent
17539 When a @command{gnatcheck} annotation has more then four arguments,
17540 @command{gnatcheck} issues a warning and ignores the additional arguments.
17541 If the additional arguments do not follow the syntax above,
17542 @command{gnatcheck} emits a warning and ignores the annotation.
17543
17544 The @i{@code{Rule_Name}} argument should be the name of some existing
17545 @command{gnatcheck} rule.
17546 Otherwise a warning message is generated and the pragma is
17547 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
17548 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
17549
17550 A source code section where an exemption is active for a given rule is
17551 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
17552
17553 @smallexample @c ada
17554 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
17555 -- source code section
17556 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
17557 @end smallexample
17558
17559
17560 @node gnatcheck Annotations Rules
17561 @subsection @command{gnatcheck} Annotations Rules
17562 @cindex @command{gnatcheck} annotations rules
17563
17564 @itemize @bullet
17565
17566 @item
17567 An ``Exempt_Off'' annotation can only appear after a corresponding
17568 ``Exempt_On'' annotation.
17569
17570 @item
17571 Exempted source code sections are only based on the source location of the
17572 annotations. Any source construct between the two
17573 annotations is part of the exempted source code section.
17574
17575 @item
17576 Exempted source code sections for different rules are independent. They can
17577 be nested or intersect with one another without limitation.
17578 Creating nested or intersecting source code sections for the same rule is
17579 not allowed.
17580
17581 @item
17582 Malformed exempted source code sections are reported by a warning, and
17583 the corresponding rule exemptions are ignored.
17584
17585 @item
17586 When an exempted source code section does not contain at least one violation
17587 of the exempted rule, a warning is emitted on @file{stderr}.
17588
17589 @item
17590 If an ``Exempt_On'' annotation pragma does not have a matching
17591 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
17592 exemption for the given rule is ignored and a warning is issued.
17593 @end itemize
17594
17595
17596 @node Predefined Rules
17597 @section Predefined Rules
17598 @cindex Predefined rules (for @command{gnatcheck})
17599
17600 @ignore
17601 @c (Jan 2007) Since the global rules are still under development and are not
17602 @c documented, there is no point in explaining the difference between
17603 @c global and local rules
17604 @noindent
17605 A rule in @command{gnatcheck} is either local or global.
17606 A @emph{local rule} is a rule that applies to a well-defined section
17607 of a program and that can be checked by analyzing only this section.
17608 A @emph{global rule} requires analysis of some global properties of the
17609 whole program (mostly related to the program call graph).
17610 As of @value{NOW}, the implementation of global rules should be
17611 considered to be at a preliminary stage. You can use the
17612 @option{+GLOBAL} option to enable all the global rules, and the
17613 @option{-GLOBAL} rule option to disable all the global rules.
17614
17615 All the global rules in the list below are
17616 so indicated by marking them ``GLOBAL''.
17617 This +GLOBAL and -GLOBAL options are not
17618 included in the list of gnatcheck options above, because at the moment they
17619 are considered as a temporary debug options.
17620
17621 @command{gnatcheck} performs rule checks for generic
17622 instances only for global rules.  This limitation may be relaxed in a later
17623 release.
17624 @end ignore
17625
17626 @noindent
17627 The predefined rules implemented in @command{gnatcheck}
17628 are described in a companion document,
17629 @cite{GNATcheck Reference Manual -- Predefined Rules}.
17630 The rule identifier is
17631 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
17632 switches.
17633
17634
17635 @node Example of gnatcheck Usage
17636 @section Example of @command{gnatcheck} Usage
17637
17638 @noindent
17639 Here is a simple example. Suppose that in the current directory we have a
17640 project file named @file{gnatcheck_example.gpr} with the following content:
17641
17642 @smallexample @c projectfile
17643 project Gnatcheck_Example is
17644
17645    for Source_Dirs use ("src");
17646    for Object_Dir use "obj";
17647    for Main use ("main.adb");
17648
17649    package Check is
17650       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
17651    end Check;
17652
17653 end Gnatcheck_Example;
17654 @end smallexample
17655
17656 @noindent
17657 And the file named @file{coding_standard} is also located in the current
17658 directory and has the following content:
17659
17660 @smallexample
17661 -----------------------------------------------------
17662 -- This is a sample gnatcheck coding standard file --
17663 -----------------------------------------------------
17664
17665 --  First, turning on rules, that are directly implemented in gnatcheck
17666 +RAbstract_Type_Declarations
17667 +RAnonymous_Arrays
17668 +RLocal_Packages
17669 +RFloat_Equality_Checks
17670 +REXIT_Statements_With_No_Loop_Name
17671
17672 --  Then, activating compiler checks of interest:
17673 +RStyle_Checks:e
17674 --  This style check checks if a unit name is present on END keyword that
17675 --  is the end of the unit declaration
17676 @end smallexample
17677
17678 @noindent
17679 And the subdirectory @file{src} contains the following Ada sources:
17680
17681 @file{pack.ads}:
17682
17683 @smallexample @c ada
17684 package Pack is
17685    type T is abstract tagged private;
17686    procedure P (X : T) is abstract;
17687
17688    package Inner is
17689       type My_Float is digits 8;
17690       function Is_Equal (L, R : My_Float) return Boolean;
17691    end Inner;
17692 private
17693    type T is abstract tagged null record;
17694 end;
17695 @end smallexample
17696
17697 @noindent
17698 @file{pack.adb}:
17699
17700 @smallexample @c ada
17701 package body Pack is
17702    package body Inner is
17703       function Is_Equal (L, R : My_Float) return Boolean is
17704       begin
17705          return L = R;
17706       end;
17707    end Inner;
17708 end Pack;
17709 @end smallexample
17710
17711 @noindent
17712 and @file{main.adb}
17713
17714 @smallexample @c ada
17715 with Pack; use Pack;
17716 procedure Main is
17717
17718    pragma Annotate
17719      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
17720    Float_Array : array (1 .. 10) of Inner.My_Float;
17721    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
17722
17723    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
17724
17725    use Inner;
17726
17727    B : Boolean := False;
17728
17729 begin
17730    for J in Float_Array'Range loop
17731       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
17732          B := True;
17733          exit;
17734       end if;
17735    end loop;
17736 end Main;
17737 @end smallexample
17738
17739 @noindent
17740 And suppose we call @command{gnatcheck} from the current directory using
17741 the @command{gnat} driver:
17742
17743 @smallexample
17744    gnat check -Pgnatcheck_example.gpr
17745 @end smallexample
17746
17747 @noindent
17748 As a result, @command{gnatcheck} is called to check all the files from the
17749 project @file{gnatcheck_example.gpr} using the coding standard defined by
17750 the file @file{coding_standard}. As the result, the @command{gnatcheck}
17751 report file named @file{gnatcheck.out} will be created in the current
17752 directory, and it will have the following content:
17753
17754 @smallexample
17755 RULE CHECKING REPORT
17756
17757 1. OVERVIEW
17758
17759 Date and time of execution: 2009.10.28 14:17
17760 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
17761 Command line:
17762
17763 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
17764
17765 Coding standard (applied rules):
17766    Abstract_Type_Declarations
17767    Anonymous_Arrays
17768    EXIT_Statements_With_No_Loop_Name
17769    Float_Equality_Checks
17770    Local_Packages
17771
17772    Compiler style checks: -gnatye
17773
17774 Number of coding standard violations: 6
17775 Number of exempted coding standard violations: 1
17776
17777 2. DETECTED RULE VIOLATIONS
17778
17779 2.1. NON-EXEMPTED VIOLATIONS
17780
17781 Source files with non-exempted violations
17782    pack.ads
17783    pack.adb
17784    main.adb
17785
17786 List of violations grouped by files, and ordered by increasing source location:
17787
17788 pack.ads:2:4: declaration of abstract type
17789 pack.ads:5:4: declaration of local package
17790 pack.ads:10:30: declaration of abstract type
17791 pack.ads:11:1: (style) "end Pack" required
17792 pack.adb:5:19: use of equality operation for float values
17793 pack.adb:6:7: (style) "end Is_Equal" required
17794 main.adb:9:26: anonymous array type
17795 main.adb:19:10: exit statement with no loop name
17796
17797 2.2. EXEMPTED VIOLATIONS
17798
17799 Source files with exempted violations
17800    main.adb
17801
17802 List of violations grouped by files, and ordered by increasing source location:
17803
17804 main.adb:6:18: anonymous array type
17805    (this one is fine)
17806
17807 2.3. SOURCE FILES WITH NO VIOLATION
17808
17809    No files without violations
17810
17811 END OF REPORT
17812 @end smallexample
17813
17814
17815 @c *********************************
17816 @node Creating Sample Bodies Using gnatstub
17817 @chapter Creating Sample Bodies Using @command{gnatstub}
17818 @findex gnatstub
17819
17820 @noindent
17821 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17822 for library unit declarations.
17823
17824 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17825 driver (see @ref{The GNAT Driver and Project Files}).
17826
17827 To create a body stub, @command{gnatstub} has to compile the library
17828 unit declaration. Therefore, bodies can be created only for legal
17829 library units. Moreover, if a library unit depends semantically upon
17830 units located outside the current directory, you have to provide
17831 the source search path when calling @command{gnatstub}, see the description
17832 of @command{gnatstub} switches below.
17833
17834 By default, all the program unit body stubs generated by @code{gnatstub}
17835 raise the predefined @code{Program_Error} exception, which will catch
17836 accidental calls of generated stubs. This behavior can be changed with
17837 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17838
17839 @menu
17840 * Running gnatstub::
17841 * Switches for gnatstub::
17842 @end menu
17843
17844 @node Running gnatstub
17845 @section Running @command{gnatstub}
17846
17847 @noindent
17848 @command{gnatstub} has the command-line interface of the form
17849
17850 @smallexample
17851 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17852 @c Expanding @ovar macro inline (explanation in macro def comments)
17853 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17854 @end smallexample
17855
17856 @noindent
17857 where
17858 @table @var
17859 @item filename
17860 is the name of the source file that contains a library unit declaration
17861 for which a body must be created. The file name may contain the path
17862 information.
17863 The file name does not have to follow the GNAT file name conventions. If the
17864 name
17865 does not follow GNAT file naming conventions, the name of the body file must
17866 be provided
17867 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17868 If the file name follows the GNAT file naming
17869 conventions and the name of the body file is not provided,
17870 @command{gnatstub}
17871 creates the name
17872 of the body file from the argument file name by replacing the @file{.ads}
17873 suffix
17874 with the @file{.adb} suffix.
17875
17876 @item directory
17877 indicates the directory in which the body stub is to be placed (the default
17878 is the
17879 current directory)
17880
17881 @item @samp{@var{gcc_switches}} is a list of switches for
17882 @command{gcc}. They will be passed on to all compiler invocations made by
17883 @command{gnatelim} to generate the ASIS trees. Here you can provide
17884 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17885 use the @option{-gnatec} switch to set the configuration file etc.
17886
17887 @item switches
17888 is an optional sequence of switches as described in the next section
17889 @end table
17890
17891 @node Switches for gnatstub
17892 @section Switches for @command{gnatstub}
17893
17894 @table @option
17895 @c !sort!
17896
17897 @item ^-f^/FULL^
17898 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17899 If the destination directory already contains a file with the name of the
17900 body file
17901 for the argument spec file, replace it with the generated body stub.
17902
17903 @item ^-hs^/HEADER=SPEC^
17904 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17905 Put the comment header (i.e., all the comments preceding the
17906 compilation unit) from the source of the library unit declaration
17907 into the body stub.
17908
17909 @item ^-hg^/HEADER=GENERAL^
17910 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17911 Put a sample comment header into the body stub.
17912
17913 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17914 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17915 Use the content of the file as the comment header for a generated body stub.
17916
17917 @ifclear vms
17918 @item -IDIR
17919 @cindex @option{-IDIR} (@command{gnatstub})
17920 @itemx -I-
17921 @cindex @option{-I-} (@command{gnatstub})
17922 @end ifclear
17923 @ifset vms
17924 @item /NOCURRENT_DIRECTORY
17925 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17926 @end ifset
17927 ^These switches have ^This switch has^ the same meaning as in calls to
17928 @command{gcc}.
17929 ^They define ^It defines ^ the source search path in the call to
17930 @command{gcc} issued
17931 by @command{gnatstub} to compile an argument source file.
17932
17933 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17934 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17935 This switch has the same meaning as in calls to @command{gcc}.
17936 It defines the additional configuration file to be passed to the call to
17937 @command{gcc} issued
17938 by @command{gnatstub} to compile an argument source file.
17939
17940 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17941 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17942 (@var{n} is a non-negative integer). Set the maximum line length in the
17943 body stub to @var{n}; the default is 79. The maximum value that can be
17944 specified is 32767. Note that in the special case of configuration
17945 pragma files, the maximum is always 32767 regardless of whether or
17946 not this switch appears.
17947
17948 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17949 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17950 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17951 the generated body sample to @var{n}.
17952 The default indentation is 3.
17953
17954 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17955 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17956 Order local bodies alphabetically. (By default local bodies are ordered
17957 in the same way as the corresponding local specs in the argument spec file.)
17958
17959 @item ^-i^/INDENTATION=^@var{n}
17960 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17961 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17962
17963 @item ^-k^/TREE_FILE=SAVE^
17964 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17965 Do not remove the tree file (i.e., the snapshot of the compiler internal
17966 structures used by @command{gnatstub}) after creating the body stub.
17967
17968 @item ^-l^/LINE_LENGTH=^@var{n}
17969 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17970 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17971
17972 @item ^--no-exception^/NO_EXCEPTION^
17973 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17974 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17975 This is not always possible for function stubs.
17976
17977 @item ^--no-local-header^/NO_LOCAL_HEADER^
17978 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17979 Do not place local comment header with unit name before body stub for a
17980 unit.
17981
17982 @item ^-o ^/BODY=^@var{body-name}
17983 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17984 Body file name.  This should be set if the argument file name does not
17985 follow
17986 the GNAT file naming
17987 conventions. If this switch is omitted the default name for the body will be
17988 obtained
17989 from the argument file name according to the GNAT file naming conventions.
17990
17991 @item ^-q^/QUIET^
17992 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17993 Quiet mode: do not generate a confirmation when a body is
17994 successfully created, and do not generate a message when a body is not
17995 required for an
17996 argument unit.
17997
17998 @item ^-r^/TREE_FILE=REUSE^
17999 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18000 Reuse the tree file (if it exists) instead of creating it.  Instead of
18001 creating the tree file for the library unit declaration, @command{gnatstub}
18002 tries to find it in the current directory and use it for creating
18003 a body. If the tree file is not found, no body is created. This option
18004 also implies @option{^-k^/SAVE^}, whether or not
18005 the latter is set explicitly.
18006
18007 @item ^-t^/TREE_FILE=OVERWRITE^
18008 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18009 Overwrite the existing tree file.  If the current directory already
18010 contains the file which, according to the GNAT file naming rules should
18011 be considered as a tree file for the argument source file,
18012 @command{gnatstub}
18013 will refuse to create the tree file needed to create a sample body
18014 unless this option is set.
18015
18016 @item ^-v^/VERBOSE^
18017 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18018 Verbose mode: generate version information.
18019
18020 @end table
18021
18022 @c *********************************
18023 @node Generating Ada Bindings for C and C++ headers
18024 @chapter Generating Ada Bindings for C and C++ headers
18025 @findex binding
18026
18027 @noindent
18028 GNAT now comes with a binding generator for C and C++ headers which is
18029 intended to do 95% of the tedious work of generating Ada specs from C
18030 or C++ header files.
18031
18032 Note that this capability is not intended to generate 100% correct Ada specs,
18033 and will is some cases require manual adjustments, although it can often
18034 be used out of the box in practice.
18035
18036 Some of the known limitations include:
18037
18038 @itemize @bullet
18039 @item only very simple character constant macros are translated into Ada
18040 constants. Function macros (macros with arguments) are partially translated
18041 as comments, to be completed manually if needed.
18042 @item some extensions (e.g. vector types) are not supported
18043 @item pointers to pointers or complex structures are mapped to System.Address
18044 @end itemize
18045
18046 The code generated is using the Ada 2005 syntax, which makes it
18047 easier to interface with other languages than previous versions of Ada.
18048
18049 @menu
18050 * Running the binding generator::
18051 * Generating bindings for C++ headers::
18052 * Switches::
18053 @end menu
18054
18055 @node Running the binding generator
18056 @section Running the binding generator
18057
18058 @noindent
18059 The binding generator is part of the @command{gcc} compiler and can be
18060 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18061 spec files for the header files specified on the command line, and all
18062 header files needed by these files transitivitely. For example:
18063
18064 @smallexample
18065 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18066 $ gcc -c -gnat05 *.ads
18067 @end smallexample
18068
18069 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18070 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18071 correspond to the files @file{/usr/include/time.h},
18072 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18073 mode these Ada specs.
18074
18075 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18076 and will attempt to generate corresponding Ada comments.
18077
18078 If you want to generate a single Ada file and not the transitive closure, you
18079 can use instead the @option{-fdump-ada-spec-slim} switch.
18080
18081 Note that we recommend when possible to use the @command{g++} driver to
18082 generate bindings, even for most C headers, since this will in general
18083 generate better Ada specs. For generating bindings for C++ headers, it is
18084 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18085 is equivalent in this case. If @command{g++} cannot work on your C headers
18086 because of incompatibilities between C and C++, then you can fallback to
18087 @command{gcc} instead.
18088
18089 For an example of better bindings generated from the C++ front-end,
18090 the name of the parameters (when available) are actually ignored by the C
18091 front-end. Consider the following C header:
18092
18093 @smallexample
18094 extern void foo (int variable);
18095 @end smallexample
18096
18097 with the C front-end, @code{variable} is ignored, and the above is handled as:
18098
18099 @smallexample
18100 extern void foo (int);
18101 @end smallexample
18102
18103 generating a generic:
18104
18105 @smallexample
18106 procedure foo (param1 : int);
18107 @end smallexample
18108
18109 with the C++ front-end, the name is available, and we generate:
18110
18111 @smallexample
18112 procedure foo (variable : int);
18113 @end smallexample
18114
18115 In some cases, the generated bindings will be more complete or more meaningful
18116 when defining some macros, which you can do via the @option{-D} switch. This
18117 is for example the case with @file{Xlib.h} under GNU/Linux:
18118
18119 @smallexample
18120 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18121 @end smallexample
18122
18123 The above will generate more complete bindings than a straight call without
18124 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18125
18126 In other cases, it is not possible to parse a header file in a stand alone
18127 manner, because other include files need to be included first. In this
18128 case, the solution is to create a small header file including the needed
18129 @code{#include} and possible @code{#define} directives. For example, to
18130 generate Ada bindings for @file{readline/readline.h}, you need to first
18131 include @file{stdio.h}, so you can create a file with the following two
18132 lines in e.g. @file{readline1.h}:
18133
18134 @smallexample
18135 #include <stdio.h>
18136 #include <readline/readline.h>
18137 @end smallexample
18138
18139 and then generate Ada bindings from this file:
18140
18141 @smallexample
18142 $ g++ -c -fdump-ada-spec readline1.h
18143 @end smallexample
18144
18145 @node Generating bindings for C++ headers
18146 @section Generating bindings for C++ headers
18147
18148 @noindent
18149 Generating bindings for C++ headers is done using the same options, always
18150 with the @command{g++} compiler.
18151
18152 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18153 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18154 multiple inheritance of abstract classes will be mapped to Ada interfaces
18155 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18156 information on interfacing to C++).
18157
18158 For example, given the following C++ header file:
18159
18160 @smallexample
18161 @group
18162 @cartouche
18163 class Carnivore @{
18164 public:
18165    virtual int Number_Of_Teeth () = 0;
18166 @};
18167
18168 class Domestic @{
18169 public:
18170    virtual void Set_Owner (char* Name) = 0;
18171 @};
18172
18173 class Animal @{
18174 public:
18175   int Age_Count;
18176   virtual void Set_Age (int New_Age);
18177 @};
18178
18179 class Dog : Animal, Carnivore, Domestic @{
18180  public:
18181   int  Tooth_Count;
18182   char *Owner;
18183
18184   virtual int  Number_Of_Teeth ();
18185   virtual void Set_Owner (char* Name);
18186
18187   Dog();
18188 @};
18189 @end cartouche
18190 @end group
18191 @end smallexample
18192
18193 The corresponding Ada code is generated:
18194
18195 @smallexample @c ada
18196 @group
18197 @cartouche
18198   package Class_Carnivore is
18199     type Carnivore is limited interface;
18200     pragma Import (CPP, Carnivore);
18201
18202     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18203   end;
18204   use Class_Carnivore;
18205
18206   package Class_Domestic is
18207     type Domestic is limited interface;
18208     pragma Import (CPP, Domestic);
18209
18210     procedure Set_Owner
18211       (this : access Domestic;
18212        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18213   end;
18214   use Class_Domestic;
18215
18216   package Class_Animal is
18217     type Animal is tagged limited record
18218       Age_Count : aliased int;
18219     end record;
18220     pragma Import (CPP, Animal);
18221
18222     procedure Set_Age (this : access Animal; New_Age : int);
18223     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18224   end;
18225   use Class_Animal;
18226
18227   package Class_Dog is
18228     type Dog is new Animal and Carnivore and Domestic with record
18229       Tooth_Count : aliased int;
18230       Owner : Interfaces.C.Strings.chars_ptr;
18231     end record;
18232     pragma Import (CPP, Dog);
18233
18234     function Number_Of_Teeth (this : access Dog) return int;
18235     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18236
18237     procedure Set_Owner
18238       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18239     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18240
18241     function New_Dog return Dog;
18242     pragma CPP_Constructor (New_Dog);
18243     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18244   end;
18245   use Class_Dog;
18246 @end cartouche
18247 @end group
18248 @end smallexample
18249
18250 @node Switches
18251 @section Switches
18252
18253 @table @option
18254 @item -fdump-ada-spec
18255 @cindex @option{-fdump-ada-spec} (@command{gcc})
18256 Generate Ada spec files for the given header files transitively (including
18257 all header files that these headers depend upon).
18258
18259 @item -fdump-ada-spec-slim
18260 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18261 Generate Ada spec files for the header files specified on the command line
18262 only.
18263
18264 @item -C
18265 @cindex @option{-C} (@command{gcc})
18266 Extract comments from headers and generate Ada comments in the Ada spec files.
18267 @end table
18268
18269 @node Other Utility Programs
18270 @chapter Other Utility Programs
18271
18272 @noindent
18273 This chapter discusses some other utility programs available in the Ada
18274 environment.
18275
18276 @menu
18277 * Using Other Utility Programs with GNAT::
18278 * The External Symbol Naming Scheme of GNAT::
18279 * Converting Ada Files to html with gnathtml::
18280 * Installing gnathtml::
18281 @ifset vms
18282 * LSE::
18283 * Profiling::
18284 @end ifset
18285 @end menu
18286
18287 @node Using Other Utility Programs with GNAT
18288 @section Using Other Utility Programs with GNAT
18289
18290 @noindent
18291 The object files generated by GNAT are in standard system format and in
18292 particular the debugging information uses this format. This means
18293 programs generated by GNAT can be used with existing utilities that
18294 depend on these formats.
18295
18296 @ifclear vms
18297 In general, any utility program that works with C will also often work with
18298 Ada programs generated by GNAT. This includes software utilities such as
18299 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18300 as Purify.
18301 @end ifclear
18302
18303 @node The External Symbol Naming Scheme of GNAT
18304 @section The External Symbol Naming Scheme of GNAT
18305
18306 @noindent
18307 In order to interpret the output from GNAT, when using tools that are
18308 originally intended for use with other languages, it is useful to
18309 understand the conventions used to generate link names from the Ada
18310 entity names.
18311
18312 All link names are in all lowercase letters. With the exception of library
18313 procedure names, the mechanism used is simply to use the full expanded
18314 Ada name with dots replaced by double underscores. For example, suppose
18315 we have the following package spec:
18316
18317 @smallexample @c ada
18318 @group
18319 @cartouche
18320 package QRS is
18321    MN : Integer;
18322 end QRS;
18323 @end cartouche
18324 @end group
18325 @end smallexample
18326
18327 @noindent
18328 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18329 the corresponding link name is @code{qrs__mn}.
18330 @findex Export
18331 Of course if a @code{pragma Export} is used this may be overridden:
18332
18333 @smallexample @c ada
18334 @group
18335 @cartouche
18336 package Exports is
18337    Var1 : Integer;
18338    pragma Export (Var1, C, External_Name => "var1_name");
18339    Var2 : Integer;
18340    pragma Export (Var2, C, Link_Name => "var2_link_name");
18341 end Exports;
18342 @end cartouche
18343 @end group
18344 @end smallexample
18345
18346 @noindent
18347 In this case, the link name for @var{Var1} is whatever link name the
18348 C compiler would assign for the C function @var{var1_name}. This typically
18349 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18350 system conventions, but other possibilities exist. The link name for
18351 @var{Var2} is @var{var2_link_name}, and this is not operating system
18352 dependent.
18353
18354 @findex _main
18355 One exception occurs for library level procedures. A potential ambiguity
18356 arises between the required name @code{_main} for the C main program,
18357 and the name we would otherwise assign to an Ada library level procedure
18358 called @code{Main} (which might well not be the main program).
18359
18360 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18361 names. So if we have a library level procedure such as
18362
18363 @smallexample @c ada
18364 @group
18365 @cartouche
18366 procedure Hello (S : String);
18367 @end cartouche
18368 @end group
18369 @end smallexample
18370
18371 @noindent
18372 the external name of this procedure will be @var{_ada_hello}.
18373
18374
18375 @node Converting Ada Files to html with gnathtml
18376 @section Converting Ada Files to HTML with @code{gnathtml}
18377
18378 @noindent
18379 This @code{Perl} script allows Ada source files to be browsed using
18380 standard Web browsers. For installation procedure, see the section
18381 @xref{Installing gnathtml}.
18382
18383 Ada reserved keywords are highlighted in a bold font and Ada comments in
18384 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18385 switch to suppress the generation of cross-referencing information, user
18386 defined variables and types will appear in a different color; you will
18387 be able to click on any identifier and go to its declaration.
18388
18389 The command line is as follow:
18390 @smallexample
18391 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18392 @c Expanding @ovar macro inline (explanation in macro def comments)
18393 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18394 @end smallexample
18395
18396 @noindent
18397 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18398 an html file for every ada file, and a global file called @file{index.htm}.
18399 This file is an index of every identifier defined in the files.
18400
18401 The available ^switches^options^ are the following ones:
18402
18403 @table @option
18404 @item -83
18405 @cindex @option{-83} (@code{gnathtml})
18406 Only the Ada 83 subset of keywords will be highlighted.
18407
18408 @item -cc @var{color}
18409 @cindex @option{-cc} (@code{gnathtml})
18410 This option allows you to change the color used for comments. The default
18411 value is green. The color argument can be any name accepted by html.
18412
18413 @item -d
18414 @cindex @option{-d} (@code{gnathtml})
18415 If the Ada files depend on some other files (for instance through
18416 @code{with} clauses, the latter files will also be converted to html.
18417 Only the files in the user project will be converted to html, not the files
18418 in the run-time library itself.
18419
18420 @item -D
18421 @cindex @option{-D} (@code{gnathtml})
18422 This command is the same as @option{-d} above, but @command{gnathtml} will
18423 also look for files in the run-time library, and generate html files for them.
18424
18425 @item -ext @var{extension}
18426 @cindex @option{-ext} (@code{gnathtml})
18427 This option allows you to change the extension of the generated HTML files.
18428 If you do not specify an extension, it will default to @file{htm}.
18429
18430 @item -f
18431 @cindex @option{-f} (@code{gnathtml})
18432 By default, gnathtml will generate html links only for global entities
18433 ('with'ed units, global variables and types,@dots{}).  If you specify
18434 @option{-f} on the command line, then links will be generated for local
18435 entities too.
18436
18437 @item -l @var{number}
18438 @cindex @option{-l} (@code{gnathtml})
18439 If this ^switch^option^ is provided and @var{number} is not 0, then
18440 @code{gnathtml} will number the html files every @var{number} line.
18441
18442 @item -I @var{dir}
18443 @cindex @option{-I} (@code{gnathtml})
18444 Specify a directory to search for library files (@file{.ALI} files) and
18445 source files. You can provide several -I switches on the command line,
18446 and the directories will be parsed in the order of the command line.
18447
18448 @item -o @var{dir}
18449 @cindex @option{-o} (@code{gnathtml})
18450 Specify the output directory for html files. By default, gnathtml will
18451 saved the generated html files in a subdirectory named @file{html/}.
18452
18453 @item -p @var{file}
18454 @cindex @option{-p} (@code{gnathtml})
18455 If you are using Emacs and the most recent Emacs Ada mode, which provides
18456 a full Integrated Development Environment for compiling, checking,
18457 running and debugging applications, you may use @file{.gpr} files
18458 to give the directories where Emacs can find sources and object files.
18459
18460 Using this ^switch^option^, you can tell gnathtml to use these files.
18461 This allows you to get an html version of your application, even if it
18462 is spread over multiple directories.
18463
18464 @item -sc @var{color}
18465 @cindex @option{-sc} (@code{gnathtml})
18466 This ^switch^option^ allows you to change the color used for symbol
18467 definitions.
18468 The default value is red. The color argument can be any name accepted by html.
18469
18470 @item -t @var{file}
18471 @cindex @option{-t} (@code{gnathtml})
18472 This ^switch^option^ provides the name of a file. This file contains a list of
18473 file names to be converted, and the effect is exactly as though they had
18474 appeared explicitly on the command line. This
18475 is the recommended way to work around the command line length limit on some
18476 systems.
18477
18478 @end table
18479
18480 @node Installing gnathtml
18481 @section Installing @code{gnathtml}
18482
18483 @noindent
18484 @code{Perl} needs to be installed on your machine to run this script.
18485 @code{Perl} is freely available for almost every architecture and
18486 Operating System via the Internet.
18487
18488 On Unix systems, you  may want to modify  the  first line of  the script
18489 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18490 is. The syntax of this line is:
18491 @smallexample
18492 #!full_path_name_to_perl
18493 @end smallexample
18494
18495 @noindent
18496 Alternatively, you may run the script using the following command line:
18497
18498 @smallexample
18499 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18500 @c Expanding @ovar macro inline (explanation in macro def comments)
18501 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18502 @end smallexample
18503
18504 @ifset vms
18505 @node LSE
18506 @section LSE
18507 @findex LSE
18508
18509 @noindent
18510 The GNAT distribution provides an Ada 95 template for the HP Language
18511 Sensitive Editor (LSE), a component of DECset. In order to
18512 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18513
18514 @node Profiling
18515 @section Profiling
18516 @findex PCA
18517
18518 @noindent
18519 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18520 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18521 the collection phase with the /DEBUG qualifier.
18522
18523 @smallexample
18524 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18525 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18526 $ RUN/DEBUG <PROGRAM_NAME>
18527 @end smallexample
18528 @noindent
18529 @end ifset
18530
18531 @ifclear vms
18532 @c ******************************
18533 @node Code Coverage and Profiling
18534 @chapter Code Coverage and Profiling
18535 @cindex Code Coverage
18536 @cindex Profiling
18537
18538 @noindent
18539 This chapter describes how to use @code{gcov} - coverage testing tool - and
18540 @code{gprof} - profiler tool - on your Ada programs.
18541
18542 @menu
18543 * Code Coverage of Ada Programs using gcov::
18544 * Profiling an Ada Program using gprof::
18545 @end menu
18546
18547 @node Code Coverage of Ada Programs using gcov
18548 @section Code Coverage of Ada Programs using gcov
18549 @cindex gcov
18550 @cindex -fprofile-arcs
18551 @cindex -ftest-coverage
18552 @cindex -coverage
18553 @cindex Code Coverage
18554
18555 @noindent
18556 @code{gcov} is a test coverage program: it analyzes the execution of a given
18557 program on selected tests, to help you determine the portions of the program
18558 that are still untested.
18559
18560 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18561 User's Guide. You can refer to this documentation for a more complete
18562 description.
18563
18564 This chapter provides a quick startup guide, and
18565 details some Gnat-specific features.
18566
18567 @menu
18568 * Quick startup guide::
18569 * Gnat specifics::
18570 @end menu
18571
18572 @node Quick startup guide
18573 @subsection Quick startup guide
18574
18575 In order to perform coverage analysis of a program using @code{gcov}, 3
18576 steps are needed:
18577
18578 @itemize @bullet
18579 @item
18580 Code instrumentation during the compilation process
18581 @item
18582 Execution of the instrumented program
18583 @item
18584 Execution of the @code{gcov} tool to generate the result.
18585 @end itemize
18586
18587 The code instrumentation needed by gcov is created at the object level:
18588 The source code is not modified in any way, because the instrumentation code is
18589 inserted by gcc during the compilation process. To compile your code with code
18590 coverage activated, you need to recompile your whole project using the
18591 switches
18592 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18593 @code{-fprofile-arcs}.
18594
18595 @smallexample
18596 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18597    -largs -fprofile-arcs
18598 @end smallexample
18599
18600 This compilation process will create @file{.gcno} files together with
18601 the usual object files.
18602
18603 Once the program is compiled with coverage instrumentation, you can
18604 run it as many times as needed - on portions of a test suite for
18605 example. The first execution will produce @file{.gcda} files at the
18606 same location as the @file{.gcno} files.  The following executions
18607 will update those files, so that a cumulative result of the covered
18608 portions of the program is generated.
18609
18610 Finally, you need to call the @code{gcov} tool. The different options of
18611 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18612
18613 This will create annotated source files with a @file{.gcov} extension:
18614 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18615
18616 @node Gnat specifics
18617 @subsection Gnat specifics
18618
18619 Because Ada semantics, portions of the source code may be shared among
18620 several object files. This is the case for example when generics are
18621 involved, when inlining is active  or when declarations generate  initialisation
18622 calls. In order to take
18623 into account this shared code, you need to call @code{gcov} on all
18624 source files of the tested program at once.
18625
18626 The list of source files might exceed the system's maximum command line
18627 length. In order to bypass this limitation, a new mechanism has been
18628 implemented in @code{gcov}: you can now list all your project's files into a
18629 text file, and provide this file to gcov as a parameter,  preceded by a @@
18630 (e.g. @samp{gcov @@mysrclist.txt}).
18631
18632 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18633 not supported as there can be unresolved symbols during the final link.
18634
18635 @node Profiling an Ada Program using gprof
18636 @section Profiling an Ada Program using gprof
18637 @cindex gprof
18638 @cindex -pg
18639 @cindex Profiling
18640
18641 @noindent
18642 This section is not meant to be an exhaustive documentation of @code{gprof}.
18643 Full documentation for it can be found in the GNU Profiler User's Guide
18644 documentation that is part of this GNAT distribution.
18645
18646 Profiling a program helps determine the parts of a program that are executed
18647 most often, and are therefore the most time-consuming.
18648
18649 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18650 better handle Ada programs and multitasking.
18651 It is currently supported on the following platforms
18652 @itemize @bullet
18653 @item
18654 linux x86/x86_64
18655 @item
18656 solaris sparc/sparc64/x86
18657 @item
18658 windows x86
18659 @end itemize
18660
18661 @noindent
18662 In order to profile a program using @code{gprof}, 3 steps are needed:
18663
18664 @itemize @bullet
18665 @item
18666 Code instrumentation, requiring a full recompilation of the project with the
18667 proper switches.
18668 @item
18669 Execution of the program under the analysis conditions, i.e. with the desired
18670 input.
18671 @item
18672 Analysis of the results using the @code{gprof} tool.
18673 @end itemize
18674
18675 @noindent
18676 The following sections detail the different steps, and indicate how
18677 to interpret the results:
18678 @menu
18679 * Compilation for profiling::
18680 * Program execution::
18681 * Running gprof::
18682 * Interpretation of profiling results::
18683 @end menu
18684
18685 @node Compilation for profiling
18686 @subsection Compilation for profiling
18687 @cindex -pg
18688 @cindex Profiling
18689
18690 In order to profile a program the first step is to tell the compiler
18691 to generate the necessary profiling information. The compiler switch to be used
18692 is @code{-pg}, which must be added to other compilation switches. This
18693 switch needs to be specified both during compilation and link stages, and can
18694 be specified once when using gnatmake:
18695
18696 @smallexample
18697 gnatmake -f -pg -P my_project
18698 @end smallexample
18699
18700 @noindent
18701 Note that only the objects that were compiled with the @samp{-pg} switch will be
18702 profiled; if you need to profile your whole project, use the
18703 @samp{-f} gnatmake switch to force full recompilation.
18704
18705 @node Program execution
18706 @subsection Program execution
18707
18708 @noindent
18709 Once the program has been compiled for profiling, you can run it as usual.
18710
18711 The only constraint imposed by profiling is that the program must terminate
18712 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18713 properly analyzed.
18714
18715 Once the program completes execution, a data file called @file{gmon.out} is
18716 generated in the directory where the program was launched from. If this file
18717 already exists, it will be overwritten.
18718
18719 @node Running gprof
18720 @subsection Running gprof
18721
18722 @noindent
18723 The @code{gprof} tool is called as follow:
18724
18725 @smallexample
18726 gprof my_prog gmon.out
18727 @end smallexample
18728
18729 @noindent
18730 or simpler:
18731
18732 @smallexample
18733 gprof my_prog
18734 @end smallexample
18735
18736 @noindent
18737 The complete form of the gprof command line is the following:
18738
18739 @smallexample
18740 gprof [^switches^options^] [executable [data-file]]
18741 @end smallexample
18742
18743 @noindent
18744 @code{gprof} supports numerous ^switch^options^. The order of these
18745 ^switch^options^ does not matter. The full list of options can be found in
18746 the GNU Profiler User's Guide documentation that comes with this documentation.
18747
18748 The following is the subset of those switches that is most relevant:
18749
18750 @table @option
18751
18752 @item --demangle[=@var{style}]
18753 @itemx --no-demangle
18754 @cindex @option{--demangle} (@code{gprof})
18755 These options control whether symbol names should be demangled when
18756 printing output.  The default is to demangle C++ symbols.  The
18757 @code{--no-demangle} option may be used to turn off demangling. Different
18758 compilers have different mangling styles.  The optional demangling style
18759 argument can be used to choose an appropriate demangling style for your
18760 compiler, in particular Ada symbols generated by GNAT can be demangled using
18761 @code{--demangle=gnat}.
18762
18763 @item -e @var{function_name}
18764 @cindex @option{-e} (@code{gprof})
18765 The @samp{-e @var{function}} option tells @code{gprof} not to print
18766 information about the function @var{function_name} (and its
18767 children@dots{}) in the call graph.  The function will still be listed
18768 as a child of any functions that call it, but its index number will be
18769 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18770 given; only one @var{function_name} may be indicated with each @samp{-e}
18771 option.
18772
18773 @item -E @var{function_name}
18774 @cindex @option{-E} (@code{gprof})
18775 The @code{-E @var{function}} option works like the @code{-e} option, but
18776 execution time spent in the function (and children who were not called from
18777 anywhere else), will not be used to compute the percentages-of-time for
18778 the call graph.  More than one @samp{-E} option may be given; only one
18779 @var{function_name} may be indicated with each @samp{-E} option.
18780
18781 @item -f @var{function_name}
18782 @cindex @option{-f} (@code{gprof})
18783 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18784 call graph to the function @var{function_name} and its children (and
18785 their children@dots{}).  More than one @samp{-f} option may be given;
18786 only one @var{function_name} may be indicated with each @samp{-f}
18787 option.
18788
18789 @item -F @var{function_name}
18790 @cindex @option{-F} (@code{gprof})
18791 The @samp{-F @var{function}} option works like the @code{-f} option, but
18792 only time spent in the function and its children (and their
18793 children@dots{}) will be used to determine total-time and
18794 percentages-of-time for the call graph.  More than one @samp{-F} option
18795 may be given; only one @var{function_name} may be indicated with each
18796 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18797
18798 @end table
18799
18800 @node Interpretation of profiling results
18801 @subsection Interpretation of profiling results
18802
18803 @noindent
18804
18805 The results of the profiling analysis are represented by two arrays: the
18806 'flat profile' and the 'call graph'. Full documentation of those outputs
18807 can be found in the GNU Profiler User's Guide.
18808
18809 The flat profile shows the time spent in each function of the program, and how
18810 many time it has been called. This allows you to locate easily the most
18811 time-consuming functions.
18812
18813 The call graph shows, for each subprogram, the subprograms that call it,
18814 and the subprograms that it calls. It also provides an estimate of the time
18815 spent in each of those callers/called subprograms.
18816 @end ifclear
18817
18818 @c ******************************
18819 @node Running and Debugging Ada Programs
18820 @chapter Running and Debugging Ada Programs
18821 @cindex Debugging
18822
18823 @noindent
18824 This chapter discusses how to debug Ada programs.
18825 @ifset vms
18826 It applies to GNAT on the Alpha OpenVMS platform;
18827 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18828 since HP has implemented Ada support in the OpenVMS debugger on I64.
18829 @end ifset
18830
18831 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18832
18833 @enumerate
18834 @item
18835 The illegality may be a violation of the static semantics of Ada. In
18836 that case GNAT diagnoses the constructs in the program that are illegal.
18837 It is then a straightforward matter for the user to modify those parts of
18838 the program.
18839
18840 @item
18841 The illegality may be a violation of the dynamic semantics of Ada. In
18842 that case the program compiles and executes, but may generate incorrect
18843 results, or may terminate abnormally with some exception.
18844
18845 @item
18846 When presented with a program that contains convoluted errors, GNAT
18847 itself may terminate abnormally without providing full diagnostics on
18848 the incorrect user program.
18849 @end enumerate
18850
18851 @menu
18852 * The GNAT Debugger GDB::
18853 * Running GDB::
18854 * Introduction to GDB Commands::
18855 * Using Ada Expressions::
18856 * Calling User-Defined Subprograms::
18857 * Using the Next Command in a Function::
18858 * Ada Exceptions::
18859 * Ada Tasks::
18860 * Debugging Generic Units::
18861 * Remote Debugging using gdbserver::
18862 * GNAT Abnormal Termination or Failure to Terminate::
18863 * Naming Conventions for GNAT Source Files::
18864 * Getting Internal Debugging Information::
18865 * Stack Traceback::
18866 @end menu
18867
18868 @cindex Debugger
18869 @findex gdb
18870
18871 @node The GNAT Debugger GDB
18872 @section The GNAT Debugger GDB
18873
18874 @noindent
18875 @code{GDB} is a general purpose, platform-independent debugger that
18876 can be used to debug mixed-language programs compiled with @command{gcc},
18877 and in particular is capable of debugging Ada programs compiled with
18878 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18879 complex Ada data structures.
18880
18881 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18882 @ifset vms
18883 located in the GNU:[DOCS] directory,
18884 @end ifset
18885 for full details on the usage of @code{GDB}, including a section on
18886 its usage on programs. This manual should be consulted for full
18887 details. The section that follows is a brief introduction to the
18888 philosophy and use of @code{GDB}.
18889
18890 When GNAT programs are compiled, the compiler optionally writes debugging
18891 information into the generated object file, including information on
18892 line numbers, and on declared types and variables. This information is
18893 separate from the generated code. It makes the object files considerably
18894 larger, but it does not add to the size of the actual executable that
18895 will be loaded into memory, and has no impact on run-time performance. The
18896 generation of debug information is triggered by the use of the
18897 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18898 used to carry out the compilations. It is important to emphasize that
18899 the use of these options does not change the generated code.
18900
18901 The debugging information is written in standard system formats that
18902 are used by many tools, including debuggers and profilers. The format
18903 of the information is typically designed to describe C types and
18904 semantics, but GNAT implements a translation scheme which allows full
18905 details about Ada types and variables to be encoded into these
18906 standard C formats. Details of this encoding scheme may be found in
18907 the file exp_dbug.ads in the GNAT source distribution. However, the
18908 details of this encoding are, in general, of no interest to a user,
18909 since @code{GDB} automatically performs the necessary decoding.
18910
18911 When a program is bound and linked, the debugging information is
18912 collected from the object files, and stored in the executable image of
18913 the program. Again, this process significantly increases the size of
18914 the generated executable file, but it does not increase the size of
18915 the executable program itself. Furthermore, if this program is run in
18916 the normal manner, it runs exactly as if the debug information were
18917 not present, and takes no more actual memory.
18918
18919 However, if the program is run under control of @code{GDB}, the
18920 debugger is activated.  The image of the program is loaded, at which
18921 point it is ready to run.  If a run command is given, then the program
18922 will run exactly as it would have if @code{GDB} were not present. This
18923 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18924 entirely non-intrusive until a breakpoint is encountered.  If no
18925 breakpoint is ever hit, the program will run exactly as it would if no
18926 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18927 the debugging information and can respond to user commands to inspect
18928 variables, and more generally to report on the state of execution.
18929
18930 @c **************
18931 @node Running GDB
18932 @section Running GDB
18933
18934 @noindent
18935 This section describes how to initiate the debugger.
18936 @c The above sentence is really just filler, but it was otherwise
18937 @c clumsy to get the first paragraph nonindented given the conditional
18938 @c nature of the description
18939
18940 @ifclear vms
18941 The debugger can be launched from a @code{GPS} menu or
18942 directly from the command line. The description below covers the latter use.
18943 All the commands shown can be used in the @code{GPS} debug console window,
18944 but there are usually more GUI-based ways to achieve the same effect.
18945 @end ifclear
18946
18947 The command to run @code{GDB} is
18948
18949 @smallexample
18950 $ ^gdb program^GDB PROGRAM^
18951 @end smallexample
18952
18953 @noindent
18954 where @code{^program^PROGRAM^} is the name of the executable file. This
18955 activates the debugger and results in a prompt for debugger commands.
18956 The simplest command is simply @code{run}, which causes the program to run
18957 exactly as if the debugger were not present. The following section
18958 describes some of the additional commands that can be given to @code{GDB}.
18959
18960 @c *******************************
18961 @node Introduction to GDB Commands
18962 @section Introduction to GDB Commands
18963
18964 @noindent
18965 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
18966 Debugging with GDB, gdb, Debugging with GDB},
18967 @ifset vms
18968 located in the GNU:[DOCS] directory,
18969 @end ifset
18970 for extensive documentation on the use
18971 of these commands, together with examples of their use. Furthermore,
18972 the command @command{help} invoked from within GDB activates a simple help
18973 facility which summarizes the available commands and their options.
18974 In this section we summarize a few of the most commonly
18975 used commands to give an idea of what @code{GDB} is about. You should create
18976 a simple program with debugging information and experiment with the use of
18977 these @code{GDB} commands on the program as you read through the
18978 following section.
18979
18980 @table @code
18981 @item set args @var{arguments}
18982 The @var{arguments} list above is a list of arguments to be passed to
18983 the program on a subsequent run command, just as though the arguments
18984 had been entered on a normal invocation of the program. The @code{set args}
18985 command is not needed if the program does not require arguments.
18986
18987 @item run
18988 The @code{run} command causes execution of the program to start from
18989 the beginning. If the program is already running, that is to say if
18990 you are currently positioned at a breakpoint, then a prompt will ask
18991 for confirmation that you want to abandon the current execution and
18992 restart.
18993
18994 @item breakpoint @var{location}
18995 The breakpoint command sets a breakpoint, that is to say a point at which
18996 execution will halt and @code{GDB} will await further
18997 commands. @var{location} is
18998 either a line number within a file, given in the format @code{file:linenumber},
18999 or it is the name of a subprogram. If you request that a breakpoint be set on
19000 a subprogram that is overloaded, a prompt will ask you to specify on which of
19001 those subprograms you want to breakpoint. You can also
19002 specify that all of them should be breakpointed. If the program is run
19003 and execution encounters the breakpoint, then the program
19004 stops and @code{GDB} signals that the breakpoint was encountered by
19005 printing the line of code before which the program is halted.
19006
19007 @item catch exception @var{name}
19008 This command causes the program execution to stop whenever exception
19009 @var{name} is raised.  If @var{name} is omitted, then the execution is
19010 suspended when any exception is raised.
19011
19012 @item print @var{expression}
19013 This will print the value of the given expression. Most simple
19014 Ada expression formats are properly handled by @code{GDB}, so the expression
19015 can contain function calls, variables, operators, and attribute references.
19016
19017 @item continue
19018 Continues execution following a breakpoint, until the next breakpoint or the
19019 termination of the program.
19020
19021 @item step
19022 Executes a single line after a breakpoint. If the next statement
19023 is a subprogram call, execution continues into (the first statement of)
19024 the called subprogram.
19025
19026 @item next
19027 Executes a single line. If this line is a subprogram call, executes and
19028 returns from the call.
19029
19030 @item list
19031 Lists a few lines around the current source location. In practice, it
19032 is usually more convenient to have a separate edit window open with the
19033 relevant source file displayed. Successive applications of this command
19034 print subsequent lines. The command can be given an argument which is a
19035 line number, in which case it displays a few lines around the specified one.
19036
19037 @item backtrace
19038 Displays a backtrace of the call chain. This command is typically
19039 used after a breakpoint has occurred, to examine the sequence of calls that
19040 leads to the current breakpoint. The display includes one line for each
19041 activation record (frame) corresponding to an active subprogram.
19042
19043 @item up
19044 At a breakpoint, @code{GDB} can display the values of variables local
19045 to the current frame. The command @code{up} can be used to
19046 examine the contents of other active frames, by moving the focus up
19047 the stack, that is to say from callee to caller, one frame at a time.
19048
19049 @item down
19050 Moves the focus of @code{GDB} down from the frame currently being
19051 examined to the frame of its callee (the reverse of the previous command),
19052
19053 @item frame @var{n}
19054 Inspect the frame with the given number. The value 0 denotes the frame
19055 of the current breakpoint, that is to say the top of the call stack.
19056
19057 @end table
19058
19059 @noindent
19060 The above list is a very short introduction to the commands that
19061 @code{GDB} provides. Important additional capabilities, including conditional
19062 breakpoints, the ability to execute command sequences on a breakpoint,
19063 the ability to debug at the machine instruction level and many other
19064 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19065 Debugging with GDB}.  Note that most commands can be abbreviated
19066 (for example, c for continue, bt for backtrace).
19067
19068 @node Using Ada Expressions
19069 @section Using Ada Expressions
19070 @cindex Ada expressions
19071
19072 @noindent
19073 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19074 extensions. The philosophy behind the design of this subset is
19075
19076 @itemize @bullet
19077 @item
19078 That @code{GDB} should provide basic literals and access to operations for
19079 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19080 leaving more sophisticated computations to subprograms written into the
19081 program (which therefore may be called from @code{GDB}).
19082
19083 @item
19084 That type safety and strict adherence to Ada language restrictions
19085 are not particularly important to the @code{GDB} user.
19086
19087 @item
19088 That brevity is important to the @code{GDB} user.
19089 @end itemize
19090
19091 @noindent
19092 Thus, for brevity, the debugger acts as if there were
19093 implicit @code{with} and @code{use} clauses in effect for all user-written
19094 packages, thus making it unnecessary to fully qualify most names with
19095 their packages, regardless of context. Where this causes ambiguity,
19096 @code{GDB} asks the user's intent.
19097
19098 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19099 GDB, gdb, Debugging with GDB}.
19100
19101 @node Calling User-Defined Subprograms
19102 @section Calling User-Defined Subprograms
19103
19104 @noindent
19105 An important capability of @code{GDB} is the ability to call user-defined
19106 subprograms while debugging. This is achieved simply by entering
19107 a subprogram call statement in the form:
19108
19109 @smallexample
19110 call subprogram-name (parameters)
19111 @end smallexample
19112
19113 @noindent
19114 The keyword @code{call} can be omitted in the normal case where the
19115 @code{subprogram-name} does not coincide with any of the predefined
19116 @code{GDB} commands.
19117
19118 The effect is to invoke the given subprogram, passing it the
19119 list of parameters that is supplied. The parameters can be expressions and
19120 can include variables from the program being debugged. The
19121 subprogram must be defined
19122 at the library level within your program, and @code{GDB} will call the
19123 subprogram within the environment of your program execution (which
19124 means that the subprogram is free to access or even modify variables
19125 within your program).
19126
19127 The most important use of this facility is in allowing the inclusion of
19128 debugging routines that are tailored to particular data structures
19129 in your program. Such debugging routines can be written to provide a suitably
19130 high-level description of an abstract type, rather than a low-level dump
19131 of its physical layout. After all, the standard
19132 @code{GDB print} command only knows the physical layout of your
19133 types, not their abstract meaning. Debugging routines can provide information
19134 at the desired semantic level and are thus enormously useful.
19135
19136 For example, when debugging GNAT itself, it is crucial to have access to
19137 the contents of the tree nodes used to represent the program internally.
19138 But tree nodes are represented simply by an integer value (which in turn
19139 is an index into a table of nodes).
19140 Using the @code{print} command on a tree node would simply print this integer
19141 value, which is not very useful. But the PN routine (defined in file
19142 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19143 a useful high level representation of the tree node, which includes the
19144 syntactic category of the node, its position in the source, the integers
19145 that denote descendant nodes and parent node, as well as varied
19146 semantic information. To study this example in more detail, you might want to
19147 look at the body of the PN procedure in the stated file.
19148
19149 @node Using the Next Command in a Function
19150 @section Using the Next Command in a Function
19151
19152 @noindent
19153 When you use the @code{next} command in a function, the current source
19154 location will advance to the next statement as usual. A special case
19155 arises in the case of a @code{return} statement.
19156
19157 Part of the code for a return statement is the ``epilog'' of the function.
19158 This is the code that returns to the caller. There is only one copy of
19159 this epilog code, and it is typically associated with the last return
19160 statement in the function if there is more than one return. In some
19161 implementations, this epilog is associated with the first statement
19162 of the function.
19163
19164 The result is that if you use the @code{next} command from a return
19165 statement that is not the last return statement of the function you
19166 may see a strange apparent jump to the last return statement or to
19167 the start of the function. You should simply ignore this odd jump.
19168 The value returned is always that from the first return statement
19169 that was stepped through.
19170
19171 @node Ada Exceptions
19172 @section Stopping when Ada Exceptions are Raised
19173 @cindex Exceptions
19174
19175 @noindent
19176 You can set catchpoints that stop the program execution when your program
19177 raises selected exceptions.
19178
19179 @table @code
19180 @item catch exception
19181 Set a catchpoint that stops execution whenever (any task in the) program
19182 raises any exception.
19183
19184 @item catch exception @var{name}
19185 Set a catchpoint that stops execution whenever (any task in the) program
19186 raises the exception @var{name}.
19187
19188 @item catch exception unhandled
19189 Set a catchpoint that stops executino whenever (any task in the) program
19190 raises an exception for which there is no handler.
19191
19192 @item info exceptions
19193 @itemx info exceptions @var{regexp}
19194 The @code{info exceptions} command permits the user to examine all defined
19195 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19196 argument, prints out only those exceptions whose name matches @var{regexp}.
19197 @end table
19198
19199 @node Ada Tasks
19200 @section Ada Tasks
19201 @cindex Tasks
19202
19203 @noindent
19204 @code{GDB} allows the following task-related commands:
19205
19206 @table @code
19207 @item info tasks
19208 This command shows a list of current Ada tasks, as in the following example:
19209
19210 @smallexample
19211 @iftex
19212 @leftskip=0cm
19213 @end iftex
19214 (gdb) info tasks
19215   ID       TID P-ID   Thread Pri State                 Name
19216    1   8088000   0   807e000  15 Child Activation Wait main_task
19217    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19218    3   809a800   1   80a4800  15 Child Activation Wait a
19219 *  4   80ae800   3   80b8000  15 Running               c
19220 @end smallexample
19221
19222 @noindent
19223 In this listing, the asterisk before the first task indicates it to be the
19224 currently running task. The first column lists the task ID that is used
19225 to refer to tasks in the following commands.
19226
19227 @item break @var{linespec} task @var{taskid}
19228 @itemx break @var{linespec} task @var{taskid} if @dots{}
19229 @cindex Breakpoints and tasks
19230 These commands are like the @code{break @dots{} thread @dots{}}.
19231 @var{linespec} specifies source lines.
19232
19233 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19234 to specify that you only want @code{GDB} to stop the program when a
19235 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19236 numeric task identifiers assigned by @code{GDB}, shown in the first
19237 column of the @samp{info tasks} display.
19238
19239 If you do not specify @samp{task @var{taskid}} when you set a
19240 breakpoint, the breakpoint applies to @emph{all} tasks of your
19241 program.
19242
19243 You can use the @code{task} qualifier on conditional breakpoints as
19244 well; in this case, place @samp{task @var{taskid}} before the
19245 breakpoint condition (before the @code{if}).
19246
19247 @item task @var{taskno}
19248 @cindex Task switching
19249
19250 This command allows to switch to the task referred by @var{taskno}. In
19251 particular, This allows to browse the backtrace of the specified
19252 task. It is advised to switch back to the original task before
19253 continuing execution otherwise the scheduling of the program may be
19254 perturbed.
19255 @end table
19256
19257 @noindent
19258 For more detailed information on the tasking support,
19259 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19260
19261 @node Debugging Generic Units
19262 @section Debugging Generic Units
19263 @cindex Debugging Generic Units
19264 @cindex Generics
19265
19266 @noindent
19267 GNAT always uses code expansion for generic instantiation. This means that
19268 each time an instantiation occurs, a complete copy of the original code is
19269 made, with appropriate substitutions of formals by actuals.
19270
19271 It is not possible to refer to the original generic entities in
19272 @code{GDB}, but it is always possible to debug a particular instance of
19273 a generic, by using the appropriate expanded names. For example, if we have
19274
19275 @smallexample @c ada
19276 @group
19277 @cartouche
19278 procedure g is
19279
19280    generic package k is
19281       procedure kp (v1 : in out integer);
19282    end k;
19283
19284    package body k is
19285       procedure kp (v1 : in out integer) is
19286       begin
19287          v1 := v1 + 1;
19288       end kp;
19289    end k;
19290
19291    package k1 is new k;
19292    package k2 is new k;
19293
19294    var : integer := 1;
19295
19296 begin
19297    k1.kp (var);
19298    k2.kp (var);
19299    k1.kp (var);
19300    k2.kp (var);
19301 end;
19302 @end cartouche
19303 @end group
19304 @end smallexample
19305
19306 @noindent
19307 Then to break on a call to procedure kp in the k2 instance, simply
19308 use the command:
19309
19310 @smallexample
19311 (gdb) break g.k2.kp
19312 @end smallexample
19313
19314 @noindent
19315 When the breakpoint occurs, you can step through the code of the
19316 instance in the normal manner and examine the values of local variables, as for
19317 other units.
19318
19319 @node Remote Debugging using gdbserver
19320 @section Remote Debugging using gdbserver
19321 @cindex Remote Debugging using gdbserver
19322
19323 @noindent
19324 On platforms where gdbserver is supported, it is possible to use this tool
19325 to debug your application remotely.  This can be useful in situations
19326 where the program needs to be run on a target host that is different
19327 from the host used for development, particularly when the target has
19328 a limited amount of resources (either CPU and/or memory).
19329
19330 To do so, start your program using gdbserver on the target machine.
19331 gdbserver then automatically suspends the execution of your program
19332 at its entry point, waiting for a debugger to connect to it.  The
19333 following commands starts an application and tells gdbserver to
19334 wait for a connection with the debugger on localhost port 4444.
19335
19336 @smallexample
19337 $ gdbserver localhost:4444 program
19338 Process program created; pid = 5685
19339 Listening on port 4444
19340 @end smallexample
19341
19342 Once gdbserver has started listening, we can tell the debugger to establish
19343 a connection with this gdbserver, and then start the same debugging session
19344 as if the program was being debugged on the same host, directly under
19345 the control of GDB.
19346
19347 @smallexample
19348 $ gdb program
19349 (gdb) target remote targethost:4444
19350 Remote debugging using targethost:4444
19351 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19352 (gdb) b foo.adb:3
19353 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19354 (gdb) continue
19355 Continuing.
19356
19357 Breakpoint 1, foo () at foo.adb:4
19358 4       end foo;
19359 @end smallexample
19360
19361 It is also possible to use gdbserver to attach to an already running
19362 program, in which case the execution of that program is simply suspended
19363 until the connection between the debugger and gdbserver is established.
19364
19365 For more information on how to use gdbserver, @ref{Top, Server, Using
19366 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
19367 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19368
19369 @node GNAT Abnormal Termination or Failure to Terminate
19370 @section GNAT Abnormal Termination or Failure to Terminate
19371 @cindex GNAT Abnormal Termination or Failure to Terminate
19372
19373 @noindent
19374 When presented with programs that contain serious errors in syntax
19375 or semantics,
19376 GNAT may on rare occasions  experience problems in operation, such
19377 as aborting with a
19378 segmentation fault or illegal memory access, raising an internal
19379 exception, terminating abnormally, or failing to terminate at all.
19380 In such cases, you can activate
19381 various features of GNAT that can help you pinpoint the construct in your
19382 program that is the likely source of the problem.
19383
19384 The following strategies are presented in increasing order of
19385 difficulty, corresponding to your experience in using GNAT and your
19386 familiarity with compiler internals.
19387
19388 @enumerate
19389 @item
19390 Run @command{gcc} with the @option{-gnatf}. This first
19391 switch causes all errors on a given line to be reported. In its absence,
19392 only the first error on a line is displayed.
19393
19394 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19395 are encountered, rather than after compilation is terminated. If GNAT
19396 terminates prematurely or goes into an infinite loop, the last error
19397 message displayed may help to pinpoint the culprit.
19398
19399 @item
19400 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19401 mode, @command{gcc} produces ongoing information about the progress of the
19402 compilation and provides the name of each procedure as code is
19403 generated. This switch allows you to find which Ada procedure was being
19404 compiled when it encountered a code generation problem.
19405
19406 @item
19407 @cindex @option{-gnatdc} switch
19408 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19409 switch that does for the front-end what @option{^-v^VERBOSE^} does
19410 for the back end. The system prints the name of each unit,
19411 either a compilation unit or nested unit, as it is being analyzed.
19412 @item
19413 Finally, you can start
19414 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19415 front-end of GNAT, and can be run independently (normally it is just
19416 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19417 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19418 @code{where} command is the first line of attack; the variable
19419 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19420 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19421 which the execution stopped, and @code{input_file name} indicates the name of
19422 the source file.
19423 @end enumerate
19424
19425 @node Naming Conventions for GNAT Source Files
19426 @section Naming Conventions for GNAT Source Files
19427
19428 @noindent
19429 In order to examine the workings of the GNAT system, the following
19430 brief description of its organization may be helpful:
19431
19432 @itemize @bullet
19433 @item
19434 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19435
19436 @item
19437 All files prefixed with @file{^par^PAR^} are components of the parser. The
19438 numbers correspond to chapters of the Ada Reference Manual. For example,
19439 parsing of select statements can be found in @file{par-ch9.adb}.
19440
19441 @item
19442 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19443 numbers correspond to chapters of the Ada standard. For example, all
19444 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19445 addition, some features of the language require sufficient special processing
19446 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19447 dynamic dispatching, etc.
19448
19449 @item
19450 All files prefixed with @file{^exp^EXP^} perform normalization and
19451 expansion of the intermediate representation (abstract syntax tree, or AST).
19452 these files use the same numbering scheme as the parser and semantics files.
19453 For example, the construction of record initialization procedures is done in
19454 @file{exp_ch3.adb}.
19455
19456 @item
19457 The files prefixed with @file{^bind^BIND^} implement the binder, which
19458 verifies the consistency of the compilation, determines an order of
19459 elaboration, and generates the bind file.
19460
19461 @item
19462 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19463 data structures used by the front-end.
19464
19465 @item
19466 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19467 the abstract syntax tree as produced by the parser.
19468
19469 @item
19470 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19471 all entities, computed during semantic analysis.
19472
19473 @item
19474 Library management issues are dealt with in files with prefix
19475 @file{^lib^LIB^}.
19476
19477 @item
19478 @findex Ada
19479 @cindex Annex A
19480 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19481 defined in Annex A.
19482
19483 @item
19484 @findex Interfaces
19485 @cindex Annex B
19486 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19487 defined in Annex B.
19488
19489 @item
19490 @findex System
19491 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19492 both language-defined children and GNAT run-time routines.
19493
19494 @item
19495 @findex GNAT
19496 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19497 general-purpose packages, fully documented in their specs. All
19498 the other @file{.c} files are modifications of common @command{gcc} files.
19499 @end itemize
19500
19501 @node Getting Internal Debugging Information
19502 @section Getting Internal Debugging Information
19503
19504 @noindent
19505 Most compilers have internal debugging switches and modes. GNAT
19506 does also, except GNAT internal debugging switches and modes are not
19507 secret. A summary and full description of all the compiler and binder
19508 debug flags are in the file @file{debug.adb}. You must obtain the
19509 sources of the compiler to see the full detailed effects of these flags.
19510
19511 The switches that print the source of the program (reconstructed from
19512 the internal tree) are of general interest for user programs, as are the
19513 options to print
19514 the full internal tree, and the entity table (the symbol table
19515 information). The reconstructed source provides a readable version of the
19516 program after the front-end has completed analysis and  expansion,
19517 and is useful when studying the performance of specific constructs.
19518 For example, constraint checks are indicated, complex aggregates
19519 are replaced with loops and assignments, and tasking primitives
19520 are replaced with run-time calls.
19521
19522 @node Stack Traceback
19523 @section Stack Traceback
19524 @cindex traceback
19525 @cindex stack traceback
19526 @cindex stack unwinding
19527
19528 @noindent
19529 Traceback is a mechanism to display the sequence of subprogram calls that
19530 leads to a specified execution point in a program. Often (but not always)
19531 the execution point is an instruction at which an exception has been raised.
19532 This mechanism is also known as @i{stack unwinding} because it obtains
19533 its information by scanning the run-time stack and recovering the activation
19534 records of all active subprograms. Stack unwinding is one of the most
19535 important tools for program debugging.
19536
19537 The first entry stored in traceback corresponds to the deepest calling level,
19538 that is to say the subprogram currently executing the instruction
19539 from which we want to obtain the traceback.
19540
19541 Note that there is no runtime performance penalty when stack traceback
19542 is enabled, and no exception is raised during program execution.
19543
19544 @menu
19545 * Non-Symbolic Traceback::
19546 * Symbolic Traceback::
19547 @end menu
19548
19549 @node Non-Symbolic Traceback
19550 @subsection Non-Symbolic Traceback
19551 @cindex traceback, non-symbolic
19552
19553 @noindent
19554 Note: this feature is not supported on all platforms. See
19555 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19556 platforms.
19557
19558 @menu
19559 * Tracebacks From an Unhandled Exception::
19560 * Tracebacks From Exception Occurrences (non-symbolic)::
19561 * Tracebacks From Anywhere in a Program (non-symbolic)::
19562 @end menu
19563
19564 @node Tracebacks From an Unhandled Exception
19565 @subsubsection Tracebacks From an Unhandled Exception
19566
19567 @noindent
19568 A runtime non-symbolic traceback is a list of addresses of call instructions.
19569 To enable this feature you must use the @option{-E}
19570 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19571 of exception information. You can retrieve this information using the
19572 @code{addr2line} tool.
19573
19574 Here is a simple example:
19575
19576 @smallexample @c ada
19577 @cartouche
19578 procedure STB is
19579
19580    procedure P1 is
19581    begin
19582       raise Constraint_Error;
19583    end P1;
19584
19585    procedure P2 is
19586    begin
19587       P1;
19588    end P2;
19589
19590 begin
19591    P2;
19592 end STB;
19593 @end cartouche
19594 @end smallexample
19595
19596 @smallexample
19597 $ gnatmake stb -bargs -E
19598 $ stb
19599
19600 Execution terminated by unhandled exception
19601 Exception name: CONSTRAINT_ERROR
19602 Message: stb.adb:5
19603 Call stack traceback locations:
19604 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19605 @end smallexample
19606
19607 @noindent
19608 As we see the traceback lists a sequence of addresses for the unhandled
19609 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19610 guess that this exception come from procedure P1. To translate these
19611 addresses into the source lines where the calls appear, the
19612 @code{addr2line} tool, described below, is invaluable. The use of this tool
19613 requires the program to be compiled with debug information.
19614
19615 @smallexample
19616 $ gnatmake -g stb -bargs -E
19617 $ stb
19618
19619 Execution terminated by unhandled exception
19620 Exception name: CONSTRAINT_ERROR
19621 Message: stb.adb:5
19622 Call stack traceback locations:
19623 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19624
19625 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19626    0x4011f1 0x77e892a4
19627
19628 00401373 at d:/stb/stb.adb:5
19629 0040138B at d:/stb/stb.adb:10
19630 0040139C at d:/stb/stb.adb:14
19631 00401335 at d:/stb/b~stb.adb:104
19632 004011C4 at /build/@dots{}/crt1.c:200
19633 004011F1 at /build/@dots{}/crt1.c:222
19634 77E892A4 in ?? at ??:0
19635 @end smallexample
19636
19637 @noindent
19638 The @code{addr2line} tool has several other useful options:
19639
19640 @table @code
19641 @item --functions
19642 to get the function name corresponding to any location
19643
19644 @item --demangle=gnat
19645 to use the gnat decoding mode for the function names. Note that
19646 for binutils version 2.9.x the option is simply @option{--demangle}.
19647 @end table
19648
19649 @smallexample
19650 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19651    0x40139c 0x401335 0x4011c4 0x4011f1
19652
19653 00401373 in stb.p1 at d:/stb/stb.adb:5
19654 0040138B in stb.p2 at d:/stb/stb.adb:10
19655 0040139C in stb at d:/stb/stb.adb:14
19656 00401335 in main at d:/stb/b~stb.adb:104
19657 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19658 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19659 @end smallexample
19660
19661 @noindent
19662 From this traceback we can see that the exception was raised in
19663 @file{stb.adb} at line 5, which was reached from a procedure call in
19664 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19665 which contains the call to the main program.
19666 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19667 and the output will vary from platform to platform.
19668
19669 It is also possible to use @code{GDB} with these traceback addresses to debug
19670 the program. For example, we can break at a given code location, as reported
19671 in the stack traceback:
19672
19673 @smallexample
19674 $ gdb -nw stb
19675 @ifclear vms
19676 @noindent
19677 Furthermore, this feature is not implemented inside Windows DLL. Only
19678 the non-symbolic traceback is reported in this case.
19679 @end ifclear
19680
19681 (gdb) break *0x401373
19682 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19683 @end smallexample
19684
19685 @noindent
19686 It is important to note that the stack traceback addresses
19687 do not change when debug information is included. This is particularly useful
19688 because it makes it possible to release software without debug information (to
19689 minimize object size), get a field report that includes a stack traceback
19690 whenever an internal bug occurs, and then be able to retrieve the sequence
19691 of calls with the same program compiled with debug information.
19692
19693 @node Tracebacks From Exception Occurrences (non-symbolic)
19694 @subsubsection Tracebacks From Exception Occurrences
19695
19696 @noindent
19697 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19698 The stack traceback is attached to the exception information string, and can
19699 be retrieved in an exception handler within the Ada program, by means of the
19700 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19701
19702 @smallexample @c ada
19703 with Ada.Text_IO;
19704 with Ada.Exceptions;
19705
19706 procedure STB is
19707
19708    use Ada;
19709    use Ada.Exceptions;
19710
19711    procedure P1 is
19712       K : Positive := 1;
19713    begin
19714       K := K - 1;
19715    exception
19716       when E : others =>
19717          Text_IO.Put_Line (Exception_Information (E));
19718    end P1;
19719
19720    procedure P2 is
19721    begin
19722       P1;
19723    end P2;
19724
19725 begin
19726    P2;
19727 end STB;
19728 @end smallexample
19729
19730 @noindent
19731 This program will output:
19732
19733 @smallexample
19734 $ stb
19735
19736 Exception name: CONSTRAINT_ERROR
19737 Message: stb.adb:12
19738 Call stack traceback locations:
19739 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19740 @end smallexample
19741
19742 @node Tracebacks From Anywhere in a Program (non-symbolic)
19743 @subsubsection Tracebacks From Anywhere in a Program
19744
19745 @noindent
19746 It is also possible to retrieve a stack traceback from anywhere in a
19747 program. For this you need to
19748 use the @code{GNAT.Traceback} API. This package includes a procedure called
19749 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19750 display procedures described below. It is not necessary to use the
19751 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19752 is invoked explicitly.
19753
19754 @noindent
19755 In the following example we compute a traceback at a specific location in
19756 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19757 convert addresses to strings:
19758
19759 @smallexample @c ada
19760 with Ada.Text_IO;
19761 with GNAT.Traceback;
19762 with GNAT.Debug_Utilities;
19763
19764 procedure STB is
19765
19766    use Ada;
19767    use GNAT;
19768    use GNAT.Traceback;
19769
19770    procedure P1 is
19771       TB  : Tracebacks_Array (1 .. 10);
19772       --  We are asking for a maximum of 10 stack frames.
19773       Len : Natural;
19774       --  Len will receive the actual number of stack frames returned.
19775    begin
19776       Call_Chain (TB, Len);
19777
19778       Text_IO.Put ("In STB.P1 : ");
19779
19780       for K in 1 .. Len loop
19781          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19782          Text_IO.Put (' ');
19783       end loop;
19784
19785       Text_IO.New_Line;
19786    end P1;
19787
19788    procedure P2 is
19789    begin
19790       P1;
19791    end P2;
19792
19793 begin
19794    P2;
19795 end STB;
19796 @end smallexample
19797
19798 @smallexample
19799 $ gnatmake -g stb
19800 $ stb
19801
19802 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19803 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19804 @end smallexample
19805
19806 @noindent
19807 You can then get further information by invoking the @code{addr2line}
19808 tool as described earlier (note that the hexadecimal addresses
19809 need to be specified in C format, with a leading ``0x'').
19810
19811 @node Symbolic Traceback
19812 @subsection Symbolic Traceback
19813 @cindex traceback, symbolic
19814
19815 @noindent
19816 A symbolic traceback is a stack traceback in which procedure names are
19817 associated with each code location.
19818
19819 @noindent
19820 Note that this feature is not supported on all platforms. See
19821 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19822 list of currently supported platforms.
19823
19824 @noindent
19825 Note that the symbolic traceback requires that the program be compiled
19826 with debug information. If it is not compiled with debug information
19827 only the non-symbolic information will be valid.
19828
19829 @menu
19830 * Tracebacks From Exception Occurrences (symbolic)::
19831 * Tracebacks From Anywhere in a Program (symbolic)::
19832 @end menu
19833
19834 @node Tracebacks From Exception Occurrences (symbolic)
19835 @subsubsection Tracebacks From Exception Occurrences
19836
19837 @smallexample @c ada
19838 with Ada.Text_IO;
19839 with GNAT.Traceback.Symbolic;
19840
19841 procedure STB is
19842
19843    procedure P1 is
19844    begin
19845       raise Constraint_Error;
19846    end P1;
19847
19848    procedure P2 is
19849    begin
19850       P1;
19851    end P2;
19852
19853    procedure P3 is
19854    begin
19855       P2;
19856    end P3;
19857
19858 begin
19859    P3;
19860 exception
19861    when E : others =>
19862       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19863 end STB;
19864 @end smallexample
19865
19866 @smallexample
19867 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19868 $ stb
19869
19870 0040149F in stb.p1 at stb.adb:8
19871 004014B7 in stb.p2 at stb.adb:13
19872 004014CF in stb.p3 at stb.adb:18
19873 004015DD in ada.stb at stb.adb:22
19874 00401461 in main at b~stb.adb:168
19875 004011C4 in __mingw_CRTStartup at crt1.c:200
19876 004011F1 in mainCRTStartup at crt1.c:222
19877 77E892A4 in ?? at ??:0
19878 @end smallexample
19879
19880 @noindent
19881 In the above example the ``.\'' syntax in the @command{gnatmake} command
19882 is currently required by @command{addr2line} for files that are in
19883 the current working directory.
19884 Moreover, the exact sequence of linker options may vary from platform
19885 to platform.
19886 The above @option{-largs} section is for Windows platforms. By contrast,
19887 under Unix there is no need for the @option{-largs} section.
19888 Differences across platforms are due to details of linker implementation.
19889
19890 @node Tracebacks From Anywhere in a Program (symbolic)
19891 @subsubsection Tracebacks From Anywhere in a Program
19892
19893 @noindent
19894 It is possible to get a symbolic stack traceback
19895 from anywhere in a program, just as for non-symbolic tracebacks.
19896 The first step is to obtain a non-symbolic
19897 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19898 information. Here is an example:
19899
19900 @smallexample @c ada
19901 with Ada.Text_IO;
19902 with GNAT.Traceback;
19903 with GNAT.Traceback.Symbolic;
19904
19905 procedure STB is
19906
19907    use Ada;
19908    use GNAT.Traceback;
19909    use GNAT.Traceback.Symbolic;
19910
19911    procedure P1 is
19912       TB  : Tracebacks_Array (1 .. 10);
19913       --  We are asking for a maximum of 10 stack frames.
19914       Len : Natural;
19915       --  Len will receive the actual number of stack frames returned.
19916    begin
19917       Call_Chain (TB, Len);
19918       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19919    end P1;
19920
19921    procedure P2 is
19922    begin
19923       P1;
19924    end P2;
19925
19926 begin
19927    P2;
19928 end STB;
19929 @end smallexample
19930
19931 @c ******************************
19932 @ifset vms
19933 @node Compatibility with HP Ada
19934 @chapter Compatibility with HP Ada
19935 @cindex Compatibility
19936
19937 @noindent
19938 @cindex DEC Ada
19939 @cindex HP Ada
19940 @cindex Compatibility between GNAT and HP Ada
19941 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19942 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19943 GNAT is highly compatible
19944 with HP Ada, and it should generally be straightforward to port code
19945 from the HP Ada environment to GNAT. However, there are a few language
19946 and implementation differences of which the user must be aware. These
19947 differences are discussed in this chapter. In
19948 addition, the operating environment and command structure for the
19949 compiler are different, and these differences are also discussed.
19950
19951 For further details on these and other compatibility issues,
19952 see Appendix E of the HP publication
19953 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19954
19955 Except where otherwise indicated, the description of GNAT for OpenVMS
19956 applies to both the Alpha and I64 platforms.
19957
19958 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19959 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19960
19961 The discussion in this chapter addresses specifically the implementation
19962 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19963 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19964 GNAT always follows the Alpha implementation.
19965
19966 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19967 attributes are recognized, although only a subset of them can sensibly
19968 be implemented.  The description of pragmas in
19969 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19970 indicates whether or not they are applicable to non-VMS systems.
19971
19972 @menu
19973 * Ada Language Compatibility::
19974 * Differences in the Definition of Package System::
19975 * Language-Related Features::
19976 * The Package STANDARD::
19977 * The Package SYSTEM::
19978 * Tasking and Task-Related Features::
19979 * Pragmas and Pragma-Related Features::
19980 * Library of Predefined Units::
19981 * Bindings::
19982 * Main Program Definition::
19983 * Implementation-Defined Attributes::
19984 * Compiler and Run-Time Interfacing::
19985 * Program Compilation and Library Management::
19986 * Input-Output::
19987 * Implementation Limits::
19988 * Tools and Utilities::
19989 @end menu
19990
19991 @node Ada Language Compatibility
19992 @section Ada Language Compatibility
19993
19994 @noindent
19995 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19996 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19997 with Ada 83, and therefore Ada 83 programs will compile
19998 and run under GNAT with
19999 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20000 provides details on specific incompatibilities.
20001
20002 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20003 as well as the pragma @code{ADA_83}, to force the compiler to
20004 operate in Ada 83 mode. This mode does not guarantee complete
20005 conformance to Ada 83, but in practice is sufficient to
20006 eliminate most sources of incompatibilities.
20007 In particular, it eliminates the recognition of the
20008 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20009 in Ada 83 programs is legal, and handles the cases of packages
20010 with optional bodies, and generics that instantiate unconstrained
20011 types without the use of @code{(<>)}.
20012
20013 @node Differences in the Definition of Package System
20014 @section Differences in the Definition of Package @code{System}
20015
20016 @noindent
20017 An Ada compiler is allowed to add
20018 implementation-dependent declarations to package @code{System}.
20019 In normal mode,
20020 GNAT does not take advantage of this permission, and the version of
20021 @code{System} provided by GNAT exactly matches that defined in the Ada
20022 Reference Manual.
20023
20024 However, HP Ada adds an extensive set of declarations to package
20025 @code{System},
20026 as fully documented in the HP Ada manuals. To minimize changes required
20027 for programs that make use of these extensions, GNAT provides the pragma
20028 @code{Extend_System} for extending the definition of package System. By using:
20029 @cindex pragma @code{Extend_System}
20030 @cindex @code{Extend_System} pragma
20031
20032 @smallexample @c ada
20033 @group
20034 @cartouche
20035 pragma Extend_System (Aux_DEC);
20036 @end cartouche
20037 @end group
20038 @end smallexample
20039
20040 @noindent
20041 the set of definitions in @code{System} is extended to include those in
20042 package @code{System.Aux_DEC}.
20043 @cindex @code{System.Aux_DEC} package
20044 @cindex @code{Aux_DEC} package (child of @code{System})
20045 These definitions are incorporated directly into package @code{System},
20046 as though they had been declared there. For a
20047 list of the declarations added, see the spec of this package,
20048 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20049 @cindex @file{s-auxdec.ads} file
20050 The pragma @code{Extend_System} is a configuration pragma, which means that
20051 it can be placed in the file @file{gnat.adc}, so that it will automatically
20052 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20053 for further details.
20054
20055 An alternative approach that avoids the use of the non-standard
20056 @code{Extend_System} pragma is to add a context clause to the unit that
20057 references these facilities:
20058
20059 @smallexample @c ada
20060 @cartouche
20061 with System.Aux_DEC;
20062 use  System.Aux_DEC;
20063 @end cartouche
20064 @end smallexample
20065
20066 @noindent
20067 The effect is not quite semantically identical to incorporating
20068 the declarations directly into package @code{System},
20069 but most programs will not notice a difference
20070 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20071 to reference the entities directly in package @code{System}.
20072 For units containing such references,
20073 the prefixes must either be removed, or the pragma @code{Extend_System}
20074 must be used.
20075
20076 @node Language-Related Features
20077 @section Language-Related Features
20078
20079 @noindent
20080 The following sections highlight differences in types,
20081 representations of types, operations, alignment, and
20082 related topics.
20083
20084 @menu
20085 * Integer Types and Representations::
20086 * Floating-Point Types and Representations::
20087 * Pragmas Float_Representation and Long_Float::
20088 * Fixed-Point Types and Representations::
20089 * Record and Array Component Alignment::
20090 * Address Clauses::
20091 * Other Representation Clauses::
20092 @end menu
20093
20094 @node Integer Types and Representations
20095 @subsection Integer Types and Representations
20096
20097 @noindent
20098 The set of predefined integer types is identical in HP Ada and GNAT.
20099 Furthermore the representation of these integer types is also identical,
20100 including the capability of size clauses forcing biased representation.
20101
20102 In addition,
20103 HP Ada for OpenVMS Alpha systems has defined the
20104 following additional integer types in package @code{System}:
20105
20106 @itemize @bullet
20107
20108 @item
20109 @code{INTEGER_8}
20110
20111 @item
20112 @code{INTEGER_16}
20113
20114 @item
20115 @code{INTEGER_32}
20116
20117 @item
20118 @code{INTEGER_64}
20119
20120 @item
20121 @code{LARGEST_INTEGER}
20122 @end itemize
20123
20124 @noindent
20125 In GNAT, the first four of these types may be obtained from the
20126 standard Ada package @code{Interfaces}.
20127 Alternatively, by use of the pragma @code{Extend_System}, identical
20128 declarations can be referenced directly in package @code{System}.
20129 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20130
20131 @node Floating-Point Types and Representations
20132 @subsection Floating-Point Types and Representations
20133 @cindex Floating-Point types
20134
20135 @noindent
20136 The set of predefined floating-point types is identical in HP Ada and GNAT.
20137 Furthermore the representation of these floating-point
20138 types is also identical. One important difference is that the default
20139 representation for HP Ada is @code{VAX_Float}, but the default representation
20140 for GNAT is IEEE.
20141
20142 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20143 pragma @code{Float_Representation} as described in the HP Ada
20144 documentation.
20145 For example, the declarations:
20146
20147 @smallexample @c ada
20148 @cartouche
20149 type F_Float is digits 6;
20150 pragma Float_Representation (VAX_Float, F_Float);
20151 @end cartouche
20152 @end smallexample
20153
20154 @noindent
20155 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20156 format.
20157 This set of declarations actually appears in @code{System.Aux_DEC},
20158 which contains
20159 the full set of additional floating-point declarations provided in
20160 the HP Ada version of package @code{System}.
20161 This and similar declarations may be accessed in a user program
20162 by using pragma @code{Extend_System}. The use of this
20163 pragma, and the related pragma @code{Long_Float} is described in further
20164 detail in the following section.
20165
20166 @node Pragmas Float_Representation and Long_Float
20167 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20168
20169 @noindent
20170 HP Ada provides the pragma @code{Float_Representation}, which
20171 acts as a program library switch to allow control over
20172 the internal representation chosen for the predefined
20173 floating-point types declared in the package @code{Standard}.
20174 The format of this pragma is as follows:
20175
20176 @smallexample @c ada
20177 @cartouche
20178 pragma Float_Representation(VAX_Float | IEEE_Float);
20179 @end cartouche
20180 @end smallexample
20181
20182 @noindent
20183 This pragma controls the representation of floating-point
20184 types as follows:
20185
20186 @itemize @bullet
20187 @item
20188 @code{VAX_Float} specifies that floating-point
20189 types are represented by default with the VAX system hardware types
20190 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20191 Note that the @code{H-floating}
20192 type was available only on VAX systems, and is not available
20193 in either HP Ada or GNAT.
20194
20195 @item
20196 @code{IEEE_Float} specifies that floating-point
20197 types are represented by default with the IEEE single and
20198 double floating-point types.
20199 @end itemize
20200
20201 @noindent
20202 GNAT provides an identical implementation of the pragma
20203 @code{Float_Representation}, except that it functions as a
20204 configuration pragma. Note that the
20205 notion of configuration pragma corresponds closely to the
20206 HP Ada notion of a program library switch.
20207
20208 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20209 which is different
20210 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20211 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20212 advisable to change the format of numbers passed to standard library
20213 routines, and if necessary explicit type conversions may be needed.
20214
20215 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20216 efficient, and (given that it conforms to an international standard)
20217 potentially more portable.
20218 The situation in which @code{VAX_Float} may be useful is in interfacing
20219 to existing code and data that expect the use of @code{VAX_Float}.
20220 In such a situation use the predefined @code{VAX_Float}
20221 types in package @code{System}, as extended by
20222 @code{Extend_System}. For example, use @code{System.F_Float}
20223 to specify the 32-bit @code{F-Float} format.
20224
20225 @noindent
20226 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20227 to allow control over the internal representation chosen
20228 for the predefined type @code{Long_Float} and for floating-point
20229 type declarations with digits specified in the range 7 .. 15.
20230 The format of this pragma is as follows:
20231
20232 @smallexample @c ada
20233 @cartouche
20234 pragma Long_Float (D_FLOAT | G_FLOAT);
20235 @end cartouche
20236 @end smallexample
20237
20238 @node Fixed-Point Types and Representations
20239 @subsection Fixed-Point Types and Representations
20240
20241 @noindent
20242 On HP Ada for OpenVMS Alpha systems, rounding is
20243 away from zero for both positive and negative numbers.
20244 Therefore, @code{+0.5} rounds to @code{1},
20245 and @code{-0.5} rounds to @code{-1}.
20246
20247 On GNAT the results of operations
20248 on fixed-point types are in accordance with the Ada
20249 rules. In particular, results of operations on decimal
20250 fixed-point types are truncated.
20251
20252 @node Record and Array Component Alignment
20253 @subsection Record and Array Component Alignment
20254
20255 @noindent
20256 On HP Ada for OpenVMS Alpha, all non-composite components
20257 are aligned on natural boundaries. For example, 1-byte
20258 components are aligned on byte boundaries, 2-byte
20259 components on 2-byte boundaries, 4-byte components on 4-byte
20260 byte boundaries, and so on. The OpenVMS Alpha hardware
20261 runs more efficiently with naturally aligned data.
20262
20263 On GNAT, alignment rules are compatible
20264 with HP Ada for OpenVMS Alpha.
20265
20266 @node Address Clauses
20267 @subsection Address Clauses
20268
20269 @noindent
20270 In HP Ada and GNAT, address clauses are supported for
20271 objects and imported subprograms.
20272 The predefined type @code{System.Address} is a private type
20273 in both compilers on Alpha OpenVMS, with the same representation
20274 (it is simply a machine pointer). Addition, subtraction, and comparison
20275 operations are available in the standard Ada package
20276 @code{System.Storage_Elements}, or in package @code{System}
20277 if it is extended to include @code{System.Aux_DEC} using a
20278 pragma @code{Extend_System} as previously described.
20279
20280 Note that code that @code{with}'s both this extended package @code{System}
20281 and the package @code{System.Storage_Elements} should not @code{use}
20282 both packages, or ambiguities will result. In general it is better
20283 not to mix these two sets of facilities. The Ada package was
20284 designed specifically to provide the kind of features that HP Ada
20285 adds directly to package @code{System}.
20286
20287 The type @code{System.Address} is a 64-bit integer type in GNAT for
20288 I64 OpenVMS.  For more information,
20289 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20290
20291 GNAT is compatible with HP Ada in its handling of address
20292 clauses, except for some limitations in
20293 the form of address clauses for composite objects with
20294 initialization. Such address clauses are easily replaced
20295 by the use of an explicitly-defined constant as described
20296 in the Ada Reference Manual (13.1(22)). For example, the sequence
20297 of declarations:
20298
20299 @smallexample @c ada
20300 @cartouche
20301 X, Y : Integer := Init_Func;
20302 Q : String (X .. Y) := "abc";
20303 @dots{}
20304 for Q'Address use Compute_Address;
20305 @end cartouche
20306 @end smallexample
20307
20308 @noindent
20309 will be rejected by GNAT, since the address cannot be computed at the time
20310 that @code{Q} is declared. To achieve the intended effect, write instead:
20311
20312 @smallexample @c ada
20313 @group
20314 @cartouche
20315 X, Y : Integer := Init_Func;
20316 Q_Address : constant Address := Compute_Address;
20317 Q : String (X .. Y) := "abc";
20318 @dots{}
20319 for Q'Address use Q_Address;
20320 @end cartouche
20321 @end group
20322 @end smallexample
20323
20324 @noindent
20325 which will be accepted by GNAT (and other Ada compilers), and is also
20326 compatible with Ada 83. A fuller description of the restrictions
20327 on address specifications is found in @ref{Top, GNAT Reference Manual,
20328 About This Guide, gnat_rm, GNAT Reference Manual}.
20329
20330 @node Other Representation Clauses
20331 @subsection Other Representation Clauses
20332
20333 @noindent
20334 GNAT implements in a compatible manner all the representation
20335 clauses supported by HP Ada. In addition, GNAT
20336 implements the representation clause forms that were introduced in Ada 95,
20337 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20338
20339 @node The Package STANDARD
20340 @section The Package @code{STANDARD}
20341
20342 @noindent
20343 The package @code{STANDARD}, as implemented by HP Ada, is fully
20344 described in the @cite{Ada Reference Manual} and in the
20345 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20346 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20347
20348 In addition, HP Ada supports the Latin-1 character set in
20349 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20350 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20351 the type @code{WIDE_CHARACTER}.
20352
20353 The floating-point types supported by GNAT are those
20354 supported by HP Ada, but the defaults are different, and are controlled by
20355 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20356
20357 @node The Package SYSTEM
20358 @section The Package @code{SYSTEM}
20359
20360 @noindent
20361 HP Ada provides a specific version of the package
20362 @code{SYSTEM} for each platform on which the language is implemented.
20363 For the complete spec of the package @code{SYSTEM}, see
20364 Appendix F of the @cite{HP Ada Language Reference Manual}.
20365
20366 On HP Ada, the package @code{SYSTEM} includes the following conversion
20367 functions:
20368 @itemize @bullet
20369 @item @code{TO_ADDRESS(INTEGER)}
20370
20371 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20372
20373 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20374
20375 @item @code{TO_INTEGER(ADDRESS)}
20376
20377 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20378
20379 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20380 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20381 @end itemize
20382
20383 @noindent
20384 By default, GNAT supplies a version of @code{SYSTEM} that matches
20385 the definition given in the @cite{Ada Reference Manual}.
20386 This
20387 is a subset of the HP system definitions, which is as
20388 close as possible to the original definitions. The only difference
20389 is that the definition of @code{SYSTEM_NAME} is different:
20390
20391 @smallexample @c ada
20392 @cartouche
20393 type Name is (SYSTEM_NAME_GNAT);
20394 System_Name : constant Name := SYSTEM_NAME_GNAT;
20395 @end cartouche
20396 @end smallexample
20397
20398 @noindent
20399 Also, GNAT adds the Ada declarations for
20400 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20401
20402 However, the use of the following pragma causes GNAT
20403 to extend the definition of package @code{SYSTEM} so that it
20404 encompasses the full set of HP-specific extensions,
20405 including the functions listed above:
20406
20407 @smallexample @c ada
20408 @cartouche
20409 pragma Extend_System (Aux_DEC);
20410 @end cartouche
20411 @end smallexample
20412
20413 @noindent
20414 The pragma @code{Extend_System} is a configuration pragma that
20415 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20416 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20417
20418 HP Ada does not allow the recompilation of the package
20419 @code{SYSTEM}. Instead HP Ada provides several pragmas
20420 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20421 to modify values in the package @code{SYSTEM}.
20422 On OpenVMS Alpha systems, the pragma
20423 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20424 its single argument.
20425
20426 GNAT does permit the recompilation of package @code{SYSTEM} using
20427 the special switch @option{-gnatg}, and this switch can be used if
20428 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20429 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20430 or @code{MEMORY_SIZE} by any other means.
20431
20432 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20433 enumeration literal @code{SYSTEM_NAME_GNAT}.
20434
20435 The definitions provided by the use of
20436
20437 @smallexample @c ada
20438 pragma Extend_System (AUX_Dec);
20439 @end smallexample
20440
20441 @noindent
20442 are virtually identical to those provided by the HP Ada 83 package
20443 @code{SYSTEM}. One important difference is that the name of the
20444 @code{TO_ADDRESS}
20445 function for type @code{UNSIGNED_LONGWORD} is changed to
20446 @code{TO_ADDRESS_LONG}.
20447 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20448 discussion of why this change was necessary.
20449
20450 @noindent
20451 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20452 is in fact
20453 an extension to Ada 83 not strictly compatible with the reference manual.
20454 GNAT, in order to be exactly compatible with the standard,
20455 does not provide this capability. In HP Ada 83, the
20456 point of this definition is to deal with a call like:
20457
20458 @smallexample @c ada
20459 TO_ADDRESS (16#12777#);
20460 @end smallexample
20461
20462 @noindent
20463 Normally, according to Ada 83 semantics, one would expect this to be
20464 ambiguous, since it matches both the @code{INTEGER} and
20465 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20466 However, in HP Ada 83, there is no ambiguity, since the
20467 definition using @i{universal_integer} takes precedence.
20468
20469 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20470 it is
20471 not possible to be 100% compatible. Since there are many programs using
20472 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20473 GNAT was
20474 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20475 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20476
20477 @smallexample @c ada
20478 function To_Address (X : Integer) return Address;
20479 pragma Pure_Function (To_Address);
20480
20481 function To_Address_Long (X : Unsigned_Longword) return Address;
20482 pragma Pure_Function (To_Address_Long);
20483 @end smallexample
20484
20485 @noindent
20486 This means that programs using @code{TO_ADDRESS} for
20487 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20488
20489 @node Tasking and Task-Related Features
20490 @section Tasking and Task-Related Features
20491
20492 @noindent
20493 This section compares the treatment of tasking in GNAT
20494 and in HP Ada for OpenVMS Alpha.
20495 The GNAT description applies to both Alpha and I64 OpenVMS.
20496 For detailed information on tasking in
20497 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20498 relevant run-time reference manual.
20499
20500 @menu
20501 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20502 * Assigning Task IDs::
20503 * Task IDs and Delays::
20504 * Task-Related Pragmas::
20505 * Scheduling and Task Priority::
20506 * The Task Stack::
20507 * External Interrupts::
20508 @end menu
20509
20510 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20511 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20512
20513 @noindent
20514 On OpenVMS Alpha systems, each Ada task (except a passive
20515 task) is implemented as a single stream of execution
20516 that is created and managed by the kernel. On these
20517 systems, HP Ada tasking support is based on DECthreads,
20518 an implementation of the POSIX standard for threads.
20519
20520 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20521 code that calls DECthreads routines can be used together.
20522 The interaction between Ada tasks and DECthreads routines
20523 can have some benefits. For example when on OpenVMS Alpha,
20524 HP Ada can call C code that is already threaded.
20525
20526 GNAT uses the facilities of DECthreads,
20527 and Ada tasks are mapped to threads.
20528
20529 @node Assigning Task IDs
20530 @subsection Assigning Task IDs
20531
20532 @noindent
20533 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20534 the environment task that executes the main program. On
20535 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20536 that have been created but are not yet activated.
20537
20538 On OpenVMS Alpha systems, task IDs are assigned at
20539 activation. On GNAT systems, task IDs are also assigned at
20540 task creation but do not have the same form or values as
20541 task ID values in HP Ada. There is no null task, and the
20542 environment task does not have a specific task ID value.
20543
20544 @node Task IDs and Delays
20545 @subsection Task IDs and Delays
20546
20547 @noindent
20548 On OpenVMS Alpha systems, tasking delays are implemented
20549 using Timer System Services. The Task ID is used for the
20550 identification of the timer request (the @code{REQIDT} parameter).
20551 If Timers are used in the application take care not to use
20552 @code{0} for the identification, because cancelling such a timer
20553 will cancel all timers and may lead to unpredictable results.
20554
20555 @node Task-Related Pragmas
20556 @subsection Task-Related Pragmas
20557
20558 @noindent
20559 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20560 specification of the size of the guard area for a task
20561 stack. (The guard area forms an area of memory that has no
20562 read or write access and thus helps in the detection of
20563 stack overflow.) On OpenVMS Alpha systems, if the pragma
20564 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20565 area is created. In the absence of a pragma @code{TASK_STORAGE},
20566 a default guard area is created.
20567
20568 GNAT supplies the following task-related pragmas:
20569
20570 @itemize @bullet
20571 @item  @code{TASK_INFO}
20572
20573 This pragma appears within a task definition and
20574 applies to the task in which it appears. The argument
20575 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20576
20577 @item  @code{TASK_STORAGE}
20578
20579 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20580 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20581 @code{SUPPRESS}, and @code{VOLATILE}.
20582 @end itemize
20583 @node Scheduling and Task Priority
20584 @subsection Scheduling and Task Priority
20585
20586 @noindent
20587 HP Ada implements the Ada language requirement that
20588 when two tasks are eligible for execution and they have
20589 different priorities, the lower priority task does not
20590 execute while the higher priority task is waiting. The HP
20591 Ada Run-Time Library keeps a task running until either the
20592 task is suspended or a higher priority task becomes ready.
20593
20594 On OpenVMS Alpha systems, the default strategy is round-
20595 robin with preemption. Tasks of equal priority take turns
20596 at the processor. A task is run for a certain period of
20597 time and then placed at the tail of the ready queue for
20598 its priority level.
20599
20600 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20601 which can be used to enable or disable round-robin
20602 scheduling of tasks with the same priority.
20603 See the relevant HP Ada run-time reference manual for
20604 information on using the pragmas to control HP Ada task
20605 scheduling.
20606
20607 GNAT follows the scheduling rules of Annex D (Real-Time
20608 Annex) of the @cite{Ada Reference Manual}. In general, this
20609 scheduling strategy is fully compatible with HP Ada
20610 although it provides some additional constraints (as
20611 fully documented in Annex D).
20612 GNAT implements time slicing control in a manner compatible with
20613 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20614 are identical to the HP Ada 83 pragma of the same name.
20615 Note that it is not possible to mix GNAT tasking and
20616 HP Ada 83 tasking in the same program, since the two run-time
20617 libraries are not compatible.
20618
20619 @node The Task Stack
20620 @subsection The Task Stack
20621
20622 @noindent
20623 In HP Ada, a task stack is allocated each time a
20624 non-passive task is activated. As soon as the task is
20625 terminated, the storage for the task stack is deallocated.
20626 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20627 a default stack size is used. Also, regardless of the size
20628 specified, some additional space is allocated for task
20629 management purposes. On OpenVMS Alpha systems, at least
20630 one page is allocated.
20631
20632 GNAT handles task stacks in a similar manner. In accordance with
20633 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20634 an alternative method for controlling the task stack size.
20635 The specification of the attribute @code{T'STORAGE_SIZE} is also
20636 supported in a manner compatible with HP Ada.
20637
20638 @node External Interrupts
20639 @subsection External Interrupts
20640
20641 @noindent
20642 On HP Ada, external interrupts can be associated with task entries.
20643 GNAT is compatible with HP Ada in its handling of external interrupts.
20644
20645 @node Pragmas and Pragma-Related Features
20646 @section Pragmas and Pragma-Related Features
20647
20648 @noindent
20649 Both HP Ada and GNAT supply all language-defined pragmas
20650 as specified by the Ada 83 standard. GNAT also supplies all
20651 language-defined pragmas introduced by Ada 95 and Ada 2005.
20652 In addition, GNAT implements the implementation-defined pragmas
20653 from HP Ada 83.
20654
20655 @itemize @bullet
20656 @item  @code{AST_ENTRY}
20657
20658 @item  @code{COMMON_OBJECT}
20659
20660 @item  @code{COMPONENT_ALIGNMENT}
20661
20662 @item  @code{EXPORT_EXCEPTION}
20663
20664 @item  @code{EXPORT_FUNCTION}
20665
20666 @item  @code{EXPORT_OBJECT}
20667
20668 @item  @code{EXPORT_PROCEDURE}
20669
20670 @item  @code{EXPORT_VALUED_PROCEDURE}
20671
20672 @item  @code{FLOAT_REPRESENTATION}
20673
20674 @item  @code{IDENT}
20675
20676 @item  @code{IMPORT_EXCEPTION}
20677
20678 @item  @code{IMPORT_FUNCTION}
20679
20680 @item  @code{IMPORT_OBJECT}
20681
20682 @item  @code{IMPORT_PROCEDURE}
20683
20684 @item  @code{IMPORT_VALUED_PROCEDURE}
20685
20686 @item  @code{INLINE_GENERIC}
20687
20688 @item  @code{INTERFACE_NAME}
20689
20690 @item  @code{LONG_FLOAT}
20691
20692 @item  @code{MAIN_STORAGE}
20693
20694 @item  @code{PASSIVE}
20695
20696 @item  @code{PSECT_OBJECT}
20697
20698 @item  @code{SHARE_GENERIC}
20699
20700 @item  @code{SUPPRESS_ALL}
20701
20702 @item  @code{TASK_STORAGE}
20703
20704 @item  @code{TIME_SLICE}
20705
20706 @item  @code{TITLE}
20707 @end itemize
20708
20709 @noindent
20710 These pragmas are all fully implemented, with the exception of @code{TITLE},
20711 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20712 recognized, but which have no
20713 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20714 use of Ada protected objects. In GNAT, all generics are inlined.
20715
20716 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20717 a separate subprogram specification which must appear before the
20718 subprogram body.
20719
20720 GNAT also supplies a number of implementation-defined pragmas including the
20721 following:
20722
20723 @itemize @bullet
20724 @item  @code{ABORT_DEFER}
20725
20726 @item  @code{ADA_83}
20727
20728 @item  @code{ADA_95}
20729
20730 @item  @code{ADA_05}
20731
20732 @item  @code{Ada_2005}
20733
20734 @item  @code{Ada_12}
20735
20736 @item  @code{Ada_2012}
20737
20738 @item  @code{ANNOTATE}
20739
20740 @item  @code{ASSERT}
20741
20742 @item  @code{C_PASS_BY_COPY}
20743
20744 @item  @code{CPP_CLASS}
20745
20746 @item  @code{CPP_CONSTRUCTOR}
20747
20748 @item  @code{CPP_DESTRUCTOR}
20749
20750 @item  @code{DEBUG}
20751
20752 @item  @code{EXTEND_SYSTEM}
20753
20754 @item  @code{LINKER_ALIAS}
20755
20756 @item  @code{LINKER_SECTION}
20757
20758 @item  @code{MACHINE_ATTRIBUTE}
20759
20760 @item  @code{NO_RETURN}
20761
20762 @item  @code{PURE_FUNCTION}
20763
20764 @item  @code{SOURCE_FILE_NAME}
20765
20766 @item  @code{SOURCE_REFERENCE}
20767
20768 @item  @code{TASK_INFO}
20769
20770 @item  @code{UNCHECKED_UNION}
20771
20772 @item  @code{UNIMPLEMENTED_UNIT}
20773
20774 @item  @code{UNIVERSAL_DATA}
20775
20776 @item  @code{UNSUPPRESS}
20777
20778 @item  @code{WARNINGS}
20779
20780 @item  @code{WEAK_EXTERNAL}
20781 @end itemize
20782
20783 @noindent
20784 For full details on these and other GNAT implementation-defined pragmas,
20785 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20786 Manual}.
20787
20788 @menu
20789 * Restrictions on the Pragma INLINE::
20790 * Restrictions on the Pragma INTERFACE::
20791 * Restrictions on the Pragma SYSTEM_NAME::
20792 @end menu
20793
20794 @node Restrictions on the Pragma INLINE
20795 @subsection Restrictions on Pragma @code{INLINE}
20796
20797 @noindent
20798 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20799 @itemize @bullet
20800 @item  Parameters cannot have a task type.
20801
20802 @item  Function results cannot be task types, unconstrained
20803 array types, or unconstrained types with discriminants.
20804
20805 @item  Bodies cannot declare the following:
20806 @itemize @bullet
20807 @item  Subprogram body or stub (imported subprogram is allowed)
20808
20809 @item  Tasks
20810
20811 @item  Generic declarations
20812
20813 @item  Instantiations
20814
20815 @item  Exceptions
20816
20817 @item  Access types (types derived from access types allowed)
20818
20819 @item  Array or record types
20820
20821 @item  Dependent tasks
20822
20823 @item  Direct recursive calls of subprogram or containing
20824 subprogram, directly or via a renaming
20825
20826 @end itemize
20827 @end itemize
20828
20829 @noindent
20830 In GNAT, the only restriction on pragma @code{INLINE} is that the
20831 body must occur before the call if both are in the same
20832 unit, and the size must be appropriately small. There are
20833 no other specific restrictions which cause subprograms to
20834 be incapable of being inlined.
20835
20836 @node  Restrictions on the Pragma INTERFACE
20837 @subsection  Restrictions on Pragma @code{INTERFACE}
20838
20839 @noindent
20840 The following restrictions on pragma @code{INTERFACE}
20841 are enforced by both HP Ada and GNAT:
20842 @itemize @bullet
20843 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20844 Default is the default on OpenVMS Alpha systems.
20845
20846 @item  Parameter passing: Language specifies default
20847 mechanisms but can be overridden with an @code{EXPORT} pragma.
20848
20849 @itemize @bullet
20850 @item  Ada: Use internal Ada rules.
20851
20852 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20853 record or task type. Result cannot be a string, an
20854 array, or a record.
20855
20856 @item  Fortran: Parameters cannot have a task type. Result cannot
20857 be a string, an array, or a record.
20858 @end itemize
20859 @end itemize
20860
20861 @noindent
20862 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20863 record parameters for all languages.
20864
20865 @node  Restrictions on the Pragma SYSTEM_NAME
20866 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
20867
20868 @noindent
20869 For HP Ada for OpenVMS Alpha, the enumeration literal
20870 for the type @code{NAME} is @code{OPENVMS_AXP}.
20871 In GNAT, the enumeration
20872 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20873
20874 @node  Library of Predefined Units
20875 @section  Library of Predefined Units
20876
20877 @noindent
20878 A library of predefined units is provided as part of the
20879 HP Ada and GNAT implementations. HP Ada does not provide
20880 the package @code{MACHINE_CODE} but instead recommends importing
20881 assembler code.
20882
20883 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20884 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20885 version.
20886 The HP Ada Predefined Library units are modified to remove post-Ada 83
20887 incompatibilities and to make them interoperable with GNAT
20888 (@pxref{Changes to DECLIB}, for details).
20889 The units are located in the @file{DECLIB} directory.
20890
20891 The GNAT RTL is contained in
20892 the @file{ADALIB} directory, and
20893 the default search path is set up to find @code{DECLIB} units in preference
20894 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20895 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20896
20897 @menu
20898 * Changes to DECLIB::
20899 @end menu
20900
20901 @node Changes to DECLIB
20902 @subsection Changes to @code{DECLIB}
20903
20904 @noindent
20905 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20906 compatibility are minor and include the following:
20907
20908 @itemize @bullet
20909 @item  Adjusting the location of pragmas and record representation
20910 clauses to obey Ada 95 (and thus Ada 2005) rules
20911
20912 @item  Adding the proper notation to generic formal parameters
20913 that take unconstrained types in instantiation
20914
20915 @item  Adding pragma @code{ELABORATE_BODY} to package specs
20916 that have package bodies not otherwise allowed
20917
20918 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20919 ``@code{PROTECTD}''.
20920 Currently these are found only in the @code{STARLET} package spec.
20921
20922 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20923 where the address size is constrained to 32 bits.
20924 @end itemize
20925
20926 @noindent
20927 None of the above changes is visible to users.
20928
20929 @node Bindings
20930 @section Bindings
20931
20932 @noindent
20933 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20934 @itemize @bullet
20935
20936 @item  Command Language Interpreter (CLI interface)
20937
20938 @item  DECtalk Run-Time Library (DTK interface)
20939
20940 @item  Librarian utility routines (LBR interface)
20941
20942 @item  General Purpose Run-Time Library (LIB interface)
20943
20944 @item  Math Run-Time Library (MTH interface)
20945
20946 @item  National Character Set Run-Time Library (NCS interface)
20947
20948 @item  Compiled Code Support Run-Time Library (OTS interface)
20949
20950 @item  Parallel Processing Run-Time Library (PPL interface)
20951
20952 @item  Screen Management Run-Time Library (SMG interface)
20953
20954 @item  Sort Run-Time Library (SOR interface)
20955
20956 @item  String Run-Time Library (STR interface)
20957
20958 @item STARLET System Library
20959 @findex Starlet
20960
20961 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20962
20963 @item  X Windows Toolkit (XT interface)
20964
20965 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20966 @end itemize
20967
20968 @noindent
20969 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20970 directory, on both the Alpha and I64 OpenVMS platforms.
20971
20972 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20973 in the
20974 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20975 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20976 @code{Xt}, and @code{X_Lib}
20977 causing the default X/Motif sharable image libraries to be linked in. This
20978 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20979 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20980
20981 It may be necessary to edit these options files to update or correct the
20982 library names if, for example, the newer X/Motif bindings from
20983 @file{ADA$EXAMPLES}
20984 had been (previous to installing GNAT) copied and renamed to supersede the
20985 default @file{ADA$PREDEFINED} versions.
20986
20987 @menu
20988 * Shared Libraries and Options Files::
20989 * Interfaces to C::
20990 @end menu
20991
20992 @node Shared Libraries and Options Files
20993 @subsection Shared Libraries and Options Files
20994
20995 @noindent
20996 When using the HP Ada
20997 predefined X and Motif bindings, the linking with their sharable images is
20998 done automatically by @command{GNAT LINK}.
20999 When using other X and Motif bindings, you need
21000 to add the corresponding sharable images to the command line for
21001 @code{GNAT LINK}. When linking with shared libraries, or with
21002 @file{.OPT} files, you must
21003 also add them to the command line for @command{GNAT LINK}.
21004
21005 A shared library to be used with GNAT is built in the same way as other
21006 libraries under VMS. The VMS Link command can be used in standard fashion.
21007
21008 @node Interfaces to C
21009 @subsection Interfaces to C
21010
21011 @noindent
21012 HP Ada
21013 provides the following Ada types and operations:
21014
21015 @itemize @bullet
21016 @item C types package (@code{C_TYPES})
21017
21018 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21019
21020 @item Other_types (@code{SHORT_INT})
21021 @end itemize
21022
21023 @noindent
21024 Interfacing to C with GNAT, you can use the above approach
21025 described for HP Ada or the facilities of Annex B of
21026 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21027 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21028 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21029
21030 The @option{-gnatF} qualifier forces default and explicit
21031 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21032 to be uppercased for compatibility with the default behavior
21033 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21034
21035 @node Main Program Definition
21036 @section Main Program Definition
21037
21038 @noindent
21039 The following section discusses differences in the
21040 definition of main programs on HP Ada and GNAT.
21041 On HP Ada, main programs are defined to meet the
21042 following conditions:
21043 @itemize @bullet
21044 @item  Procedure with no formal parameters (returns @code{0} upon
21045 normal completion)
21046
21047 @item  Procedure with no formal parameters (returns @code{42} when
21048 an unhandled exception is raised)
21049
21050 @item  Function with no formal parameters whose returned value
21051 is of a discrete type
21052
21053 @item  Procedure with one @code{out} formal of a discrete type for
21054 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21055
21056 @end itemize
21057
21058 @noindent
21059 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21060 a main function or main procedure returns a discrete
21061 value whose size is less than 64 bits (32 on VAX systems),
21062 the value is zero- or sign-extended as appropriate.
21063 On GNAT, main programs are defined as follows:
21064 @itemize @bullet
21065 @item  Must be a non-generic, parameterless subprogram that
21066 is either a procedure or function returning an Ada
21067 @code{STANDARD.INTEGER} (the predefined type)
21068
21069 @item  Cannot be a generic subprogram or an instantiation of a
21070 generic subprogram
21071 @end itemize
21072
21073 @node Implementation-Defined Attributes
21074 @section Implementation-Defined Attributes
21075
21076 @noindent
21077 GNAT provides all HP Ada implementation-defined
21078 attributes.
21079
21080 @node Compiler and Run-Time Interfacing
21081 @section Compiler and Run-Time Interfacing
21082
21083 @noindent
21084 HP Ada provides the following qualifiers to pass options to the linker
21085 (ACS LINK):
21086 @itemize @bullet
21087 @item  @option{/WAIT} and @option{/SUBMIT}
21088
21089 @item  @option{/COMMAND}
21090
21091 @item  @option{/@r{[}NO@r{]}MAP}
21092
21093 @item  @option{/OUTPUT=@var{file-spec}}
21094
21095 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21096 @end itemize
21097
21098 @noindent
21099 To pass options to the linker, GNAT provides the following
21100 switches:
21101
21102 @itemize @bullet
21103 @item   @option{/EXECUTABLE=@var{exec-name}}
21104
21105 @item   @option{/VERBOSE}
21106
21107 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21108 @end itemize
21109
21110 @noindent
21111 For more information on these switches, see
21112 @ref{Switches for gnatlink}.
21113 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21114 to control optimization. HP Ada also supplies the
21115 following pragmas:
21116 @itemize @bullet
21117 @item  @code{OPTIMIZE}
21118
21119 @item  @code{INLINE}
21120
21121 @item  @code{INLINE_GENERIC}
21122
21123 @item  @code{SUPPRESS_ALL}
21124
21125 @item  @code{PASSIVE}
21126 @end itemize
21127
21128 @noindent
21129 In GNAT, optimization is controlled strictly by command
21130 line parameters, as described in the corresponding section of this guide.
21131 The HP pragmas for control of optimization are
21132 recognized but ignored.
21133
21134 Note that in GNAT, the default is optimization off, whereas in HP Ada
21135 the default is that optimization is turned on.
21136
21137 @node Program Compilation and Library Management
21138 @section Program Compilation and Library Management
21139
21140 @noindent
21141 HP Ada and GNAT provide a comparable set of commands to
21142 build programs. HP Ada also provides a program library,
21143 which is a concept that does not exist on GNAT. Instead,
21144 GNAT provides directories of sources that are compiled as
21145 needed.
21146
21147 The following table summarizes
21148 the HP Ada commands and provides
21149 equivalent GNAT commands. In this table, some GNAT
21150 equivalents reflect the fact that GNAT does not use the
21151 concept of a program library. Instead, it uses a model
21152 in which collections of source and object files are used
21153 in a manner consistent with other languages like C and
21154 Fortran. Therefore, standard system file commands are used
21155 to manipulate these elements. Those GNAT commands are marked with
21156 an asterisk.
21157 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21158
21159 @need 1500
21160 @multitable @columnfractions .35 .65
21161
21162 @item @emph{HP Ada Command}
21163 @tab @emph{GNAT Equivalent / Description}
21164
21165 @item @command{ADA}
21166 @tab @command{GNAT COMPILE}@*
21167 Invokes the compiler to compile one or more Ada source files.
21168
21169 @item @command{ACS ATTACH}@*
21170 @tab [No equivalent]@*
21171 Switches control of terminal from current process running the program
21172 library manager.
21173
21174 @item @command{ACS CHECK}
21175 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21176 Forms the execution closure of one
21177 or more compiled units and checks completeness and currency.
21178
21179 @item @command{ACS COMPILE}
21180 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21181 Forms the execution closure of one or
21182 more specified units, checks completeness and currency,
21183 identifies units that have revised source files, compiles same,
21184 and recompiles units that are or will become obsolete.
21185 Also completes incomplete generic instantiations.
21186
21187 @item @command{ACS COPY FOREIGN}
21188 @tab Copy (*)@*
21189 Copies a foreign object file into the program library as a
21190 library unit body.
21191
21192 @item @command{ACS COPY UNIT}
21193 @tab Copy (*)@*
21194 Copies a compiled unit from one program library to another.
21195
21196 @item @command{ACS CREATE LIBRARY}
21197 @tab Create /directory (*)@*
21198 Creates a program library.
21199
21200 @item @command{ACS CREATE SUBLIBRARY}
21201 @tab Create /directory (*)@*
21202 Creates a program sublibrary.
21203
21204 @item @command{ACS DELETE LIBRARY}
21205 @tab @*
21206 Deletes a program library and its contents.
21207
21208 @item @command{ACS DELETE SUBLIBRARY}
21209 @tab @*
21210 Deletes a program sublibrary and its contents.
21211
21212 @item @command{ACS DELETE UNIT}
21213 @tab Delete file (*)@*
21214 On OpenVMS systems, deletes one or more compiled units from
21215 the current program library.
21216
21217 @item @command{ACS DIRECTORY}
21218 @tab Directory (*)@*
21219 On OpenVMS systems, lists units contained in the current
21220 program library.
21221
21222 @item @command{ACS ENTER FOREIGN}
21223 @tab Copy (*)@*
21224 Allows the import of a foreign body as an Ada library
21225 spec and enters a reference to a pointer.
21226
21227 @item @command{ACS ENTER UNIT}
21228 @tab Copy (*)@*
21229 Enters a reference (pointer) from the current program library to
21230 a unit compiled into another program library.
21231
21232 @item @command{ACS EXIT}
21233 @tab [No equivalent]@*
21234 Exits from the program library manager.
21235
21236 @item @command{ACS EXPORT}
21237 @tab Copy (*)@*
21238 Creates an object file that contains system-specific object code
21239 for one or more units. With GNAT, object files can simply be copied
21240 into the desired directory.
21241
21242 @item @command{ACS EXTRACT SOURCE}
21243 @tab Copy (*)@*
21244 Allows access to the copied source file for each Ada compilation unit
21245
21246 @item @command{ACS HELP}
21247 @tab @command{HELP GNAT}@*
21248 Provides online help.
21249
21250 @item @command{ACS LINK}
21251 @tab @command{GNAT LINK}@*
21252 Links an object file containing Ada units into an executable file.
21253
21254 @item @command{ACS LOAD}
21255 @tab Copy (*)@*
21256 Loads (partially compiles) Ada units into the program library.
21257 Allows loading a program from a collection of files into a library
21258 without knowing the relationship among units.
21259
21260 @item @command{ACS MERGE}
21261 @tab Copy (*)@*
21262 Merges into the current program library, one or more units from
21263 another library where they were modified.
21264
21265 @item @command{ACS RECOMPILE}
21266 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21267 Recompiles from   external or copied source files any obsolete
21268 unit in the closure. Also, completes any incomplete generic
21269 instantiations.
21270
21271 @item @command{ACS REENTER}
21272 @tab @command{GNAT MAKE}@*
21273 Reenters current references to units compiled after last entered
21274 with the @command{ACS ENTER UNIT} command.
21275
21276 @item @command{ACS SET LIBRARY}
21277 @tab Set default (*)@*
21278 Defines a program library to be the compilation context as well
21279 as the target library for compiler output and commands in general.
21280
21281 @item @command{ACS SET PRAGMA}
21282 @tab Edit @file{gnat.adc} (*)@*
21283 Redefines specified  values of the library characteristics
21284 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21285 and @code{Float_Representation}.
21286
21287 @item @command{ACS SET SOURCE}
21288 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21289 Defines the source file search list for the @command{ACS COMPILE} command.
21290
21291 @item @command{ACS SHOW LIBRARY}
21292 @tab Directory (*)@*
21293 Lists information about one or more program libraries.
21294
21295 @item @command{ACS SHOW PROGRAM}
21296 @tab [No equivalent]@*
21297 Lists information about the execution closure of one or
21298 more units in the program library.
21299
21300 @item @command{ACS SHOW SOURCE}
21301 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21302 Shows the source file search used when compiling units.
21303
21304 @item @command{ACS SHOW VERSION}
21305 @tab Compile with @option{VERBOSE} option
21306 Displays the version number of the compiler and program library
21307 manager used.
21308
21309 @item @command{ACS SPAWN}
21310 @tab [No equivalent]@*
21311 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21312 command).
21313
21314 @item @command{ACS VERIFY}
21315 @tab [No equivalent]@*
21316 Performs a series of consistency checks on a program library to
21317 determine whether the library structure and library files are in
21318 valid form.
21319 @end multitable
21320
21321 @noindent
21322
21323 @node Input-Output
21324 @section Input-Output
21325
21326 @noindent
21327 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21328 Management Services (RMS) to perform operations on
21329 external files.
21330
21331 @noindent
21332 HP Ada and GNAT predefine an identical set of input-
21333 output packages. To make the use of the
21334 generic @code{TEXT_IO} operations more convenient, HP Ada
21335 provides predefined library packages that instantiate the
21336 integer and floating-point operations for the predefined
21337 integer and floating-point types as shown in the following table.
21338
21339 @multitable @columnfractions .45 .55
21340 @item @emph{Package Name} @tab Instantiation
21341
21342 @item @code{INTEGER_TEXT_IO}
21343 @tab @code{INTEGER_IO(INTEGER)}
21344
21345 @item @code{SHORT_INTEGER_TEXT_IO}
21346 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21347
21348 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21349 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21350
21351 @item @code{FLOAT_TEXT_IO}
21352 @tab @code{FLOAT_IO(FLOAT)}
21353
21354 @item @code{LONG_FLOAT_TEXT_IO}
21355 @tab @code{FLOAT_IO(LONG_FLOAT)}
21356 @end multitable
21357
21358 @noindent
21359 The HP Ada predefined packages and their operations
21360 are implemented using OpenVMS Alpha files and input-output
21361 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21362 Familiarity with the following is recommended:
21363 @itemize @bullet
21364 @item  RMS file organizations and access methods
21365
21366 @item  OpenVMS file specifications and directories
21367
21368 @item  OpenVMS File Definition Language (FDL)
21369 @end itemize
21370
21371 @noindent
21372 GNAT provides I/O facilities that are completely
21373 compatible with HP Ada. The distribution includes the
21374 standard HP Ada versions of all I/O packages, operating
21375 in a manner compatible with HP Ada. In particular, the
21376 following packages are by default the HP Ada (Ada 83)
21377 versions of these packages rather than the renamings
21378 suggested in Annex J of the Ada Reference Manual:
21379 @itemize @bullet
21380 @item  @code{TEXT_IO}
21381
21382 @item  @code{SEQUENTIAL_IO}
21383
21384 @item  @code{DIRECT_IO}
21385 @end itemize
21386
21387 @noindent
21388 The use of the standard child package syntax (for
21389 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21390 packages.
21391 GNAT provides HP-compatible predefined instantiations
21392 of the @code{TEXT_IO} packages, and also
21393 provides the standard predefined instantiations required
21394 by the @cite{Ada Reference Manual}.
21395
21396 For further information on how GNAT interfaces to the file
21397 system or how I/O is implemented in programs written in
21398 mixed languages, see @ref{Implementation of the Standard I/O,,,
21399 gnat_rm, GNAT Reference Manual}.
21400 This chapter covers the following:
21401 @itemize @bullet
21402 @item  Standard I/O packages
21403
21404 @item  @code{FORM} strings
21405
21406 @item  @code{ADA.DIRECT_IO}
21407
21408 @item  @code{ADA.SEQUENTIAL_IO}
21409
21410 @item  @code{ADA.TEXT_IO}
21411
21412 @item  Stream pointer positioning
21413
21414 @item  Reading and writing non-regular files
21415
21416 @item  @code{GET_IMMEDIATE}
21417
21418 @item  Treating @code{TEXT_IO} files as streams
21419
21420 @item  Shared files
21421
21422 @item  Open modes
21423 @end itemize
21424
21425 @node Implementation Limits
21426 @section Implementation Limits
21427
21428 @noindent
21429 The following table lists implementation limits for HP Ada
21430 and GNAT systems.
21431 @multitable @columnfractions .60 .20 .20
21432 @sp 1
21433 @item  @emph{Compilation Parameter}
21434 @tab   @emph{HP Ada}
21435 @tab   @emph{GNAT}
21436 @sp 1
21437
21438 @item  In a subprogram or entry  declaration, maximum number of
21439 formal parameters that are of an unconstrained record type
21440 @tab   32
21441 @tab   No set limit
21442 @sp 1
21443
21444 @item  Maximum identifier length (number of characters)
21445 @tab   255
21446 @tab   32766
21447 @sp 1
21448
21449 @item  Maximum number of characters in a source line
21450 @tab   255
21451 @tab   32766
21452 @sp 1
21453
21454 @item  Maximum collection size   (number of bytes)
21455 @tab   2**31-1
21456 @tab   2**31-1
21457 @sp 1
21458
21459 @item  Maximum number of discriminants for a record type
21460 @tab   245
21461 @tab   No set limit
21462 @sp 1
21463
21464 @item  Maximum number of formal parameters in an entry or
21465 subprogram declaration
21466 @tab   246
21467 @tab    No set limit
21468 @sp 1
21469
21470 @item  Maximum number of dimensions in an array type
21471 @tab   255
21472 @tab   No set limit
21473 @sp 1
21474
21475 @item  Maximum number of library  units and subunits in a compilation.
21476 @tab   4095
21477 @tab   No set limit
21478 @sp 1
21479
21480 @item  Maximum number of library units and subunits in an execution.
21481 @tab   16383
21482 @tab   No set limit
21483 @sp 1
21484
21485 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21486 or @code{PSECT_OBJECT}
21487 @tab   32757
21488 @tab   No set limit
21489 @sp 1
21490
21491 @item  Maximum number of enumeration literals in an enumeration type
21492 definition
21493 @tab   65535
21494 @tab   No set limit
21495 @sp 1
21496
21497 @item  Maximum number of lines in a source file
21498 @tab   65534
21499 @tab   No set limit
21500 @sp 1
21501
21502 @item  Maximum number of bits in any object
21503 @tab   2**31-1
21504 @tab   2**31-1
21505 @sp 1
21506
21507 @item  Maximum size of the static portion of a stack frame (approximate)
21508 @tab   2**31-1
21509 @tab   2**31-1
21510 @end multitable
21511
21512 @node Tools and Utilities
21513 @section Tools and Utilities
21514
21515 @noindent
21516 The following table lists some of the OpenVMS development tools
21517 available for HP Ada, and the corresponding tools for
21518 use with @value{EDITION} on Alpha and I64 platforms.
21519 Aside from the debugger, all the OpenVMS tools identified are part
21520 of the DECset package.
21521
21522 @iftex
21523 @c Specify table in TeX since Texinfo does a poor job
21524 @tex
21525 \smallskip
21526 \smallskip
21527 \settabs\+Language-Sensitive Editor\quad
21528    &Product with HP Ada\quad
21529    &\cr
21530 \+\it Tool
21531    &\it Product with HP Ada
21532    & \it Product with GNAT Pro\cr
21533 \smallskip
21534 \+Code Management System
21535    &HP CMS
21536    & HP CMS\cr
21537 \smallskip
21538 \+Language-Sensitive Editor
21539    &HP LSE
21540    & emacs or HP LSE (Alpha)\cr
21541 \+
21542    &
21543    & HP LSE (I64)\cr
21544 \smallskip
21545 \+Debugger
21546    &OpenVMS Debug
21547    & gdb (Alpha),\cr
21548 \+
21549    &
21550    & OpenVMS Debug (I64)\cr
21551 \smallskip
21552 \+Source Code Analyzer /
21553    &HP SCA
21554    & GNAT XREF\cr
21555 \+Cross Referencer
21556    &
21557    &\cr
21558 \smallskip
21559 \+Test Manager
21560    &HP Digital Test
21561    & HP DTM\cr
21562 \+
21563    &Manager (DTM)
21564    &\cr
21565 \smallskip
21566 \+Performance and
21567    & HP PCA
21568    & HP PCA\cr
21569 \+Coverage Analyzer
21570    &
21571    &\cr
21572 \smallskip
21573 \+Module Management
21574    & HP MMS
21575    & Not applicable\cr
21576 \+ System
21577    &
21578    &\cr
21579 \smallskip
21580 \smallskip
21581 @end tex
21582 @end iftex
21583
21584 @ifnottex
21585 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21586 @c the TeX version above for the printed version
21587 @flushleft
21588 @c @multitable @columnfractions .3 .4 .4
21589 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21590 @item @i{Tool}
21591 @tab @i{Tool with HP Ada}
21592 @tab @i{Tool with @value{EDITION}}
21593 @item Code Management@*System
21594 @tab HP CMS
21595 @tab HP CMS
21596 @item Language-Sensitive@*Editor
21597 @tab HP LSE
21598 @tab emacs or HP LSE (Alpha)
21599 @item
21600 @tab
21601 @tab HP LSE (I64)
21602 @item Debugger
21603 @tab OpenVMS Debug
21604 @tab gdb (Alpha),
21605 @item
21606 @tab
21607 @tab OpenVMS Debug (I64)
21608 @item Source Code Analyzer /@*Cross Referencer
21609 @tab HP SCA
21610 @tab GNAT XREF
21611 @item Test Manager
21612 @tab HP Digital Test@*Manager (DTM)
21613 @tab HP DTM
21614 @item Performance and@*Coverage Analyzer
21615 @tab HP PCA
21616 @tab HP PCA
21617 @item Module Management@*System
21618 @tab HP MMS
21619 @tab Not applicable
21620 @end multitable
21621 @end flushleft
21622 @end ifnottex
21623
21624 @end ifset
21625
21626 @c **************************************
21627 @node Platform-Specific Information for the Run-Time Libraries
21628 @appendix Platform-Specific Information for the Run-Time Libraries
21629 @cindex Tasking and threads libraries
21630 @cindex Threads libraries and tasking
21631 @cindex Run-time libraries (platform-specific information)
21632
21633 @noindent
21634 The GNAT run-time implementation may vary with respect to both the
21635 underlying threads library and the exception handling scheme.
21636 For threads support, one or more of the following are supplied:
21637 @itemize @bullet
21638 @item @b{native threads library}, a binding to the thread package from
21639 the underlying operating system
21640
21641 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21642 POSIX thread package
21643 @end itemize
21644
21645 @noindent
21646 For exception handling, either or both of two models are supplied:
21647 @itemize @bullet
21648 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21649 Most programs should experience a substantial speed improvement by
21650 being compiled with a ZCX run-time.
21651 This is especially true for
21652 tasking applications or applications with many exception handlers.}
21653 @cindex Zero-Cost Exceptions
21654 @cindex ZCX (Zero-Cost Exceptions)
21655 which uses binder-generated tables that
21656 are interrogated at run time to locate a handler
21657
21658 @item @b{setjmp / longjmp} (``SJLJ''),
21659 @cindex setjmp/longjmp Exception Model
21660 @cindex SJLJ (setjmp/longjmp Exception Model)
21661 which uses dynamically-set data to establish
21662 the set of handlers
21663 @end itemize
21664
21665 @noindent
21666 This appendix summarizes which combinations of threads and exception support
21667 are supplied on various GNAT platforms.
21668 It then shows how to select a particular library either
21669 permanently or temporarily,
21670 explains the properties of (and tradeoffs among) the various threads
21671 libraries, and provides some additional
21672 information about several specific platforms.
21673
21674 @menu
21675 * Summary of Run-Time Configurations::
21676 * Specifying a Run-Time Library::
21677 * Choosing the Scheduling Policy::
21678 * Solaris-Specific Considerations::
21679 * Linux-Specific Considerations::
21680 * AIX-Specific Considerations::
21681 * Irix-Specific Considerations::
21682 * RTX-Specific Considerations::
21683 * HP-UX-Specific Considerations::
21684 @end menu
21685
21686 @node Summary of Run-Time Configurations
21687 @section Summary of Run-Time Configurations
21688
21689 @multitable @columnfractions .30 .70
21690 @item @b{alpha-openvms}
21691 @item @code{@ @ }@i{rts-native (default)}
21692 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21693 @item @code{@ @ @ @ }Exceptions @tab ZCX
21694 @*
21695 @item @b{alpha-tru64}
21696 @item @code{@ @ }@i{rts-native (default)}
21697 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21698 @item @code{@ @ @ @ }Exceptions @tab ZCX
21699 @*
21700 @item @code{@ @ }@i{rts-sjlj}
21701 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21702 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21703 @*
21704 @item @b{ia64-hp_linux}
21705 @item @code{@ @ }@i{rts-native (default)}
21706 @item @code{@ @ @ @ }Tasking    @tab pthread library
21707 @item @code{@ @ @ @ }Exceptions @tab ZCX
21708 @*
21709 @item @b{ia64-hpux}
21710 @item @code{@ @ }@i{rts-native (default)}
21711 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21712 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21713 @*
21714 @item @b{ia64-openvms}
21715 @item @code{@ @ }@i{rts-native (default)}
21716 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21717 @item @code{@ @ @ @ }Exceptions @tab ZCX
21718 @*
21719 @item @b{ia64-sgi_linux}
21720 @item @code{@ @ }@i{rts-native (default)}
21721 @item @code{@ @ @ @ }Tasking    @tab pthread library
21722 @item @code{@ @ @ @ }Exceptions @tab ZCX
21723 @*
21724 @item @b{mips-irix}
21725 @item @code{@ @ }@i{rts-native (default)}
21726 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21727 @item @code{@ @ @ @ }Exceptions @tab ZCX
21728 @*
21729 @item @b{pa-hpux}
21730 @item @code{@ @ }@i{rts-native (default)}
21731 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21732 @item @code{@ @ @ @ }Exceptions @tab ZCX
21733 @*
21734 @item @code{@ @ }@i{rts-sjlj}
21735 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21736 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21737 @*
21738 @item @b{ppc-aix}
21739 @item @code{@ @ }@i{rts-native (default)}
21740 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21741 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21742 @*
21743 @item @b{ppc-darwin}
21744 @item @code{@ @ }@i{rts-native (default)}
21745 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21746 @item @code{@ @ @ @ }Exceptions @tab ZCX
21747 @*
21748 @item @b{sparc-solaris}  @tab
21749 @item @code{@ @ }@i{rts-native (default)}
21750 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21751 @item @code{@ @ @ @ }Exceptions @tab ZCX
21752 @*
21753 @item @code{@ @ }@i{rts-pthread}
21754 @item @code{@ @ @ @ }Tasking    @tab pthread library
21755 @item @code{@ @ @ @ }Exceptions @tab ZCX
21756 @*
21757 @item @code{@ @ }@i{rts-sjlj}
21758 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21759 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21760 @*
21761 @item @b{sparc64-solaris}  @tab
21762 @item @code{@ @ }@i{rts-native (default)}
21763 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21764 @item @code{@ @ @ @ }Exceptions @tab ZCX
21765 @*
21766 @item @b{x86-linux}
21767 @item @code{@ @ }@i{rts-native (default)}
21768 @item @code{@ @ @ @ }Tasking    @tab pthread library
21769 @item @code{@ @ @ @ }Exceptions @tab ZCX
21770 @*
21771 @item @code{@ @ }@i{rts-sjlj}
21772 @item @code{@ @ @ @ }Tasking    @tab pthread library
21773 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21774 @*
21775 @item @b{x86-lynx}
21776 @item @code{@ @ }@i{rts-native (default)}
21777 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21778 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21779 @*
21780 @item @b{x86-solaris}
21781 @item @code{@ @ }@i{rts-native (default)}
21782 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21783 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21784 @*
21785 @item @b{x86-windows}
21786 @item @code{@ @ }@i{rts-native (default)}
21787 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21788 @item @code{@ @ @ @ }Exceptions @tab ZCX
21789 @*
21790 @item @code{@ @ }@i{rts-sjlj (default)}
21791 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21792 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21793 @*
21794 @item @b{x86-windows-rtx}
21795 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21796 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21797 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21798 @*
21799 @item @code{@ @ }@i{rts-rtx-w32}
21800 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21801 @item @code{@ @ @ @ }Exceptions @tab ZCX
21802 @*
21803 @item @b{x86_64-linux}
21804 @item @code{@ @ }@i{rts-native (default)}
21805 @item @code{@ @ @ @ }Tasking    @tab pthread library
21806 @item @code{@ @ @ @ }Exceptions @tab ZCX
21807 @*
21808 @item @code{@ @ }@i{rts-sjlj}
21809 @item @code{@ @ @ @ }Tasking    @tab pthread library
21810 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21811 @*
21812 @end multitable
21813
21814 @node Specifying a Run-Time Library
21815 @section Specifying a Run-Time Library
21816
21817 @noindent
21818 The @file{adainclude} subdirectory containing the sources of the GNAT
21819 run-time library, and the @file{adalib} subdirectory containing the
21820 @file{ALI} files and the static and/or shared GNAT library, are located
21821 in the gcc target-dependent area:
21822
21823 @smallexample
21824 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21825 @end smallexample
21826
21827 @noindent
21828 As indicated above, on some platforms several run-time libraries are supplied.
21829 These libraries are installed in the target dependent area and
21830 contain a complete source and binary subdirectory. The detailed description
21831 below explains the differences between the different libraries in terms of
21832 their thread support.
21833
21834 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21835 This default run time is selected by the means of soft links.
21836 For example on x86-linux:
21837
21838 @smallexample
21839 @group
21840  $(target-dir)
21841      |
21842      +--- adainclude----------+
21843      |                        |
21844      +--- adalib-----------+  |
21845      |                     |  |
21846      +--- rts-native       |  |
21847      |    |                |  |
21848      |    +--- adainclude <---+
21849      |    |                |
21850      |    +--- adalib <----+
21851      |
21852      +--- rts-sjlj
21853           |
21854           +--- adainclude
21855           |
21856           +--- adalib
21857 @end group
21858 @end smallexample
21859
21860 @noindent
21861 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21862 these soft links can be modified with the following commands:
21863
21864 @smallexample
21865 $ cd $target
21866 $ rm -f adainclude adalib
21867 $ ln -s rts-sjlj/adainclude adainclude
21868 $ ln -s rts-sjlj/adalib adalib
21869 @end smallexample
21870
21871 @noindent
21872 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21873 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21874 @file{$target/ada_object_path}.
21875
21876 Selecting another run-time library temporarily can be
21877 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21878 @cindex @option{--RTS} option
21879
21880 @node Choosing the Scheduling Policy
21881 @section Choosing the Scheduling Policy
21882
21883 @noindent
21884 When using a POSIX threads implementation, you have a choice of several
21885 scheduling policies: @code{SCHED_FIFO},
21886 @cindex @code{SCHED_FIFO} scheduling policy
21887 @code{SCHED_RR}
21888 @cindex @code{SCHED_RR} scheduling policy
21889 and @code{SCHED_OTHER}.
21890 @cindex @code{SCHED_OTHER} scheduling policy
21891 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21892 or @code{SCHED_RR} requires special (e.g., root) privileges.
21893
21894 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21895 @code{SCHED_FIFO},
21896 @cindex @code{SCHED_FIFO} scheduling policy
21897 you can use one of the following:
21898
21899 @itemize @bullet
21900 @item
21901 @code{pragma Time_Slice (0.0)}
21902 @cindex pragma Time_Slice
21903 @item
21904 the corresponding binder option @option{-T0}
21905 @cindex @option{-T0} option
21906 @item
21907 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21908 @cindex pragma Task_Dispatching_Policy
21909 @end itemize
21910
21911 @noindent
21912 To specify @code{SCHED_RR},
21913 @cindex @code{SCHED_RR} scheduling policy
21914 you should use @code{pragma Time_Slice} with a
21915 value greater than @code{0.0}, or else use the corresponding @option{-T}
21916 binder option.
21917
21918 @node Solaris-Specific Considerations
21919 @section Solaris-Specific Considerations
21920 @cindex Solaris Sparc threads libraries
21921
21922 @noindent
21923 This section addresses some topics related to the various threads libraries
21924 on Sparc Solaris.
21925
21926 @menu
21927 * Solaris Threads Issues::
21928 @end menu
21929
21930 @node Solaris Threads Issues
21931 @subsection Solaris Threads Issues
21932
21933 @noindent
21934 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21935 library based on POSIX threads --- @emph{rts-pthread}.
21936 @cindex rts-pthread threads library
21937 This run-time library has the advantage of being mostly shared across all
21938 POSIX-compliant thread implementations, and it also provides under
21939 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21940 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21941 and @code{PTHREAD_PRIO_PROTECT}
21942 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21943 semantics that can be selected using the predefined pragma
21944 @code{Locking_Policy}
21945 @cindex pragma Locking_Policy (under rts-pthread)
21946 with respectively
21947 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21948 @cindex @code{Inheritance_Locking} (under rts-pthread)
21949 @cindex @code{Ceiling_Locking} (under rts-pthread)
21950
21951 As explained above, the native run-time library is based on the Solaris thread
21952 library (@code{libthread}) and is the default library.
21953
21954 When the Solaris threads library is used (this is the default), programs
21955 compiled with GNAT can automatically take advantage of
21956 and can thus execute on multiple processors.
21957 The user can alternatively specify a processor on which the program should run
21958 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21959 is made by
21960 setting the environment variable @env{GNAT_PROCESSOR}
21961 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21962 to one of the following:
21963
21964 @table @code
21965 @item -2
21966 Use the default configuration (run the program on all
21967 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21968 unset
21969
21970 @item -1
21971 Let the run-time implementation choose one processor and run the program on
21972 that processor
21973
21974 @item 0 .. Last_Proc
21975 Run the program on the specified processor.
21976 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21977 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21978 @end table
21979
21980 @node Linux-Specific Considerations
21981 @section Linux-Specific Considerations
21982 @cindex Linux threads libraries
21983
21984 @noindent
21985 On GNU/Linux without NPTL support (usually system with GNU C Library
21986 older than 2.3), the signal model is not POSIX compliant, which means
21987 that to send a signal to the process, you need to send the signal to all
21988 threads, e.g.@: by using @code{killpg()}.
21989
21990 @node AIX-Specific Considerations
21991 @section AIX-Specific Considerations
21992 @cindex AIX resolver library
21993
21994 @noindent
21995 On AIX, the resolver library initializes some internal structure on
21996 the first call to @code{get*by*} functions, which are used to implement
21997 @code{GNAT.Sockets.Get_Host_By_Name} and
21998 @code{GNAT.Sockets.Get_Host_By_Address}.
21999 If such initialization occurs within an Ada task, and the stack size for
22000 the task is the default size, a stack overflow may occur.
22001
22002 To avoid this overflow, the user should either ensure that the first call
22003 to @code{GNAT.Sockets.Get_Host_By_Name} or
22004 @code{GNAT.Sockets.Get_Host_By_Addrss}
22005 occurs in the environment task, or use @code{pragma Storage_Size} to
22006 specify a sufficiently large size for the stack of the task that contains
22007 this call.
22008
22009 @node Irix-Specific Considerations
22010 @section Irix-Specific Considerations
22011 @cindex Irix libraries
22012
22013 @noindent
22014 The GCC support libraries coming with the Irix compiler have moved to
22015 their canonical place with respect to the general Irix ABI related
22016 conventions. Running applications built with the default shared GNAT
22017 run-time now requires the LD_LIBRARY_PATH environment variable to
22018 include this location. A possible way to achieve this is to issue the
22019 following command line on a bash prompt:
22020
22021 @smallexample
22022 @group
22023 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22024 @end group
22025 @end smallexample
22026
22027 @node RTX-Specific Considerations
22028 @section RTX-Specific Considerations
22029 @cindex RTX libraries
22030
22031 @noindent
22032 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22033 API. Applications can be built to work in two different modes:
22034
22035 @itemize @bullet
22036 @item
22037 Windows executables that run in Ring 3 to utilize memory protection
22038 (@emph{rts-rtx-w32}).
22039
22040 @item
22041 Real-time subsystem (RTSS) executables that run in Ring 0, where
22042 performance can be optimized with RTSS applications taking precedent
22043 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22044 the Microsoft linker to handle RTSS libraries.
22045
22046 @end itemize
22047
22048 @node HP-UX-Specific Considerations
22049 @section HP-UX-Specific Considerations
22050 @cindex HP-UX Scheduling
22051
22052 @noindent
22053 On HP-UX, appropriate privileges are required to change the scheduling
22054 parameters of a task. The calling process must have appropriate
22055 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22056 successfully change the scheduling parameters.
22057
22058 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22059 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22060 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22061
22062 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22063 one of the following:
22064
22065 @itemize @bullet
22066 @item
22067 @code{pragma Time_Slice (0.0)}
22068 @cindex pragma Time_Slice
22069 @item
22070 the corresponding binder option @option{-T0}
22071 @cindex @option{-T0} option
22072 @item
22073 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22074 @cindex pragma Task_Dispatching_Policy
22075 @end itemize
22076
22077 @noindent
22078 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22079 you should use @code{pragma Time_Slice} with a
22080 value greater than @code{0.0}, or use the corresponding @option{-T}
22081 binder option, or set the @code{pragma Task_Dispatching_Policy
22082 (Round_Robin_Within_Priorities)}.
22083
22084 @c *******************************
22085 @node Example of Binder Output File
22086 @appendix Example of Binder Output File
22087
22088 @noindent
22089 This Appendix displays the source code for @command{gnatbind}'s output
22090 file generated for a simple ``Hello World'' program.
22091 Comments have been added for clarification purposes.
22092
22093 @smallexample @c adanocomment
22094 @iftex
22095 @leftskip=0cm
22096 @end iftex
22097 --  The package is called Ada_Main unless this name is actually used
22098 --  as a unit name in the partition, in which case some other unique
22099 --  name is used.
22100
22101 with System;
22102 package ada_main is
22103
22104    Elab_Final_Code : Integer;
22105    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22106
22107    --  The main program saves the parameters (argument count,
22108    --  argument values, environment pointer) in global variables
22109    --  for later access by other units including
22110    --  Ada.Command_Line.
22111
22112    gnat_argc : Integer;
22113    gnat_argv : System.Address;
22114    gnat_envp : System.Address;
22115
22116    --  The actual variables are stored in a library routine. This
22117    --  is useful for some shared library situations, where there
22118    --  are problems if variables are not in the library.
22119
22120    pragma Import (C, gnat_argc);
22121    pragma Import (C, gnat_argv);
22122    pragma Import (C, gnat_envp);
22123
22124    --  The exit status is similarly an external location
22125
22126    gnat_exit_status : Integer;
22127    pragma Import (C, gnat_exit_status);
22128
22129    GNAT_Version : constant String :=
22130                     "GNAT Version: 6.0.0w (20061115)";
22131    pragma Export (C, GNAT_Version, "__gnat_version");
22132
22133    --  This is the generated adafinal routine that performs
22134    --  finalization at the end of execution. In the case where
22135    --  Ada is the main program, this main program makes a call
22136    --  to adafinal at program termination.
22137
22138    procedure adafinal;
22139    pragma Export (C, adafinal, "adafinal");
22140
22141    --  This is the generated adainit routine that performs
22142    --  initialization at the start of execution. In the case
22143    --  where Ada is the main program, this main program makes
22144    --  a call to adainit at program startup.
22145
22146    procedure adainit;
22147    pragma Export (C, adainit, "adainit");
22148
22149    --  This routine is called at the start of execution. It is
22150    --  a dummy routine that is used by the debugger to breakpoint
22151    --  at the start of execution.
22152
22153    procedure Break_Start;
22154    pragma Import (C, Break_Start, "__gnat_break_start");
22155
22156    --  This is the actual generated main program (it would be
22157    --  suppressed if the no main program switch were used). As
22158    --  required by standard system conventions, this program has
22159    --  the external name main.
22160
22161    function main
22162      (argc : Integer;
22163       argv : System.Address;
22164       envp : System.Address)
22165       return Integer;
22166    pragma Export (C, main, "main");
22167
22168    --  The following set of constants give the version
22169    --  identification values for every unit in the bound
22170    --  partition. This identification is computed from all
22171    --  dependent semantic units, and corresponds to the
22172    --  string that would be returned by use of the
22173    --  Body_Version or Version attributes.
22174
22175    type Version_32 is mod 2 ** 32;
22176    u00001 : constant Version_32 := 16#7880BEB3#;
22177    u00002 : constant Version_32 := 16#0D24CBD0#;
22178    u00003 : constant Version_32 := 16#3283DBEB#;
22179    u00004 : constant Version_32 := 16#2359F9ED#;
22180    u00005 : constant Version_32 := 16#664FB847#;
22181    u00006 : constant Version_32 := 16#68E803DF#;
22182    u00007 : constant Version_32 := 16#5572E604#;
22183    u00008 : constant Version_32 := 16#46B173D8#;
22184    u00009 : constant Version_32 := 16#156A40CF#;
22185    u00010 : constant Version_32 := 16#033DABE0#;
22186    u00011 : constant Version_32 := 16#6AB38FEA#;
22187    u00012 : constant Version_32 := 16#22B6217D#;
22188    u00013 : constant Version_32 := 16#68A22947#;
22189    u00014 : constant Version_32 := 16#18CC4A56#;
22190    u00015 : constant Version_32 := 16#08258E1B#;
22191    u00016 : constant Version_32 := 16#367D5222#;
22192    u00017 : constant Version_32 := 16#20C9ECA4#;
22193    u00018 : constant Version_32 := 16#50D32CB6#;
22194    u00019 : constant Version_32 := 16#39A8BB77#;
22195    u00020 : constant Version_32 := 16#5CF8FA2B#;
22196    u00021 : constant Version_32 := 16#2F1EB794#;
22197    u00022 : constant Version_32 := 16#31AB6444#;
22198    u00023 : constant Version_32 := 16#1574B6E9#;
22199    u00024 : constant Version_32 := 16#5109C189#;
22200    u00025 : constant Version_32 := 16#56D770CD#;
22201    u00026 : constant Version_32 := 16#02F9DE3D#;
22202    u00027 : constant Version_32 := 16#08AB6B2C#;
22203    u00028 : constant Version_32 := 16#3FA37670#;
22204    u00029 : constant Version_32 := 16#476457A0#;
22205    u00030 : constant Version_32 := 16#731E1B6E#;
22206    u00031 : constant Version_32 := 16#23C2E789#;
22207    u00032 : constant Version_32 := 16#0F1BD6A1#;
22208    u00033 : constant Version_32 := 16#7C25DE96#;
22209    u00034 : constant Version_32 := 16#39ADFFA2#;
22210    u00035 : constant Version_32 := 16#571DE3E7#;
22211    u00036 : constant Version_32 := 16#5EB646AB#;
22212    u00037 : constant Version_32 := 16#4249379B#;
22213    u00038 : constant Version_32 := 16#0357E00A#;
22214    u00039 : constant Version_32 := 16#3784FB72#;
22215    u00040 : constant Version_32 := 16#2E723019#;
22216    u00041 : constant Version_32 := 16#623358EA#;
22217    u00042 : constant Version_32 := 16#107F9465#;
22218    u00043 : constant Version_32 := 16#6843F68A#;
22219    u00044 : constant Version_32 := 16#63305874#;
22220    u00045 : constant Version_32 := 16#31E56CE1#;
22221    u00046 : constant Version_32 := 16#02917970#;
22222    u00047 : constant Version_32 := 16#6CCBA70E#;
22223    u00048 : constant Version_32 := 16#41CD4204#;
22224    u00049 : constant Version_32 := 16#572E3F58#;
22225    u00050 : constant Version_32 := 16#20729FF5#;
22226    u00051 : constant Version_32 := 16#1D4F93E8#;
22227    u00052 : constant Version_32 := 16#30B2EC3D#;
22228    u00053 : constant Version_32 := 16#34054F96#;
22229    u00054 : constant Version_32 := 16#5A199860#;
22230    u00055 : constant Version_32 := 16#0E7F912B#;
22231    u00056 : constant Version_32 := 16#5760634A#;
22232    u00057 : constant Version_32 := 16#5D851835#;
22233
22234    --  The following Export pragmas export the version numbers
22235    --  with symbolic names ending in B (for body) or S
22236    --  (for spec) so that they can be located in a link. The
22237    --  information provided here is sufficient to track down
22238    --  the exact versions of units used in a given build.
22239
22240    pragma Export (C, u00001, "helloB");
22241    pragma Export (C, u00002, "system__standard_libraryB");
22242    pragma Export (C, u00003, "system__standard_libraryS");
22243    pragma Export (C, u00004, "adaS");
22244    pragma Export (C, u00005, "ada__text_ioB");
22245    pragma Export (C, u00006, "ada__text_ioS");
22246    pragma Export (C, u00007, "ada__exceptionsB");
22247    pragma Export (C, u00008, "ada__exceptionsS");
22248    pragma Export (C, u00009, "gnatS");
22249    pragma Export (C, u00010, "gnat__heap_sort_aB");
22250    pragma Export (C, u00011, "gnat__heap_sort_aS");
22251    pragma Export (C, u00012, "systemS");
22252    pragma Export (C, u00013, "system__exception_tableB");
22253    pragma Export (C, u00014, "system__exception_tableS");
22254    pragma Export (C, u00015, "gnat__htableB");
22255    pragma Export (C, u00016, "gnat__htableS");
22256    pragma Export (C, u00017, "system__exceptionsS");
22257    pragma Export (C, u00018, "system__machine_state_operationsB");
22258    pragma Export (C, u00019, "system__machine_state_operationsS");
22259    pragma Export (C, u00020, "system__machine_codeS");
22260    pragma Export (C, u00021, "system__storage_elementsB");
22261    pragma Export (C, u00022, "system__storage_elementsS");
22262    pragma Export (C, u00023, "system__secondary_stackB");
22263    pragma Export (C, u00024, "system__secondary_stackS");
22264    pragma Export (C, u00025, "system__parametersB");
22265    pragma Export (C, u00026, "system__parametersS");
22266    pragma Export (C, u00027, "system__soft_linksB");
22267    pragma Export (C, u00028, "system__soft_linksS");
22268    pragma Export (C, u00029, "system__stack_checkingB");
22269    pragma Export (C, u00030, "system__stack_checkingS");
22270    pragma Export (C, u00031, "system__tracebackB");
22271    pragma Export (C, u00032, "system__tracebackS");
22272    pragma Export (C, u00033, "ada__streamsS");
22273    pragma Export (C, u00034, "ada__tagsB");
22274    pragma Export (C, u00035, "ada__tagsS");
22275    pragma Export (C, u00036, "system__string_opsB");
22276    pragma Export (C, u00037, "system__string_opsS");
22277    pragma Export (C, u00038, "interfacesS");
22278    pragma Export (C, u00039, "interfaces__c_streamsB");
22279    pragma Export (C, u00040, "interfaces__c_streamsS");
22280    pragma Export (C, u00041, "system__file_ioB");
22281    pragma Export (C, u00042, "system__file_ioS");
22282    pragma Export (C, u00043, "ada__finalizationB");
22283    pragma Export (C, u00044, "ada__finalizationS");
22284    pragma Export (C, u00045, "system__finalization_rootB");
22285    pragma Export (C, u00046, "system__finalization_rootS");
22286    pragma Export (C, u00047, "system__finalization_implementationB");
22287    pragma Export (C, u00048, "system__finalization_implementationS");
22288    pragma Export (C, u00049, "system__string_ops_concat_3B");
22289    pragma Export (C, u00050, "system__string_ops_concat_3S");
22290    pragma Export (C, u00051, "system__stream_attributesB");
22291    pragma Export (C, u00052, "system__stream_attributesS");
22292    pragma Export (C, u00053, "ada__io_exceptionsS");
22293    pragma Export (C, u00054, "system__unsigned_typesS");
22294    pragma Export (C, u00055, "system__file_control_blockS");
22295    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22296    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22297
22298    -- BEGIN ELABORATION ORDER
22299    -- ada (spec)
22300    -- gnat (spec)
22301    -- gnat.heap_sort_a (spec)
22302    -- gnat.heap_sort_a (body)
22303    -- gnat.htable (spec)
22304    -- gnat.htable (body)
22305    -- interfaces (spec)
22306    -- system (spec)
22307    -- system.machine_code (spec)
22308    -- system.parameters (spec)
22309    -- system.parameters (body)
22310    -- interfaces.c_streams (spec)
22311    -- interfaces.c_streams (body)
22312    -- system.standard_library (spec)
22313    -- ada.exceptions (spec)
22314    -- system.exception_table (spec)
22315    -- system.exception_table (body)
22316    -- ada.io_exceptions (spec)
22317    -- system.exceptions (spec)
22318    -- system.storage_elements (spec)
22319    -- system.storage_elements (body)
22320    -- system.machine_state_operations (spec)
22321    -- system.machine_state_operations (body)
22322    -- system.secondary_stack (spec)
22323    -- system.stack_checking (spec)
22324    -- system.soft_links (spec)
22325    -- system.soft_links (body)
22326    -- system.stack_checking (body)
22327    -- system.secondary_stack (body)
22328    -- system.standard_library (body)
22329    -- system.string_ops (spec)
22330    -- system.string_ops (body)
22331    -- ada.tags (spec)
22332    -- ada.tags (body)
22333    -- ada.streams (spec)
22334    -- system.finalization_root (spec)
22335    -- system.finalization_root (body)
22336    -- system.string_ops_concat_3 (spec)
22337    -- system.string_ops_concat_3 (body)
22338    -- system.traceback (spec)
22339    -- system.traceback (body)
22340    -- ada.exceptions (body)
22341    -- system.unsigned_types (spec)
22342    -- system.stream_attributes (spec)
22343    -- system.stream_attributes (body)
22344    -- system.finalization_implementation (spec)
22345    -- system.finalization_implementation (body)
22346    -- ada.finalization (spec)
22347    -- ada.finalization (body)
22348    -- ada.finalization.list_controller (spec)
22349    -- ada.finalization.list_controller (body)
22350    -- system.file_control_block (spec)
22351    -- system.file_io (spec)
22352    -- system.file_io (body)
22353    -- ada.text_io (spec)
22354    -- ada.text_io (body)
22355    -- hello (body)
22356    -- END ELABORATION ORDER
22357
22358 end ada_main;
22359
22360 --  The following source file name pragmas allow the generated file
22361 --  names to be unique for different main programs. They are needed
22362 --  since the package name will always be Ada_Main.
22363
22364 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22365 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22366
22367 --  Generated package body for Ada_Main starts here
22368
22369 package body ada_main is
22370
22371    --  The actual finalization is performed by calling the
22372    --  library routine in System.Standard_Library.Adafinal
22373
22374    procedure Do_Finalize;
22375    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22376
22377    -------------
22378    -- adainit --
22379    -------------
22380
22381 @findex adainit
22382    procedure adainit is
22383
22384       --  These booleans are set to True once the associated unit has
22385       --  been elaborated. It is also used to avoid elaborating the
22386       --  same unit twice.
22387
22388       E040 : Boolean;
22389       pragma Import (Ada, E040, "interfaces__c_streams_E");
22390
22391       E008 : Boolean;
22392       pragma Import (Ada, E008, "ada__exceptions_E");
22393
22394       E014 : Boolean;
22395       pragma Import (Ada, E014, "system__exception_table_E");
22396
22397       E053 : Boolean;
22398       pragma Import (Ada, E053, "ada__io_exceptions_E");
22399
22400       E017 : Boolean;
22401       pragma Import (Ada, E017, "system__exceptions_E");
22402
22403       E024 : Boolean;
22404       pragma Import (Ada, E024, "system__secondary_stack_E");
22405
22406       E030 : Boolean;
22407       pragma Import (Ada, E030, "system__stack_checking_E");
22408
22409       E028 : Boolean;
22410       pragma Import (Ada, E028, "system__soft_links_E");
22411
22412       E035 : Boolean;
22413       pragma Import (Ada, E035, "ada__tags_E");
22414
22415       E033 : Boolean;
22416       pragma Import (Ada, E033, "ada__streams_E");
22417
22418       E046 : Boolean;
22419       pragma Import (Ada, E046, "system__finalization_root_E");
22420
22421       E048 : Boolean;
22422       pragma Import (Ada, E048, "system__finalization_implementation_E");
22423
22424       E044 : Boolean;
22425       pragma Import (Ada, E044, "ada__finalization_E");
22426
22427       E057 : Boolean;
22428       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22429
22430       E055 : Boolean;
22431       pragma Import (Ada, E055, "system__file_control_block_E");
22432
22433       E042 : Boolean;
22434       pragma Import (Ada, E042, "system__file_io_E");
22435
22436       E006 : Boolean;
22437       pragma Import (Ada, E006, "ada__text_io_E");
22438
22439       --  Set_Globals is a library routine that stores away the
22440       --  value of the indicated set of global values in global
22441       --  variables within the library.
22442
22443       procedure Set_Globals
22444         (Main_Priority            : Integer;
22445          Time_Slice_Value         : Integer;
22446          WC_Encoding              : Character;
22447          Locking_Policy           : Character;
22448          Queuing_Policy           : Character;
22449          Task_Dispatching_Policy  : Character;
22450          Adafinal                 : System.Address;
22451          Unreserve_All_Interrupts : Integer;
22452          Exception_Tracebacks     : Integer);
22453 @findex __gnat_set_globals
22454       pragma Import (C, Set_Globals, "__gnat_set_globals");
22455
22456       --  SDP_Table_Build is a library routine used to build the
22457       --  exception tables. See unit Ada.Exceptions in files
22458       --  a-except.ads/adb for full details of how zero cost
22459       --  exception handling works. This procedure, the call to
22460       --  it, and the two following tables are all omitted if the
22461       --  build is in longjmp/setjmp exception mode.
22462
22463 @findex SDP_Table_Build
22464 @findex Zero Cost Exceptions
22465       procedure SDP_Table_Build
22466         (SDP_Addresses   : System.Address;
22467          SDP_Count       : Natural;
22468          Elab_Addresses  : System.Address;
22469          Elab_Addr_Count : Natural);
22470       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22471
22472       --  Table of Unit_Exception_Table addresses. Used for zero
22473       --  cost exception handling to build the top level table.
22474
22475       ST : aliased constant array (1 .. 23) of System.Address := (
22476         Hello'UET_Address,
22477         Ada.Text_Io'UET_Address,
22478         Ada.Exceptions'UET_Address,
22479         Gnat.Heap_Sort_A'UET_Address,
22480         System.Exception_Table'UET_Address,
22481         System.Machine_State_Operations'UET_Address,
22482         System.Secondary_Stack'UET_Address,
22483         System.Parameters'UET_Address,
22484         System.Soft_Links'UET_Address,
22485         System.Stack_Checking'UET_Address,
22486         System.Traceback'UET_Address,
22487         Ada.Streams'UET_Address,
22488         Ada.Tags'UET_Address,
22489         System.String_Ops'UET_Address,
22490         Interfaces.C_Streams'UET_Address,
22491         System.File_Io'UET_Address,
22492         Ada.Finalization'UET_Address,
22493         System.Finalization_Root'UET_Address,
22494         System.Finalization_Implementation'UET_Address,
22495         System.String_Ops_Concat_3'UET_Address,
22496         System.Stream_Attributes'UET_Address,
22497         System.File_Control_Block'UET_Address,
22498         Ada.Finalization.List_Controller'UET_Address);
22499
22500       --  Table of addresses of elaboration routines. Used for
22501       --  zero cost exception handling to make sure these
22502       --  addresses are included in the top level procedure
22503       --  address table.
22504
22505       EA : aliased constant array (1 .. 23) of System.Address := (
22506         adainit'Code_Address,
22507         Do_Finalize'Code_Address,
22508         Ada.Exceptions'Elab_Spec'Address,
22509         System.Exceptions'Elab_Spec'Address,
22510         Interfaces.C_Streams'Elab_Spec'Address,
22511         System.Exception_Table'Elab_Body'Address,
22512         Ada.Io_Exceptions'Elab_Spec'Address,
22513         System.Stack_Checking'Elab_Spec'Address,
22514         System.Soft_Links'Elab_Body'Address,
22515         System.Secondary_Stack'Elab_Body'Address,
22516         Ada.Tags'Elab_Spec'Address,
22517         Ada.Tags'Elab_Body'Address,
22518         Ada.Streams'Elab_Spec'Address,
22519         System.Finalization_Root'Elab_Spec'Address,
22520         Ada.Exceptions'Elab_Body'Address,
22521         System.Finalization_Implementation'Elab_Spec'Address,
22522         System.Finalization_Implementation'Elab_Body'Address,
22523         Ada.Finalization'Elab_Spec'Address,
22524         Ada.Finalization.List_Controller'Elab_Spec'Address,
22525         System.File_Control_Block'Elab_Spec'Address,
22526         System.File_Io'Elab_Body'Address,
22527         Ada.Text_Io'Elab_Spec'Address,
22528         Ada.Text_Io'Elab_Body'Address);
22529
22530    --  Start of processing for adainit
22531
22532    begin
22533
22534       --  Call SDP_Table_Build to build the top level procedure
22535       --  table for zero cost exception handling (omitted in
22536       --  longjmp/setjmp mode).
22537
22538       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22539
22540       --  Call Set_Globals to record various information for
22541       --  this partition.  The values are derived by the binder
22542       --  from information stored in the ali files by the compiler.
22543
22544 @findex __gnat_set_globals
22545       Set_Globals
22546         (Main_Priority            => -1,
22547          --  Priority of main program, -1 if no pragma Priority used
22548
22549          Time_Slice_Value         => -1,
22550          --  Time slice from Time_Slice pragma, -1 if none used
22551
22552          WC_Encoding              => 'b',
22553          --  Wide_Character encoding used, default is brackets
22554
22555          Locking_Policy           => ' ',
22556          --  Locking_Policy used, default of space means not
22557          --  specified, otherwise it is the first character of
22558          --  the policy name.
22559
22560          Queuing_Policy           => ' ',
22561          --  Queuing_Policy used, default of space means not
22562          --  specified, otherwise it is the first character of
22563          --  the policy name.
22564
22565          Task_Dispatching_Policy  => ' ',
22566          --  Task_Dispatching_Policy used, default of space means
22567          --  not specified, otherwise first character of the
22568          --  policy name.
22569
22570          Adafinal                 => System.Null_Address,
22571          --  Address of Adafinal routine, not used anymore
22572
22573          Unreserve_All_Interrupts => 0,
22574          --  Set true if pragma Unreserve_All_Interrupts was used
22575
22576          Exception_Tracebacks     => 0);
22577          --  Indicates if exception tracebacks are enabled
22578
22579       Elab_Final_Code := 1;
22580
22581       --  Now we have the elaboration calls for all units in the partition.
22582       --  The Elab_Spec and Elab_Body attributes generate references to the
22583       --  implicit elaboration procedures generated by the compiler for
22584       --  each unit that requires elaboration.
22585
22586       if not E040 then
22587          Interfaces.C_Streams'Elab_Spec;
22588       end if;
22589       E040 := True;
22590       if not E008 then
22591          Ada.Exceptions'Elab_Spec;
22592       end if;
22593       if not E014 then
22594          System.Exception_Table'Elab_Body;
22595          E014 := True;
22596       end if;
22597       if not E053 then
22598          Ada.Io_Exceptions'Elab_Spec;
22599          E053 := True;
22600       end if;
22601       if not E017 then
22602          System.Exceptions'Elab_Spec;
22603          E017 := True;
22604       end if;
22605       if not E030 then
22606          System.Stack_Checking'Elab_Spec;
22607       end if;
22608       if not E028 then
22609          System.Soft_Links'Elab_Body;
22610          E028 := True;
22611       end if;
22612       E030 := True;
22613       if not E024 then
22614          System.Secondary_Stack'Elab_Body;
22615          E024 := True;
22616       end if;
22617       if not E035 then
22618          Ada.Tags'Elab_Spec;
22619       end if;
22620       if not E035 then
22621          Ada.Tags'Elab_Body;
22622          E035 := True;
22623       end if;
22624       if not E033 then
22625          Ada.Streams'Elab_Spec;
22626          E033 := True;
22627       end if;
22628       if not E046 then
22629          System.Finalization_Root'Elab_Spec;
22630       end if;
22631       E046 := True;
22632       if not E008 then
22633          Ada.Exceptions'Elab_Body;
22634          E008 := True;
22635       end if;
22636       if not E048 then
22637          System.Finalization_Implementation'Elab_Spec;
22638       end if;
22639       if not E048 then
22640          System.Finalization_Implementation'Elab_Body;
22641          E048 := True;
22642       end if;
22643       if not E044 then
22644          Ada.Finalization'Elab_Spec;
22645       end if;
22646       E044 := True;
22647       if not E057 then
22648          Ada.Finalization.List_Controller'Elab_Spec;
22649       end if;
22650       E057 := True;
22651       if not E055 then
22652          System.File_Control_Block'Elab_Spec;
22653          E055 := True;
22654       end if;
22655       if not E042 then
22656          System.File_Io'Elab_Body;
22657          E042 := True;
22658       end if;
22659       if not E006 then
22660          Ada.Text_Io'Elab_Spec;
22661       end if;
22662       if not E006 then
22663          Ada.Text_Io'Elab_Body;
22664          E006 := True;
22665       end if;
22666
22667       Elab_Final_Code := 0;
22668    end adainit;
22669
22670    --------------
22671    -- adafinal --
22672    --------------
22673
22674 @findex adafinal
22675    procedure adafinal is
22676    begin
22677       Do_Finalize;
22678    end adafinal;
22679
22680    ----------
22681    -- main --
22682    ----------
22683
22684    --  main is actually a function, as in the ANSI C standard,
22685    --  defined to return the exit status. The three parameters
22686    --  are the argument count, argument values and environment
22687    --  pointer.
22688
22689 @findex Main Program
22690    function main
22691      (argc : Integer;
22692       argv : System.Address;
22693       envp : System.Address)
22694       return Integer
22695    is
22696       --  The initialize routine performs low level system
22697       --  initialization using a standard library routine which
22698       --  sets up signal handling and performs any other
22699       --  required setup. The routine can be found in file
22700       --  a-init.c.
22701
22702 @findex __gnat_initialize
22703       procedure initialize;
22704       pragma Import (C, initialize, "__gnat_initialize");
22705
22706       --  The finalize routine performs low level system
22707       --  finalization using a standard library routine. The
22708       --  routine is found in file a-final.c and in the standard
22709       --  distribution is a dummy routine that does nothing, so
22710       --  really this is a hook for special user finalization.
22711
22712 @findex __gnat_finalize
22713       procedure finalize;
22714       pragma Import (C, finalize, "__gnat_finalize");
22715
22716       --  We get to the main program of the partition by using
22717       --  pragma Import because if we try to with the unit and
22718       --  call it Ada style, then not only do we waste time
22719       --  recompiling it, but also, we don't really know the right
22720       --  switches (e.g.@: identifier character set) to be used
22721       --  to compile it.
22722
22723       procedure Ada_Main_Program;
22724       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22725
22726    --  Start of processing for main
22727
22728    begin
22729       --  Save global variables
22730
22731       gnat_argc := argc;
22732       gnat_argv := argv;
22733       gnat_envp := envp;
22734
22735       --  Call low level system initialization
22736
22737       Initialize;
22738
22739       --  Call our generated Ada initialization routine
22740
22741       adainit;
22742
22743       --  This is the point at which we want the debugger to get
22744       --  control
22745
22746       Break_Start;
22747
22748       --  Now we call the main program of the partition
22749
22750       Ada_Main_Program;
22751
22752       --  Perform Ada finalization
22753
22754       adafinal;
22755
22756       --  Perform low level system finalization
22757
22758       Finalize;
22759
22760       --  Return the proper exit status
22761       return (gnat_exit_status);
22762    end;
22763
22764 --  This section is entirely comments, so it has no effect on the
22765 --  compilation of the Ada_Main package. It provides the list of
22766 --  object files and linker options, as well as some standard
22767 --  libraries needed for the link. The gnatlink utility parses
22768 --  this b~hello.adb file to read these comment lines to generate
22769 --  the appropriate command line arguments for the call to the
22770 --  system linker. The BEGIN/END lines are used for sentinels for
22771 --  this parsing operation.
22772
22773 --  The exact file names will of course depend on the environment,
22774 --  host/target and location of files on the host system.
22775
22776 @findex Object file list
22777 -- BEGIN Object file/option list
22778    --   ./hello.o
22779    --   -L./
22780    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22781    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22782 -- END Object file/option list
22783
22784 end ada_main;
22785 @end smallexample
22786
22787 @noindent
22788 The Ada code in the above example is exactly what is generated by the
22789 binder. We have added comments to more clearly indicate the function
22790 of each part of the generated @code{Ada_Main} package.
22791
22792 The code is standard Ada in all respects, and can be processed by any
22793 tools that handle Ada. In particular, it is possible to use the debugger
22794 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22795 suppose that for reasons that you do not understand, your program is crashing
22796 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22797 you can place a breakpoint on the call:
22798
22799 @smallexample @c ada
22800 Ada.Text_Io'Elab_Body;
22801 @end smallexample
22802
22803 @noindent
22804 and trace the elaboration routine for this package to find out where
22805 the problem might be (more usually of course you would be debugging
22806 elaboration code in your own application).
22807
22808 @node Elaboration Order Handling in GNAT
22809 @appendix Elaboration Order Handling in GNAT
22810 @cindex Order of elaboration
22811 @cindex Elaboration control
22812
22813 @menu
22814 * Elaboration Code::
22815 * Checking the Elaboration Order::
22816 * Controlling the Elaboration Order::
22817 * Controlling Elaboration in GNAT - Internal Calls::
22818 * Controlling Elaboration in GNAT - External Calls::
22819 * Default Behavior in GNAT - Ensuring Safety::
22820 * Treatment of Pragma Elaborate::
22821 * Elaboration Issues for Library Tasks::
22822 * Mixing Elaboration Models::
22823 * What to Do If the Default Elaboration Behavior Fails::
22824 * Elaboration for Access-to-Subprogram Values::
22825 * Summary of Procedures for Elaboration Control::
22826 * Other Elaboration Order Considerations::
22827 @end menu
22828
22829 @noindent
22830 This chapter describes the handling of elaboration code in Ada and
22831 in GNAT, and discusses how the order of elaboration of program units can
22832 be controlled in GNAT, either automatically or with explicit programming
22833 features.
22834
22835 @node Elaboration Code
22836 @section Elaboration Code
22837
22838 @noindent
22839 Ada provides rather general mechanisms for executing code at elaboration
22840 time, that is to say before the main program starts executing. Such code arises
22841 in three contexts:
22842
22843 @table @asis
22844 @item Initializers for variables.
22845 Variables declared at the library level, in package specs or bodies, can
22846 require initialization that is performed at elaboration time, as in:
22847 @smallexample @c ada
22848 @cartouche
22849 Sqrt_Half : Float := Sqrt (0.5);
22850 @end cartouche
22851 @end smallexample
22852
22853 @item Package initialization code
22854 Code in a @code{BEGIN-END} section at the outer level of a package body is
22855 executed as part of the package body elaboration code.
22856
22857 @item Library level task allocators
22858 Tasks that are declared using task allocators at the library level
22859 start executing immediately and hence can execute at elaboration time.
22860 @end table
22861
22862 @noindent
22863 Subprogram calls are possible in any of these contexts, which means that
22864 any arbitrary part of the program may be executed as part of the elaboration
22865 code. It is even possible to write a program which does all its work at
22866 elaboration time, with a null main program, although stylistically this
22867 would usually be considered an inappropriate way to structure
22868 a program.
22869
22870 An important concern arises in the context of elaboration code:
22871 we have to be sure that it is executed in an appropriate order. What we
22872 have is a series of elaboration code sections, potentially one section
22873 for each unit in the program. It is important that these execute
22874 in the correct order. Correctness here means that, taking the above
22875 example of the declaration of @code{Sqrt_Half},
22876 if some other piece of
22877 elaboration code references @code{Sqrt_Half},
22878 then it must run after the
22879 section of elaboration code that contains the declaration of
22880 @code{Sqrt_Half}.
22881
22882 There would never be any order of elaboration problem if we made a rule
22883 that whenever you @code{with} a unit, you must elaborate both the spec and body
22884 of that unit before elaborating the unit doing the @code{with}'ing:
22885
22886 @smallexample @c ada
22887 @group
22888 @cartouche
22889 with Unit_1;
22890 package Unit_2 is @dots{}
22891 @end cartouche
22892 @end group
22893 @end smallexample
22894
22895 @noindent
22896 would require that both the body and spec of @code{Unit_1} be elaborated
22897 before the spec of @code{Unit_2}. However, a rule like that would be far too
22898 restrictive. In particular, it would make it impossible to have routines
22899 in separate packages that were mutually recursive.
22900
22901 You might think that a clever enough compiler could look at the actual
22902 elaboration code and determine an appropriate correct order of elaboration,
22903 but in the general case, this is not possible. Consider the following
22904 example.
22905
22906 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22907 that references
22908 the variable @code{Sqrt_1}, which is declared in the elaboration code
22909 of the body of @code{Unit_1}:
22910
22911 @smallexample @c ada
22912 @cartouche
22913 Sqrt_1 : Float := Sqrt (0.1);
22914 @end cartouche
22915 @end smallexample
22916
22917 @noindent
22918 The elaboration code of the body of @code{Unit_1} also contains:
22919
22920 @smallexample @c ada
22921 @group
22922 @cartouche
22923 if expression_1 = 1 then
22924    Q := Unit_2.Func_2;
22925 end if;
22926 @end cartouche
22927 @end group
22928 @end smallexample
22929
22930 @noindent
22931 @code{Unit_2} is exactly parallel,
22932 it has a procedure @code{Func_2} that references
22933 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22934 the body @code{Unit_2}:
22935
22936 @smallexample @c ada
22937 @cartouche
22938 Sqrt_2 : Float := Sqrt (0.1);
22939 @end cartouche
22940 @end smallexample
22941
22942 @noindent
22943 The elaboration code of the body of @code{Unit_2} also contains:
22944
22945 @smallexample @c ada
22946 @group
22947 @cartouche
22948 if expression_2 = 2 then
22949    Q := Unit_1.Func_1;
22950 end if;
22951 @end cartouche
22952 @end group
22953 @end smallexample
22954
22955 @noindent
22956 Now the question is, which of the following orders of elaboration is
22957 acceptable:
22958
22959 @smallexample
22960 @group
22961 Spec of Unit_1
22962 Spec of Unit_2
22963 Body of Unit_1
22964 Body of Unit_2
22965 @end group
22966 @end smallexample
22967
22968 @noindent
22969 or
22970
22971 @smallexample
22972 @group
22973 Spec of Unit_2
22974 Spec of Unit_1
22975 Body of Unit_2
22976 Body of Unit_1
22977 @end group
22978 @end smallexample
22979
22980 @noindent
22981 If you carefully analyze the flow here, you will see that you cannot tell
22982 at compile time the answer to this question.
22983 If @code{expression_1} is not equal to 1,
22984 and @code{expression_2} is not equal to 2,
22985 then either order is acceptable, because neither of the function calls is
22986 executed. If both tests evaluate to true, then neither order is acceptable
22987 and in fact there is no correct order.
22988
22989 If one of the two expressions is true, and the other is false, then one
22990 of the above orders is correct, and the other is incorrect. For example,
22991 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22992 then the call to @code{Func_1}
22993 will occur, but not the call to @code{Func_2.}
22994 This means that it is essential
22995 to elaborate the body of @code{Unit_1} before
22996 the body of @code{Unit_2}, so the first
22997 order of elaboration is correct and the second is wrong.
22998
22999 By making @code{expression_1} and @code{expression_2}
23000 depend on input data, or perhaps
23001 the time of day, we can make it impossible for the compiler or binder
23002 to figure out which of these expressions will be true, and hence it
23003 is impossible to guarantee a safe order of elaboration at run time.
23004
23005 @node Checking the Elaboration Order
23006 @section Checking the Elaboration Order
23007
23008 @noindent
23009 In some languages that involve the same kind of elaboration problems,
23010 e.g.@: Java and C++, the programmer is expected to worry about these
23011 ordering problems himself, and it is common to
23012 write a program in which an incorrect elaboration order  gives
23013 surprising results, because it references variables before they
23014 are initialized.
23015 Ada is designed to be a safe language, and a programmer-beware approach is
23016 clearly not sufficient. Consequently, the language provides three lines
23017 of defense:
23018
23019 @table @asis
23020 @item Standard rules
23021 Some standard rules restrict the possible choice of elaboration
23022 order. In particular, if you @code{with} a unit, then its spec is always
23023 elaborated before the unit doing the @code{with}. Similarly, a parent
23024 spec is always elaborated before the child spec, and finally
23025 a spec is always elaborated before its corresponding body.
23026
23027 @item Dynamic elaboration checks
23028 @cindex Elaboration checks
23029 @cindex Checks, elaboration
23030 Dynamic checks are made at run time, so that if some entity is accessed
23031 before it is elaborated (typically  by means of a subprogram call)
23032 then the exception (@code{Program_Error}) is raised.
23033
23034 @item Elaboration control
23035 Facilities are provided for the programmer to specify the desired order
23036 of elaboration.
23037 @end table
23038
23039 Let's look at these facilities in more detail. First, the rules for
23040 dynamic checking. One possible rule would be simply to say that the
23041 exception is raised if you access a variable which has not yet been
23042 elaborated. The trouble with this approach is that it could require
23043 expensive checks on every variable reference. Instead Ada has two
23044 rules which are a little more restrictive, but easier to check, and
23045 easier to state:
23046
23047 @table @asis
23048 @item Restrictions on calls
23049 A subprogram can only be called at elaboration time if its body
23050 has been elaborated. The rules for elaboration given above guarantee
23051 that the spec of the subprogram has been elaborated before the
23052 call, but not the body. If this rule is violated, then the
23053 exception @code{Program_Error} is raised.
23054
23055 @item Restrictions on instantiations
23056 A generic unit can only be instantiated if the body of the generic
23057 unit has been elaborated. Again, the rules for elaboration given above
23058 guarantee that the spec of the generic unit has been elaborated
23059 before the instantiation, but not the body. If this rule is
23060 violated, then the exception @code{Program_Error} is raised.
23061 @end table
23062
23063 @noindent
23064 The idea is that if the body has been elaborated, then any variables
23065 it references must have been elaborated; by checking for the body being
23066 elaborated we guarantee that none of its references causes any
23067 trouble. As we noted above, this is a little too restrictive, because a
23068 subprogram that has no non-local references in its body may in fact be safe
23069 to call. However, it really would be unsafe to rely on this, because
23070 it would mean that the caller was aware of details of the implementation
23071 in the body. This goes against the basic tenets of Ada.
23072
23073 A plausible implementation can be described as follows.
23074 A Boolean variable is associated with each subprogram
23075 and each generic unit. This variable is initialized to False, and is set to
23076 True at the point body is elaborated. Every call or instantiation checks the
23077 variable, and raises @code{Program_Error} if the variable is False.
23078
23079 Note that one might think that it would be good enough to have one Boolean
23080 variable for each package, but that would not deal with cases of trying
23081 to call a body in the same package as the call
23082 that has not been elaborated yet.
23083 Of course a compiler may be able to do enough analysis to optimize away
23084 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23085 does such optimizations, but still the easiest conceptual model is to
23086 think of there being one variable per subprogram.
23087
23088 @node Controlling the Elaboration Order
23089 @section Controlling the Elaboration Order
23090
23091 @noindent
23092 In the previous section we discussed the rules in Ada which ensure
23093 that @code{Program_Error} is raised if an incorrect elaboration order is
23094 chosen. This prevents erroneous executions, but we need mechanisms to
23095 specify a correct execution and avoid the exception altogether.
23096 To achieve this, Ada provides a number of features for controlling
23097 the order of elaboration. We discuss these features in this section.
23098
23099 First, there are several ways of indicating to the compiler that a given
23100 unit has no elaboration problems:
23101
23102 @table @asis
23103 @item packages that do not require a body
23104 A library package that does not require a body does not permit
23105 a body (this rule was introduced in Ada 95).
23106 Thus if we have a such a package, as in:
23107
23108 @smallexample @c ada
23109 @group
23110 @cartouche
23111 package Definitions is
23112    generic
23113       type m is new integer;
23114    package Subp is
23115       type a is array (1 .. 10) of m;
23116       type b is array (1 .. 20) of m;
23117    end Subp;
23118 end Definitions;
23119 @end cartouche
23120 @end group
23121 @end smallexample
23122
23123 @noindent
23124 A package that @code{with}'s @code{Definitions} may safely instantiate
23125 @code{Definitions.Subp} because the compiler can determine that there
23126 definitely is no package body to worry about in this case
23127
23128 @item pragma Pure
23129 @cindex pragma Pure
23130 @findex Pure
23131 Places sufficient restrictions on a unit to guarantee that
23132 no call to any subprogram in the unit can result in an
23133 elaboration problem. This means that the compiler does not need
23134 to worry about the point of elaboration of such units, and in
23135 particular, does not need to check any calls to any subprograms
23136 in this unit.
23137
23138 @item pragma Preelaborate
23139 @findex Preelaborate
23140 @cindex pragma Preelaborate
23141 This pragma places slightly less stringent restrictions on a unit than
23142 does pragma Pure,
23143 but these restrictions are still sufficient to ensure that there
23144 are no elaboration problems with any calls to the unit.
23145
23146 @item pragma Elaborate_Body
23147 @findex Elaborate_Body
23148 @cindex pragma Elaborate_Body
23149 This pragma requires that the body of a unit be elaborated immediately
23150 after its spec. Suppose a unit @code{A} has such a pragma,
23151 and unit @code{B} does
23152 a @code{with} of unit @code{A}. Recall that the standard rules require
23153 the spec of unit @code{A}
23154 to be elaborated before the @code{with}'ing unit; given the pragma in
23155 @code{A}, we also know that the body of @code{A}
23156 will be elaborated before @code{B}, so
23157 that calls to @code{A} are safe and do not need a check.
23158 @end table
23159
23160 @noindent
23161 Note that,
23162 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23163 the use of
23164 @code{Elaborate_Body} does not guarantee that the program is
23165 free of elaboration problems, because it may not be possible
23166 to satisfy the requested elaboration order.
23167 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23168 If a programmer
23169 marks @code{Unit_1} as @code{Elaborate_Body},
23170 and not @code{Unit_2,} then the order of
23171 elaboration will be:
23172
23173 @smallexample
23174 @group
23175 Spec of Unit_2
23176 Spec of Unit_1
23177 Body of Unit_1
23178 Body of Unit_2
23179 @end group
23180 @end smallexample
23181
23182 @noindent
23183 Now that means that the call to @code{Func_1} in @code{Unit_2}
23184 need not be checked,
23185 it must be safe. But the call to @code{Func_2} in
23186 @code{Unit_1} may still fail if
23187 @code{Expression_1} is equal to 1,
23188 and the programmer must still take
23189 responsibility for this not being the case.
23190
23191 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23192 eliminated, except for calls entirely within a body, which are
23193 in any case fully under programmer control. However, using the pragma
23194 everywhere is not always possible.
23195 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23196 we marked both of them as having pragma @code{Elaborate_Body}, then
23197 clearly there would be no possible elaboration order.
23198
23199 The above pragmas allow a server to guarantee safe use by clients, and
23200 clearly this is the preferable approach. Consequently a good rule
23201 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23202 and if this is not possible,
23203 mark them as @code{Elaborate_Body} if possible.
23204 As we have seen, there are situations where neither of these
23205 three pragmas can be used.
23206 So we also provide methods for clients to control the
23207 order of elaboration of the servers on which they depend:
23208
23209 @table @asis
23210 @item pragma Elaborate (unit)
23211 @findex Elaborate
23212 @cindex pragma Elaborate
23213 This pragma is placed in the context clause, after a @code{with} clause,
23214 and it requires that the body of the named unit be elaborated before
23215 the unit in which the pragma occurs. The idea is to use this pragma
23216 if the current unit calls at elaboration time, directly or indirectly,
23217 some subprogram in the named unit.
23218
23219 @item pragma Elaborate_All (unit)
23220 @findex Elaborate_All
23221 @cindex pragma Elaborate_All
23222 This is a stronger version of the Elaborate pragma. Consider the
23223 following example:
23224
23225 @smallexample
23226 Unit A @code{with}'s unit B and calls B.Func in elab code
23227 Unit B @code{with}'s unit C, and B.Func calls C.Func
23228 @end smallexample
23229
23230 @noindent
23231 Now if we put a pragma @code{Elaborate (B)}
23232 in unit @code{A}, this ensures that the
23233 body of @code{B} is elaborated before the call, but not the
23234 body of @code{C}, so
23235 the call to @code{C.Func} could still cause @code{Program_Error} to
23236 be raised.
23237
23238 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23239 not only that the body of the named unit be elaborated before the
23240 unit doing the @code{with}, but also the bodies of all units that the
23241 named unit uses, following @code{with} links transitively. For example,
23242 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23243 then it requires
23244 not only that the body of @code{B} be elaborated before @code{A},
23245 but also the
23246 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23247 @end table
23248
23249 @noindent
23250 We are now in a position to give a usage rule in Ada for avoiding
23251 elaboration problems, at least if dynamic dispatching and access to
23252 subprogram values are not used. We will handle these cases separately
23253 later.
23254
23255 The rule is simple. If a unit has elaboration code that can directly or
23256 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23257 a generic package in a @code{with}'ed unit,
23258 then if the @code{with}'ed unit does not have
23259 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23260 a pragma @code{Elaborate_All}
23261 for the @code{with}'ed unit. By following this rule a client is
23262 assured that calls can be made without risk of an exception.
23263
23264 For generic subprogram instantiations, the rule can be relaxed to
23265 require only a pragma @code{Elaborate} since elaborating the body
23266 of a subprogram cannot cause any transitive elaboration (we are
23267 not calling the subprogram in this case, just elaborating its
23268 declaration).
23269
23270 If this rule is not followed, then a program may be in one of four
23271 states:
23272
23273 @table @asis
23274 @item No order exists
23275 No order of elaboration exists which follows the rules, taking into
23276 account any @code{Elaborate}, @code{Elaborate_All},
23277 or @code{Elaborate_Body} pragmas. In
23278 this case, an Ada compiler must diagnose the situation at bind
23279 time, and refuse to build an executable program.
23280
23281 @item One or more orders exist, all incorrect
23282 One or more acceptable elaboration orders exist, and all of them
23283 generate an elaboration order problem. In this case, the binder
23284 can build an executable program, but @code{Program_Error} will be raised
23285 when the program is run.
23286
23287 @item Several orders exist, some right, some incorrect
23288 One or more acceptable elaboration orders exists, and some of them
23289 work, and some do not. The programmer has not controlled
23290 the order of elaboration, so the binder may or may not pick one of
23291 the correct orders, and the program may or may not raise an
23292 exception when it is run. This is the worst case, because it means
23293 that the program may fail when moved to another compiler, or even
23294 another version of the same compiler.
23295
23296 @item One or more orders exists, all correct
23297 One ore more acceptable elaboration orders exist, and all of them
23298 work. In this case the program runs successfully. This state of
23299 affairs can be guaranteed by following the rule we gave above, but
23300 may be true even if the rule is not followed.
23301 @end table
23302
23303 @noindent
23304 Note that one additional advantage of following our rules on the use
23305 of @code{Elaborate} and @code{Elaborate_All}
23306 is that the program continues to stay in the ideal (all orders OK) state
23307 even if maintenance
23308 changes some bodies of some units. Conversely, if a program that does
23309 not follow this rule happens to be safe at some point, this state of affairs
23310 may deteriorate silently as a result of maintenance changes.
23311
23312 You may have noticed that the above discussion did not mention
23313 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23314 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23315 code in the body makes calls to some other unit, so it is still necessary
23316 to use @code{Elaborate_All} on such units.
23317
23318 @node Controlling Elaboration in GNAT - Internal Calls
23319 @section Controlling Elaboration in GNAT - Internal Calls
23320
23321 @noindent
23322 In the case of internal calls, i.e., calls within a single package, the
23323 programmer has full control over the order of elaboration, and it is up
23324 to the programmer to elaborate declarations in an appropriate order. For
23325 example writing:
23326
23327 @smallexample @c ada
23328 @group
23329 @cartouche
23330 function One return Float;
23331
23332 Q : Float := One;
23333
23334 function One return Float is
23335 begin
23336      return 1.0;
23337 end One;
23338 @end cartouche
23339 @end group
23340 @end smallexample
23341
23342 @noindent
23343 will obviously raise @code{Program_Error} at run time, because function
23344 One will be called before its body is elaborated. In this case GNAT will
23345 generate a warning that the call will raise @code{Program_Error}:
23346
23347 @smallexample
23348 @group
23349 @cartouche
23350  1. procedure y is
23351  2.    function One return Float;
23352  3.
23353  4.    Q : Float := One;
23354                     |
23355     >>> warning: cannot call "One" before body is elaborated
23356     >>> warning: Program_Error will be raised at run time
23357
23358  5.
23359  6.    function One return Float is
23360  7.    begin
23361  8.         return 1.0;
23362  9.    end One;
23363 10.
23364 11. begin
23365 12.    null;
23366 13. end;
23367 @end cartouche
23368 @end group
23369 @end smallexample
23370
23371 @noindent
23372 Note that in this particular case, it is likely that the call is safe, because
23373 the function @code{One} does not access any global variables.
23374 Nevertheless in Ada, we do not want the validity of the check to depend on
23375 the contents of the body (think about the separate compilation case), so this
23376 is still wrong, as we discussed in the previous sections.
23377
23378 The error is easily corrected by rearranging the declarations so that the
23379 body of @code{One} appears before the declaration containing the call
23380 (note that in Ada 95 and Ada 2005,
23381 declarations can appear in any order, so there is no restriction that
23382 would prevent this reordering, and if we write:
23383
23384 @smallexample @c ada
23385 @group
23386 @cartouche
23387 function One return Float;
23388
23389 function One return Float is
23390 begin
23391      return 1.0;
23392 end One;
23393
23394 Q : Float := One;
23395 @end cartouche
23396 @end group
23397 @end smallexample
23398
23399 @noindent
23400 then all is well, no warning is generated, and no
23401 @code{Program_Error} exception
23402 will be raised.
23403 Things are more complicated when a chain of subprograms is executed:
23404
23405 @smallexample @c ada
23406 @group
23407 @cartouche
23408 function A return Integer;
23409 function B return Integer;
23410 function C return Integer;
23411
23412 function B return Integer is begin return A; end;
23413 function C return Integer is begin return B; end;
23414
23415 X : Integer := C;
23416
23417 function A return Integer is begin return 1; end;
23418 @end cartouche
23419 @end group
23420 @end smallexample
23421
23422 @noindent
23423 Now the call to @code{C}
23424 at elaboration time in the declaration of @code{X} is correct, because
23425 the body of @code{C} is already elaborated,
23426 and the call to @code{B} within the body of
23427 @code{C} is correct, but the call
23428 to @code{A} within the body of @code{B} is incorrect, because the body
23429 of @code{A} has not been elaborated, so @code{Program_Error}
23430 will be raised on the call to @code{A}.
23431 In this case GNAT will generate a
23432 warning that @code{Program_Error} may be
23433 raised at the point of the call. Let's look at the warning:
23434
23435 @smallexample
23436 @group
23437 @cartouche
23438  1. procedure x is
23439  2.    function A return Integer;
23440  3.    function B return Integer;
23441  4.    function C return Integer;
23442  5.
23443  6.    function B return Integer is begin return A; end;
23444                                                     |
23445     >>> warning: call to "A" before body is elaborated may
23446                  raise Program_Error
23447     >>> warning: "B" called at line 7
23448     >>> warning: "C" called at line 9
23449
23450  7.    function C return Integer is begin return B; end;
23451  8.
23452  9.    X : Integer := C;
23453 10.
23454 11.    function A return Integer is begin return 1; end;
23455 12.
23456 13. begin
23457 14.    null;
23458 15. end;
23459 @end cartouche
23460 @end group
23461 @end smallexample
23462
23463 @noindent
23464 Note that the message here says ``may raise'', instead of the direct case,
23465 where the message says ``will be raised''. That's because whether
23466 @code{A} is
23467 actually called depends in general on run-time flow of control.
23468 For example, if the body of @code{B} said
23469
23470 @smallexample @c ada
23471 @group
23472 @cartouche
23473 function B return Integer is
23474 begin
23475    if some-condition-depending-on-input-data then
23476       return A;
23477    else
23478       return 1;
23479    end if;
23480 end B;
23481 @end cartouche
23482 @end group
23483 @end smallexample
23484
23485 @noindent
23486 then we could not know until run time whether the incorrect call to A would
23487 actually occur, so @code{Program_Error} might
23488 or might not be raised. It is possible for a compiler to
23489 do a better job of analyzing bodies, to
23490 determine whether or not @code{Program_Error}
23491 might be raised, but it certainly
23492 couldn't do a perfect job (that would require solving the halting problem
23493 and is provably impossible), and because this is a warning anyway, it does
23494 not seem worth the effort to do the analysis. Cases in which it
23495 would be relevant are rare.
23496
23497 In practice, warnings of either of the forms given
23498 above will usually correspond to
23499 real errors, and should be examined carefully and eliminated.
23500 In the rare case where a warning is bogus, it can be suppressed by any of
23501 the following methods:
23502
23503 @itemize @bullet
23504 @item
23505 Compile with the @option{-gnatws} switch set
23506
23507 @item
23508 Suppress @code{Elaboration_Check} for the called subprogram
23509
23510 @item
23511 Use pragma @code{Warnings_Off} to turn warnings off for the call
23512 @end itemize
23513
23514 @noindent
23515 For the internal elaboration check case,
23516 GNAT by default generates the
23517 necessary run-time checks to ensure
23518 that @code{Program_Error} is raised if any
23519 call fails an elaboration check. Of course this can only happen if a
23520 warning has been issued as described above. The use of pragma
23521 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23522 some of these checks, meaning that it may be possible (but is not
23523 guaranteed) for a program to be able to call a subprogram whose body
23524 is not yet elaborated, without raising a @code{Program_Error} exception.
23525
23526 @node Controlling Elaboration in GNAT - External Calls
23527 @section Controlling Elaboration in GNAT - External Calls
23528
23529 @noindent
23530 The previous section discussed the case in which the execution of a
23531 particular thread of elaboration code occurred entirely within a
23532 single unit. This is the easy case to handle, because a programmer
23533 has direct and total control over the order of elaboration, and
23534 furthermore, checks need only be generated in cases which are rare
23535 and which the compiler can easily detect.
23536 The situation is more complex when separate compilation is taken into account.
23537 Consider the following:
23538
23539 @smallexample @c ada
23540 @cartouche
23541 @group
23542 package Math is
23543    function Sqrt (Arg : Float) return Float;
23544 end Math;
23545
23546 package body Math is
23547    function Sqrt (Arg : Float) return Float is
23548    begin
23549          @dots{}
23550    end Sqrt;
23551 end Math;
23552 @end group
23553 @group
23554 with Math;
23555 package Stuff is
23556    X : Float := Math.Sqrt (0.5);
23557 end Stuff;
23558
23559 with Stuff;
23560 procedure Main is
23561 begin
23562    @dots{}
23563 end Main;
23564 @end group
23565 @end cartouche
23566 @end smallexample
23567
23568 @noindent
23569 where @code{Main} is the main program. When this program is executed, the
23570 elaboration code must first be executed, and one of the jobs of the
23571 binder is to determine the order in which the units of a program are
23572 to be elaborated. In this case we have four units: the spec and body
23573 of @code{Math},
23574 the spec of @code{Stuff} and the body of @code{Main}).
23575 In what order should the four separate sections of elaboration code
23576 be executed?
23577
23578 There are some restrictions in the order of elaboration that the binder
23579 can choose. In particular, if unit U has a @code{with}
23580 for a package @code{X}, then you
23581 are assured that the spec of @code{X}
23582 is elaborated before U , but you are
23583 not assured that the body of @code{X}
23584 is elaborated before U.
23585 This means that in the above case, the binder is allowed to choose the
23586 order:
23587
23588 @smallexample
23589 spec of Math
23590 spec of Stuff
23591 body of Math
23592 body of Main
23593 @end smallexample
23594
23595 @noindent
23596 but that's not good, because now the call to @code{Math.Sqrt}
23597 that happens during
23598 the elaboration of the @code{Stuff}
23599 spec happens before the body of @code{Math.Sqrt} is
23600 elaborated, and hence causes @code{Program_Error} exception to be raised.
23601 At first glance, one might say that the binder is misbehaving, because
23602 obviously you want to elaborate the body of something you @code{with}
23603 first, but
23604 that is not a general rule that can be followed in all cases. Consider
23605
23606 @smallexample @c ada
23607 @group
23608 @cartouche
23609 package X is @dots{}
23610
23611 package Y is @dots{}
23612
23613 with X;
23614 package body Y is @dots{}
23615
23616 with Y;
23617 package body X is @dots{}
23618 @end cartouche
23619 @end group
23620 @end smallexample
23621
23622 @noindent
23623 This is a common arrangement, and, apart from the order of elaboration
23624 problems that might arise in connection with elaboration code, this works fine.
23625 A rule that says that you must first elaborate the body of anything you
23626 @code{with} cannot work in this case:
23627 the body of @code{X} @code{with}'s @code{Y},
23628 which means you would have to
23629 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23630 which means
23631 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23632 loop that cannot be broken.
23633
23634 It is true that the binder can in many cases guess an order of elaboration
23635 that is unlikely to cause a @code{Program_Error}
23636 exception to be raised, and it tries to do so (in the
23637 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23638 by default
23639 elaborate the body of @code{Math} right after its spec, so all will be well).
23640
23641 However, a program that blindly relies on the binder to be helpful can
23642 get into trouble, as we discussed in the previous sections, so
23643 GNAT
23644 provides a number of facilities for assisting the programmer in
23645 developing programs that are robust with respect to elaboration order.
23646
23647 @node Default Behavior in GNAT - Ensuring Safety
23648 @section Default Behavior in GNAT - Ensuring Safety
23649
23650 @noindent
23651 The default behavior in GNAT ensures elaboration safety. In its
23652 default mode GNAT implements the
23653 rule we previously described as the right approach. Let's restate it:
23654
23655 @itemize
23656 @item
23657 @emph{If a unit has elaboration code that can directly or indirectly make a
23658 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23659 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23660 does not have pragma @code{Pure} or
23661 @code{Preelaborate}, then the client should have an
23662 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23663
23664 @emph{In the case of instantiating a generic subprogram, it is always
23665 sufficient to have only an @code{Elaborate} pragma for the
23666 @code{with}'ed unit.}
23667 @end itemize
23668
23669 @noindent
23670 By following this rule a client is assured that calls and instantiations
23671 can be made without risk of an exception.
23672
23673 In this mode GNAT traces all calls that are potentially made from
23674 elaboration code, and puts in any missing implicit @code{Elaborate}
23675 and @code{Elaborate_All} pragmas.
23676 The advantage of this approach is that no elaboration problems
23677 are possible if the binder can find an elaboration order that is
23678 consistent with these implicit @code{Elaborate} and
23679 @code{Elaborate_All} pragmas. The
23680 disadvantage of this approach is that no such order may exist.
23681
23682 If the binder does not generate any diagnostics, then it means that it has
23683 found an elaboration order that is guaranteed to be safe. However, the binder
23684 may still be relying on implicitly generated @code{Elaborate} and
23685 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23686 guaranteed.
23687
23688 If it is important to guarantee portability, then the compilations should
23689 use the
23690 @option{-gnatwl}
23691 (warn on elaboration problems) switch. This will cause warning messages
23692 to be generated indicating the missing @code{Elaborate} and
23693 @code{Elaborate_All} pragmas.
23694 Consider the following source program:
23695
23696 @smallexample @c ada
23697 @group
23698 @cartouche
23699 with k;
23700 package j is
23701   m : integer := k.r;
23702 end;
23703 @end cartouche
23704 @end group
23705 @end smallexample
23706
23707 @noindent
23708 where it is clear that there
23709 should be a pragma @code{Elaborate_All}
23710 for unit @code{k}. An implicit pragma will be generated, and it is
23711 likely that the binder will be able to honor it. However, if you want
23712 to port this program to some other Ada compiler than GNAT.
23713 it is safer to include the pragma explicitly in the source. If this
23714 unit is compiled with the
23715 @option{-gnatwl}
23716 switch, then the compiler outputs a warning:
23717
23718 @smallexample
23719 @group
23720 @cartouche
23721 1. with k;
23722 2. package j is
23723 3.   m : integer := k.r;
23724                      |
23725    >>> warning: call to "r" may raise Program_Error
23726    >>> warning: missing pragma Elaborate_All for "k"
23727
23728 4. end;
23729 @end cartouche
23730 @end group
23731 @end smallexample
23732
23733 @noindent
23734 and these warnings can be used as a guide for supplying manually
23735 the missing pragmas. It is usually a bad idea to use this warning
23736 option during development. That's because it will warn you when
23737 you need to put in a pragma, but cannot warn you when it is time
23738 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23739 unnecessary dependencies and even false circularities.
23740
23741 This default mode is more restrictive than the Ada Reference
23742 Manual, and it is possible to construct programs which will compile
23743 using the dynamic model described there, but will run into a
23744 circularity using the safer static model we have described.
23745
23746 Of course any Ada compiler must be able to operate in a mode
23747 consistent with the requirements of the Ada Reference Manual,
23748 and in particular must have the capability of implementing the
23749 standard dynamic model of elaboration with run-time checks.
23750
23751 In GNAT, this standard mode can be achieved either by the use of
23752 the @option{-gnatE} switch on the compiler (@command{gcc} or
23753 @command{gnatmake}) command, or by the use of the configuration pragma:
23754
23755 @smallexample @c ada
23756 pragma Elaboration_Checks (DYNAMIC);
23757 @end smallexample
23758
23759 @noindent
23760 Either approach will cause the unit affected to be compiled using the
23761 standard dynamic run-time elaboration checks described in the Ada
23762 Reference Manual. The static model is generally preferable, since it
23763 is clearly safer to rely on compile and link time checks rather than
23764 run-time checks. However, in the case of legacy code, it may be
23765 difficult to meet the requirements of the static model. This
23766 issue is further discussed in
23767 @ref{What to Do If the Default Elaboration Behavior Fails}.
23768
23769 Note that the static model provides a strict subset of the allowed
23770 behavior and programs of the Ada Reference Manual, so if you do
23771 adhere to the static model and no circularities exist,
23772 then you are assured that your program will
23773 work using the dynamic model, providing that you remove any
23774 pragma Elaborate statements from the source.
23775
23776 @node Treatment of Pragma Elaborate
23777 @section Treatment of Pragma Elaborate
23778 @cindex Pragma Elaborate
23779
23780 @noindent
23781 The use of @code{pragma Elaborate}
23782 should generally be avoided in Ada 95 and Ada 2005 programs,
23783 since there is no guarantee that transitive calls
23784 will be properly handled. Indeed at one point, this pragma was placed
23785 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23786
23787 Now that's a bit restrictive. In practice, the case in which
23788 @code{pragma Elaborate} is useful is when the caller knows that there
23789 are no transitive calls, or that the called unit contains all necessary
23790 transitive @code{pragma Elaborate} statements, and legacy code often
23791 contains such uses.
23792
23793 Strictly speaking the static mode in GNAT should ignore such pragmas,
23794 since there is no assurance at compile time that the necessary safety
23795 conditions are met. In practice, this would cause GNAT to be incompatible
23796 with correctly written Ada 83 code that had all necessary
23797 @code{pragma Elaborate} statements in place. Consequently, we made the
23798 decision that GNAT in its default mode will believe that if it encounters
23799 a @code{pragma Elaborate} then the programmer knows what they are doing,
23800 and it will trust that no elaboration errors can occur.
23801
23802 The result of this decision is two-fold. First to be safe using the
23803 static mode, you should remove all @code{pragma Elaborate} statements.
23804 Second, when fixing circularities in existing code, you can selectively
23805 use @code{pragma Elaborate} statements to convince the static mode of
23806 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23807 statement.
23808
23809 When using the static mode with @option{-gnatwl}, any use of
23810 @code{pragma Elaborate} will generate a warning about possible
23811 problems.
23812
23813 @node Elaboration Issues for Library Tasks
23814 @section Elaboration Issues for Library Tasks
23815 @cindex Library tasks, elaboration issues
23816 @cindex Elaboration of library tasks
23817
23818 @noindent
23819 In this section we examine special elaboration issues that arise for
23820 programs that declare library level tasks.
23821
23822 Generally the model of execution of an Ada program is that all units are
23823 elaborated, and then execution of the program starts. However, the
23824 declaration of library tasks definitely does not fit this model. The
23825 reason for this is that library tasks start as soon as they are declared
23826 (more precisely, as soon as the statement part of the enclosing package
23827 body is reached), that is to say before elaboration
23828 of the program is complete. This means that if such a task calls a
23829 subprogram, or an entry in another task, the callee may or may not be
23830 elaborated yet, and in the standard
23831 Reference Manual model of dynamic elaboration checks, you can even
23832 get timing dependent Program_Error exceptions, since there can be
23833 a race between the elaboration code and the task code.
23834
23835 The static model of elaboration in GNAT seeks to avoid all such
23836 dynamic behavior, by being conservative, and the conservative
23837 approach in this particular case is to assume that all the code
23838 in a task body is potentially executed at elaboration time if
23839 a task is declared at the library level.
23840
23841 This can definitely result in unexpected circularities. Consider
23842 the following example
23843
23844 @smallexample @c ada
23845 package Decls is
23846   task Lib_Task is
23847      entry Start;
23848   end Lib_Task;
23849
23850   type My_Int is new Integer;
23851
23852   function Ident (M : My_Int) return My_Int;
23853 end Decls;
23854
23855 with Utils;
23856 package body Decls is
23857   task body Lib_Task is
23858   begin
23859      accept Start;
23860      Utils.Put_Val (2);
23861   end Lib_Task;
23862
23863   function Ident (M : My_Int) return My_Int is
23864   begin
23865      return M;
23866   end Ident;
23867 end Decls;
23868
23869 with Decls;
23870 package Utils is
23871   procedure Put_Val (Arg : Decls.My_Int);
23872 end Utils;
23873
23874 with Text_IO;
23875 package body Utils is
23876   procedure Put_Val (Arg : Decls.My_Int) is
23877   begin
23878      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23879   end Put_Val;
23880 end Utils;
23881
23882 with Decls;
23883 procedure Main is
23884 begin
23885    Decls.Lib_Task.Start;
23886 end;
23887 @end smallexample
23888
23889 @noindent
23890 If the above example is compiled in the default static elaboration
23891 mode, then a circularity occurs. The circularity comes from the call
23892 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23893 this call occurs in elaboration code, we need an implicit pragma
23894 @code{Elaborate_All} for @code{Utils}. This means that not only must
23895 the spec and body of @code{Utils} be elaborated before the body
23896 of @code{Decls}, but also the spec and body of any unit that is
23897 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23898 the body of @code{Decls}. This is the transitive implication of
23899 pragma @code{Elaborate_All} and it makes sense, because in general
23900 the body of @code{Put_Val} might have a call to something in a
23901 @code{with'ed} unit.
23902
23903 In this case, the body of Utils (actually its spec) @code{with's}
23904 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23905 must be elaborated before itself, in case there is a call from the
23906 body of @code{Utils}.
23907
23908 Here is the exact chain of events we are worrying about:
23909
23910 @enumerate
23911 @item
23912 In the body of @code{Decls} a call is made from within the body of a library
23913 task to a subprogram in the package @code{Utils}. Since this call may
23914 occur at elaboration time (given that the task is activated at elaboration
23915 time), we have to assume the worst, i.e., that the
23916 call does happen at elaboration time.
23917
23918 @item
23919 This means that the body and spec of @code{Util} must be elaborated before
23920 the body of @code{Decls} so that this call does not cause an access before
23921 elaboration.
23922
23923 @item
23924 Within the body of @code{Util}, specifically within the body of
23925 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23926 by this package.
23927
23928 @item
23929 One such @code{with}'ed package is package @code{Decls}, so there
23930 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23931 In fact there is such a call in this example, but we would have to
23932 assume that there was such a call even if it were not there, since
23933 we are not supposed to write the body of @code{Decls} knowing what
23934 is in the body of @code{Utils}; certainly in the case of the
23935 static elaboration model, the compiler does not know what is in
23936 other bodies and must assume the worst.
23937
23938 @item
23939 This means that the spec and body of @code{Decls} must also be
23940 elaborated before we elaborate the unit containing the call, but
23941 that unit is @code{Decls}! This means that the body of @code{Decls}
23942 must be elaborated before itself, and that's a circularity.
23943 @end enumerate
23944
23945 @noindent
23946 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23947 the body of @code{Decls} you will get a true Ada Reference Manual
23948 circularity that makes the program illegal.
23949
23950 In practice, we have found that problems with the static model of
23951 elaboration in existing code often arise from library tasks, so
23952 we must address this particular situation.
23953
23954 Note that if we compile and run the program above, using the dynamic model of
23955 elaboration (that is to say use the @option{-gnatE} switch),
23956 then it compiles, binds,
23957 links, and runs, printing the expected result of 2. Therefore in some sense
23958 the circularity here is only apparent, and we need to capture
23959 the properties of this program that  distinguish it from other library-level
23960 tasks that have real elaboration problems.
23961
23962 We have four possible answers to this question:
23963
23964 @itemize @bullet
23965
23966 @item
23967 Use the dynamic model of elaboration.
23968
23969 If we use the @option{-gnatE} switch, then as noted above, the program works.
23970 Why is this? If we examine the task body, it is apparent that the task cannot
23971 proceed past the
23972 @code{accept} statement until after elaboration has been completed, because
23973 the corresponding entry call comes from the main program, not earlier.
23974 This is why the dynamic model works here. But that's really giving
23975 up on a precise analysis, and we prefer to take this approach only if we cannot
23976 solve the
23977 problem in any other manner. So let us examine two ways to reorganize
23978 the program to avoid the potential elaboration problem.
23979
23980 @item
23981 Split library tasks into separate packages.
23982
23983 Write separate packages, so that library tasks are isolated from
23984 other declarations as much as possible. Let us look at a variation on
23985 the above program.
23986
23987 @smallexample @c ada
23988 package Decls1 is
23989   task Lib_Task is
23990      entry Start;
23991   end Lib_Task;
23992 end Decls1;
23993
23994 with Utils;
23995 package body Decls1 is
23996   task body Lib_Task is
23997   begin
23998      accept Start;
23999      Utils.Put_Val (2);
24000   end Lib_Task;
24001 end Decls1;
24002
24003 package Decls2 is
24004   type My_Int is new Integer;
24005   function Ident (M : My_Int) return My_Int;
24006 end Decls2;
24007
24008 with Utils;
24009 package body Decls2 is
24010   function Ident (M : My_Int) return My_Int is
24011   begin
24012      return M;
24013   end Ident;
24014 end Decls2;
24015
24016 with Decls2;
24017 package Utils is
24018   procedure Put_Val (Arg : Decls2.My_Int);
24019 end Utils;
24020
24021 with Text_IO;
24022 package body Utils is
24023   procedure Put_Val (Arg : Decls2.My_Int) is
24024   begin
24025      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24026   end Put_Val;
24027 end Utils;
24028
24029 with Decls1;
24030 procedure Main is
24031 begin
24032    Decls1.Lib_Task.Start;
24033 end;
24034 @end smallexample
24035
24036 @noindent
24037 All we have done is to split @code{Decls} into two packages, one
24038 containing the library task, and one containing everything else. Now
24039 there is no cycle, and the program compiles, binds, links and executes
24040 using the default static model of elaboration.
24041
24042 @item
24043 Declare separate task types.
24044
24045 A significant part of the problem arises because of the use of the
24046 single task declaration form. This means that the elaboration of
24047 the task type, and the elaboration of the task itself (i.e.@: the
24048 creation of the task) happen at the same time. A good rule
24049 of style in Ada is to always create explicit task types. By
24050 following the additional step of placing task objects in separate
24051 packages from the task type declaration, many elaboration problems
24052 are avoided. Here is another modified example of the example program:
24053
24054 @smallexample @c ada
24055 package Decls is
24056   task type Lib_Task_Type is
24057      entry Start;
24058   end Lib_Task_Type;
24059
24060   type My_Int is new Integer;
24061
24062   function Ident (M : My_Int) return My_Int;
24063 end Decls;
24064
24065 with Utils;
24066 package body Decls is
24067   task body Lib_Task_Type is
24068   begin
24069      accept Start;
24070      Utils.Put_Val (2);
24071   end Lib_Task_Type;
24072
24073   function Ident (M : My_Int) return My_Int is
24074   begin
24075      return M;
24076   end Ident;
24077 end Decls;
24078
24079 with Decls;
24080 package Utils is
24081   procedure Put_Val (Arg : Decls.My_Int);
24082 end Utils;
24083
24084 with Text_IO;
24085 package body Utils is
24086   procedure Put_Val (Arg : Decls.My_Int) is
24087   begin
24088      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24089   end Put_Val;
24090 end Utils;
24091
24092 with Decls;
24093 package Declst is
24094    Lib_Task : Decls.Lib_Task_Type;
24095 end Declst;
24096
24097 with Declst;
24098 procedure Main is
24099 begin
24100    Declst.Lib_Task.Start;
24101 end;
24102 @end smallexample
24103
24104 @noindent
24105 What we have done here is to replace the @code{task} declaration in
24106 package @code{Decls} with a @code{task type} declaration. Then we
24107 introduce a separate package @code{Declst} to contain the actual
24108 task object. This separates the elaboration issues for
24109 the @code{task type}
24110 declaration, which causes no trouble, from the elaboration issues
24111 of the task object, which is also unproblematic, since it is now independent
24112 of the elaboration of  @code{Utils}.
24113 This separation of concerns also corresponds to
24114 a generally sound engineering principle of separating declarations
24115 from instances. This version of the program also compiles, binds, links,
24116 and executes, generating the expected output.
24117
24118 @item
24119 Use No_Entry_Calls_In_Elaboration_Code restriction.
24120 @cindex No_Entry_Calls_In_Elaboration_Code
24121
24122 The previous two approaches described how a program can be restructured
24123 to avoid the special problems caused by library task bodies. in practice,
24124 however, such restructuring may be difficult to apply to existing legacy code,
24125 so we must consider solutions that do not require massive rewriting.
24126
24127 Let us consider more carefully why our original sample program works
24128 under the dynamic model of elaboration. The reason is that the code
24129 in the task body blocks immediately on the @code{accept}
24130 statement. Now of course there is nothing to prohibit elaboration
24131 code from making entry calls (for example from another library level task),
24132 so we cannot tell in isolation that
24133 the task will not execute the accept statement  during elaboration.
24134
24135 However, in practice it is very unusual to see elaboration code
24136 make any entry calls, and the pattern of tasks starting
24137 at elaboration time and then immediately blocking on @code{accept} or
24138 @code{select} statements is very common. What this means is that
24139 the compiler is being too pessimistic when it analyzes the
24140 whole package body as though it might be executed at elaboration
24141 time.
24142
24143 If we know that the elaboration code contains no entry calls, (a very safe
24144 assumption most of the time, that could almost be made the default
24145 behavior), then we can compile all units of the program under control
24146 of the following configuration pragma:
24147
24148 @smallexample
24149 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24150 @end smallexample
24151
24152 @noindent
24153 This pragma can be placed in the @file{gnat.adc} file in the usual
24154 manner. If we take our original unmodified program and compile it
24155 in the presence of a @file{gnat.adc} containing the above pragma,
24156 then once again, we can compile, bind, link, and execute, obtaining
24157 the expected result. In the presence of this pragma, the compiler does
24158 not trace calls in a task body, that appear after the first @code{accept}
24159 or @code{select} statement, and therefore does not report a potential
24160 circularity in the original program.
24161
24162 The compiler will check to the extent it can that the above
24163 restriction is not violated, but it is not always possible to do a
24164 complete check at compile time, so it is important to use this
24165 pragma only if the stated restriction is in fact met, that is to say
24166 no task receives an entry call before elaboration of all units is completed.
24167
24168 @end itemize
24169
24170 @node Mixing Elaboration Models
24171 @section Mixing Elaboration Models
24172 @noindent
24173 So far, we have assumed that the entire program is either compiled
24174 using the dynamic model or static model, ensuring consistency. It
24175 is possible to mix the two models, but rules have to be followed
24176 if this mixing is done to ensure that elaboration checks are not
24177 omitted.
24178
24179 The basic rule is that @emph{a unit compiled with the static model cannot
24180 be @code{with'ed} by a unit compiled with the dynamic model}. The
24181 reason for this is that in the static model, a unit assumes that
24182 its clients guarantee to use (the equivalent of) pragma
24183 @code{Elaborate_All} so that no elaboration checks are required
24184 in inner subprograms, and this assumption is violated if the
24185 client is compiled with dynamic checks.
24186
24187 The precise rule is as follows. A unit that is compiled with dynamic
24188 checks can only @code{with} a unit that meets at least one of the
24189 following criteria:
24190
24191 @itemize @bullet
24192
24193 @item
24194 The @code{with'ed} unit is itself compiled with dynamic elaboration
24195 checks (that is with the @option{-gnatE} switch.
24196
24197 @item
24198 The @code{with'ed} unit is an internal GNAT implementation unit from
24199 the System, Interfaces, Ada, or GNAT hierarchies.
24200
24201 @item
24202 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24203
24204 @item
24205 The @code{with'ing} unit (that is the client) has an explicit pragma
24206 @code{Elaborate_All} for the @code{with'ed} unit.
24207
24208 @end itemize
24209
24210 @noindent
24211 If this rule is violated, that is if a unit with dynamic elaboration
24212 checks @code{with's} a unit that does not meet one of the above four
24213 criteria, then the binder (@code{gnatbind}) will issue a warning
24214 similar to that in the following example:
24215
24216 @smallexample
24217 warning: "x.ads" has dynamic elaboration checks and with's
24218 warning:   "y.ads" which has static elaboration checks
24219 @end smallexample
24220
24221 @noindent
24222 These warnings indicate that the rule has been violated, and that as a result
24223 elaboration checks may be missed in the resulting executable file.
24224 This warning may be suppressed using the @option{-ws} binder switch
24225 in the usual manner.
24226
24227 One useful application of this mixing rule is in the case of a subsystem
24228 which does not itself @code{with} units from the remainder of the
24229 application. In this case, the entire subsystem can be compiled with
24230 dynamic checks to resolve a circularity in the subsystem, while
24231 allowing the main application that uses this subsystem to be compiled
24232 using the more reliable default static model.
24233
24234 @node What to Do If the Default Elaboration Behavior Fails
24235 @section What to Do If the Default Elaboration Behavior Fails
24236
24237 @noindent
24238 If the binder cannot find an acceptable order, it outputs detailed
24239 diagnostics. For example:
24240 @smallexample
24241 @group
24242 @iftex
24243 @leftskip=0cm
24244 @end iftex
24245 error: elaboration circularity detected
24246 info:   "proc (body)" must be elaborated before "pack (body)"
24247 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24248 info:     recompile "pack (body)" with -gnatwl
24249 info:                             for full details
24250 info:       "proc (body)"
24251 info:         is needed by its spec:
24252 info:       "proc (spec)"
24253 info:         which is withed by:
24254 info:       "pack (body)"
24255 info:  "pack (body)" must be elaborated before "proc (body)"
24256 info:     reason: pragma Elaborate in unit "proc (body)"
24257 @end group
24258
24259 @end smallexample
24260
24261 @noindent
24262 In this case we have a cycle that the binder cannot break. On the one
24263 hand, there is an explicit pragma Elaborate in @code{proc} for
24264 @code{pack}. This means that the body of @code{pack} must be elaborated
24265 before the body of @code{proc}. On the other hand, there is elaboration
24266 code in @code{pack} that calls a subprogram in @code{proc}. This means
24267 that for maximum safety, there should really be a pragma
24268 Elaborate_All in @code{pack} for @code{proc} which would require that
24269 the body of @code{proc} be elaborated before the body of
24270 @code{pack}. Clearly both requirements cannot be satisfied.
24271 Faced with a circularity of this kind, you have three different options.
24272
24273 @table @asis
24274 @item Fix the program
24275 The most desirable option from the point of view of long-term maintenance
24276 is to rearrange the program so that the elaboration problems are avoided.
24277 One useful technique is to place the elaboration code into separate
24278 child packages. Another is to move some of the initialization code to
24279 explicitly called subprograms, where the program controls the order
24280 of initialization explicitly. Although this is the most desirable option,
24281 it may be impractical and involve too much modification, especially in
24282 the case of complex legacy code.
24283
24284 @item Perform dynamic checks
24285 If the compilations are done using the
24286 @option{-gnatE}
24287 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24288 manner. Dynamic checks are generated for all calls that could possibly result
24289 in raising an exception. With this switch, the compiler does not generate
24290 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24291 exactly as specified in the @cite{Ada Reference Manual}.
24292 The binder will generate
24293 an executable program that may or may not raise @code{Program_Error}, and then
24294 it is the programmer's job to ensure that it does not raise an exception. Note
24295 that it is important to compile all units with the switch, it cannot be used
24296 selectively.
24297
24298 @item Suppress checks
24299 The drawback of dynamic checks is that they generate a
24300 significant overhead at run time, both in space and time. If you
24301 are absolutely sure that your program cannot raise any elaboration
24302 exceptions, and you still want to use the dynamic elaboration model,
24303 then you can use the configuration pragma
24304 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24305 example this pragma could be placed in the @file{gnat.adc} file.
24306
24307 @item Suppress checks selectively
24308 When you know that certain calls or instantiations in elaboration code cannot
24309 possibly lead to an elaboration error, and the binder nevertheless complains
24310 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24311 elaboration circularities, it is possible to remove those warnings locally and
24312 obtain a program that will bind. Clearly this can be unsafe, and it is the
24313 responsibility of the programmer to make sure that the resulting program has no
24314 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24315 used with different granularity to suppress warnings and break elaboration
24316 circularities:
24317
24318 @itemize @bullet
24319 @item
24320 Place the pragma that names the called subprogram in the declarative part
24321 that contains the call.
24322
24323 @item
24324 Place the pragma in the declarative part, without naming an entity. This
24325 disables warnings on all calls in the corresponding  declarative region.
24326
24327 @item
24328 Place the pragma in the package spec that declares the called subprogram,
24329 and name the subprogram. This disables warnings on all elaboration calls to
24330 that subprogram.
24331
24332 @item
24333 Place the pragma in the package spec that declares the called subprogram,
24334 without naming any entity. This disables warnings on all elaboration calls to
24335 all subprograms declared in this spec.
24336
24337 @item Use Pragma Elaborate
24338 As previously described in section @xref{Treatment of Pragma Elaborate},
24339 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24340 that no elaboration checks are required on calls to the designated unit.
24341 There may be cases in which the caller knows that no transitive calls
24342 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24343 case where @code{pragma Elaborate_All} would cause a circularity.
24344 @end itemize
24345
24346 @noindent
24347 These five cases are listed in order of decreasing safety, and therefore
24348 require increasing programmer care in their application. Consider the
24349 following program:
24350
24351 @smallexample @c adanocomment
24352 package Pack1 is
24353   function F1 return Integer;
24354   X1 : Integer;
24355 end Pack1;
24356
24357 package Pack2 is
24358   function F2 return Integer;
24359   function Pure (x : integer) return integer;
24360   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24361   --  pragma Suppress (Elaboration_Check);              -- (4)
24362 end Pack2;
24363
24364 with Pack2;
24365 package body Pack1 is
24366   function F1 return Integer is
24367   begin
24368     return 100;
24369   end F1;
24370   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24371 begin
24372   declare
24373     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24374     --  pragma Suppress(Elaboration_Check);             -- (2)
24375   begin
24376     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24377   end;
24378 end Pack1;
24379
24380 with Pack1;
24381 package body Pack2 is
24382   function F2 return Integer is
24383   begin
24384      return Pack1.F1;
24385   end F2;
24386   function Pure (x : integer) return integer is
24387   begin
24388      return x ** 3 - 3 * x;
24389   end;
24390 end Pack2;
24391
24392 with Pack1, Ada.Text_IO;
24393 procedure Proc3 is
24394 begin
24395   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24396 end Proc3;
24397 @end smallexample
24398 In the absence of any pragmas, an attempt to bind this program produces
24399 the following diagnostics:
24400 @smallexample
24401 @group
24402 @iftex
24403 @leftskip=.5cm
24404 @end iftex
24405 error: elaboration circularity detected
24406 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24407 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24408 info:       recompile "pack1 (body)" with -gnatwl for full details
24409 info:          "pack1 (body)"
24410 info:             must be elaborated along with its spec:
24411 info:          "pack1 (spec)"
24412 info:             which is withed by:
24413 info:          "pack2 (body)"
24414 info:             which must be elaborated along with its spec:
24415 info:          "pack2 (spec)"
24416 info:             which is withed by:
24417 info:          "pack1 (body)"
24418 @end group
24419 @end smallexample
24420 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24421 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24422 F2 is safe, even though F2 calls F1, because the call appears after the
24423 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24424 remove the warning on the call. It is also possible to use pragma (2)
24425 because there are no other potentially unsafe calls in the block.
24426
24427 @noindent
24428 The call to @code{Pure} is safe because this function does not depend on the
24429 state of @code{Pack2}. Therefore any call to this function is safe, and it
24430 is correct to place pragma (3) in the corresponding package spec.
24431
24432 @noindent
24433 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24434 warnings on all calls to functions declared therein. Note that this is not
24435 necessarily safe, and requires more detailed examination of the subprogram
24436 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24437 be already elaborated.
24438 @end table
24439
24440 @noindent
24441 It is hard to generalize on which of these four approaches should be
24442 taken. Obviously if it is possible to fix the program so that the default
24443 treatment works, this is preferable, but this may not always be practical.
24444 It is certainly simple enough to use
24445 @option{-gnatE}
24446 but the danger in this case is that, even if the GNAT binder
24447 finds a correct elaboration order, it may not always do so,
24448 and certainly a binder from another Ada compiler might not. A
24449 combination of testing and analysis (for which the warnings generated
24450 with the
24451 @option{-gnatwl}
24452 switch can be useful) must be used to ensure that the program is free
24453 of errors. One switch that is useful in this testing is the
24454 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24455 switch for
24456 @code{gnatbind}.
24457 Normally the binder tries to find an order that has the best chance
24458 of avoiding elaboration problems. However, if this switch is used, the binder
24459 plays a devil's advocate role, and tries to choose the order that
24460 has the best chance of failing. If your program works even with this
24461 switch, then it has a better chance of being error free, but this is still
24462 not a guarantee.
24463
24464 For an example of this approach in action, consider the C-tests (executable
24465 tests) from the ACVC suite. If these are compiled and run with the default
24466 treatment, then all but one of them succeed without generating any error
24467 diagnostics from the binder. However, there is one test that fails, and
24468 this is not surprising, because the whole point of this test is to ensure
24469 that the compiler can handle cases where it is impossible to determine
24470 a correct order statically, and it checks that an exception is indeed
24471 raised at run time.
24472
24473 This one test must be compiled and run using the
24474 @option{-gnatE}
24475 switch, and then it passes. Alternatively, the entire suite can
24476 be run using this switch. It is never wrong to run with the dynamic
24477 elaboration switch if your code is correct, and we assume that the
24478 C-tests are indeed correct (it is less efficient, but efficiency is
24479 not a factor in running the ACVC tests.)
24480
24481 @node Elaboration for Access-to-Subprogram Values
24482 @section Elaboration for Access-to-Subprogram Values
24483 @cindex Access-to-subprogram
24484
24485 @noindent
24486 Access-to-subprogram types (introduced in Ada 95) complicate
24487 the handling of elaboration. The trouble is that it becomes
24488 impossible to tell at compile time which procedure
24489 is being called. This means that it is not possible for the binder
24490 to analyze the elaboration requirements in this case.
24491
24492 If at the point at which the access value is created
24493 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24494 the body of the subprogram is
24495 known to have been elaborated, then the access value is safe, and its use
24496 does not require a check. This may be achieved by appropriate arrangement
24497 of the order of declarations if the subprogram is in the current unit,
24498 or, if the subprogram is in another unit, by using pragma
24499 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24500 on the referenced unit.
24501
24502 If the referenced body is not known to have been elaborated at the point
24503 the access value is created, then any use of the access value must do a
24504 dynamic check, and this dynamic check will fail and raise a
24505 @code{Program_Error} exception if the body has not been elaborated yet.
24506 GNAT will generate the necessary checks, and in addition, if the
24507 @option{-gnatwl}
24508 switch is set, will generate warnings that such checks are required.
24509
24510 The use of dynamic dispatching for tagged types similarly generates
24511 a requirement for dynamic checks, and premature calls to any primitive
24512 operation of a tagged type before the body of the operation has been
24513 elaborated, will result in the raising of @code{Program_Error}.
24514
24515 @node Summary of Procedures for Elaboration Control
24516 @section Summary of Procedures for Elaboration Control
24517 @cindex Elaboration control
24518
24519 @noindent
24520 First, compile your program with the default options, using none of
24521 the special elaboration control switches. If the binder successfully
24522 binds your program, then you can be confident that, apart from issues
24523 raised by the use of access-to-subprogram types and dynamic dispatching,
24524 the program is free of elaboration errors. If it is important that the
24525 program be portable, then use the
24526 @option{-gnatwl}
24527 switch to generate warnings about missing @code{Elaborate} or
24528 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24529
24530 If the program fails to bind using the default static elaboration
24531 handling, then you can fix the program to eliminate the binder
24532 message, or recompile the entire program with the
24533 @option{-gnatE} switch to generate dynamic elaboration checks,
24534 and, if you are sure there really are no elaboration problems,
24535 use a global pragma @code{Suppress (Elaboration_Check)}.
24536
24537 @node Other Elaboration Order Considerations
24538 @section Other Elaboration Order Considerations
24539 @noindent
24540 This section has been entirely concerned with the issue of finding a valid
24541 elaboration order, as defined by the Ada Reference Manual. In a case
24542 where several elaboration orders are valid, the task is to find one
24543 of the possible valid elaboration orders (and the static model in GNAT
24544 will ensure that this is achieved).
24545
24546 The purpose of the elaboration rules in the Ada Reference Manual is to
24547 make sure that no entity is accessed before it has been elaborated. For
24548 a subprogram, this means that the spec and body must have been elaborated
24549 before the subprogram is called. For an object, this means that the object
24550 must have been elaborated before its value is read or written. A violation
24551 of either of these two requirements is an access before elaboration order,
24552 and this section has been all about avoiding such errors.
24553
24554 In the case where more than one order of elaboration is possible, in the
24555 sense that access before elaboration errors are avoided, then any one of
24556 the orders is ``correct'' in the sense that it meets the requirements of
24557 the Ada Reference Manual, and no such error occurs.
24558
24559 However, it may be the case for a given program, that there are
24560 constraints on the order of elaboration that come not from consideration
24561 of avoiding elaboration errors, but rather from extra-lingual logic
24562 requirements. Consider this example:
24563
24564 @smallexample @c ada
24565 with Init_Constants;
24566 package Constants is
24567    X : Integer := 0;
24568    Y : Integer := 0;
24569 end Constants;
24570
24571 package Init_Constants is
24572    procedure P; -- require a body
24573 end Init_Constants;
24574
24575 with Constants;
24576 package body Init_Constants is
24577    procedure P is begin null; end;
24578 begin
24579    Constants.X := 3;
24580    Constants.Y := 4;
24581 end Init_Constants;
24582
24583 with Constants;
24584 package Calc is
24585    Z : Integer := Constants.X + Constants.Y;
24586 end Calc;
24587
24588 with Calc;
24589 with Text_IO; use Text_IO;
24590 procedure Main is
24591 begin
24592    Put_Line (Calc.Z'Img);
24593 end Main;
24594 @end smallexample
24595
24596 @noindent
24597 In this example, there is more than one valid order of elaboration. For
24598 example both the following are correct orders:
24599
24600 @smallexample
24601 Init_Constants spec
24602 Constants spec
24603 Calc spec
24604 Init_Constants body
24605 Main body
24606
24607   and
24608
24609 Init_Constants spec
24610 Init_Constants body
24611 Constants spec
24612 Calc spec
24613 Main body
24614 @end smallexample
24615
24616 @noindent
24617 There is no language rule to prefer one or the other, both are correct
24618 from an order of elaboration point of view. But the programmatic effects
24619 of the two orders are very different. In the first, the elaboration routine
24620 of @code{Calc} initializes @code{Z} to zero, and then the main program
24621 runs with this value of zero. But in the second order, the elaboration
24622 routine of @code{Calc} runs after the body of Init_Constants has set
24623 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24624 runs.
24625
24626 One could perhaps by applying pretty clever non-artificial intelligence
24627 to the situation guess that it is more likely that the second order of
24628 elaboration is the one desired, but there is no formal linguistic reason
24629 to prefer one over the other. In fact in this particular case, GNAT will
24630 prefer the second order, because of the rule that bodies are elaborated
24631 as soon as possible, but it's just luck that this is what was wanted
24632 (if indeed the second order was preferred).
24633
24634 If the program cares about the order of elaboration routines in a case like
24635 this, it is important to specify the order required. In this particular
24636 case, that could have been achieved by adding to the spec of Calc:
24637
24638 @smallexample @c ada
24639 pragma Elaborate_All (Constants);
24640 @end smallexample
24641
24642 @noindent
24643 which requires that the body (if any) and spec of @code{Constants},
24644 as well as the body and spec of any unit @code{with}'ed by
24645 @code{Constants} be elaborated before @code{Calc} is elaborated.
24646
24647 Clearly no automatic method can always guess which alternative you require,
24648 and if you are working with legacy code that had constraints of this kind
24649 which were not properly specified by adding @code{Elaborate} or
24650 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24651 compilers can choose different orders.
24652
24653 However, GNAT does attempt to diagnose the common situation where there
24654 are uninitialized variables in the visible part of a package spec, and the
24655 corresponding package body has an elaboration block that directly or
24656 indirectly initialized one or more of these variables. This is the situation
24657 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24658 a warning that suggests this addition if it detects this situation.
24659
24660 The @code{gnatbind}
24661 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24662 out problems. This switch causes bodies to be elaborated as late as possible
24663 instead of as early as possible. In the example above, it would have forced
24664 the choice of the first elaboration order. If you get different results
24665 when using this switch, and particularly if one set of results is right,
24666 and one is wrong as far as you are concerned, it shows that you have some
24667 missing @code{Elaborate} pragmas. For the example above, we have the
24668 following output:
24669
24670 @smallexample
24671 gnatmake -f -q main
24672 main
24673  7
24674 gnatmake -f -q main -bargs -p
24675 main
24676  0
24677 @end smallexample
24678
24679 @noindent
24680 It is of course quite unlikely that both these results are correct, so
24681 it is up to you in a case like this to investigate the source of the
24682 difference, by looking at the two elaboration orders that are chosen,
24683 and figuring out which is correct, and then adding the necessary
24684 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24685
24686
24687
24688 @c *******************************
24689 @node Conditional Compilation
24690 @appendix Conditional Compilation
24691 @c *******************************
24692 @cindex Conditional compilation
24693
24694 @noindent
24695 It is often necessary to arrange for a single source program
24696 to serve multiple purposes, where it is compiled in different
24697 ways to achieve these different goals. Some examples of the
24698 need for this feature are
24699
24700 @itemize @bullet
24701 @item  Adapting a program to a different hardware environment
24702 @item  Adapting a program to a different target architecture
24703 @item  Turning debugging features on and off
24704 @item  Arranging for a program to compile with different compilers
24705 @end itemize
24706
24707 @noindent
24708 In C, or C++, the typical approach would be to use the preprocessor
24709 that is defined as part of the language. The Ada language does not
24710 contain such a feature. This is not an oversight, but rather a very
24711 deliberate design decision, based on the experience that overuse of
24712 the preprocessing features in C and C++ can result in programs that
24713 are extremely difficult to maintain. For example, if we have ten
24714 switches that can be on or off, this means that there are a thousand
24715 separate programs, any one of which might not even be syntactically
24716 correct, and even if syntactically correct, the resulting program
24717 might not work correctly. Testing all combinations can quickly become
24718 impossible.
24719
24720 Nevertheless, the need to tailor programs certainly exists, and in
24721 this Appendix we will discuss how this can
24722 be achieved using Ada in general, and GNAT in particular.
24723
24724 @menu
24725 * Use of Boolean Constants::
24726 * Debugging - A Special Case::
24727 * Conditionalizing Declarations::
24728 * Use of Alternative Implementations::
24729 * Preprocessing::
24730 @end menu
24731
24732 @node Use of Boolean Constants
24733 @section Use of Boolean Constants
24734
24735 @noindent
24736 In the case where the difference is simply which code
24737 sequence is executed, the cleanest solution is to use Boolean
24738 constants to control which code is executed.
24739
24740 @smallexample @c ada
24741 @group
24742 FP_Initialize_Required : constant Boolean := True;
24743 @dots{}
24744 if FP_Initialize_Required then
24745 @dots{}
24746 end if;
24747 @end group
24748 @end smallexample
24749
24750 @noindent
24751 Not only will the code inside the @code{if} statement not be executed if
24752 the constant Boolean is @code{False}, but it will also be completely
24753 deleted from the program.
24754 However, the code is only deleted after the @code{if} statement
24755 has been checked for syntactic and semantic correctness.
24756 (In contrast, with preprocessors the code is deleted before the
24757 compiler ever gets to see it, so it is not checked until the switch
24758 is turned on.)
24759 @cindex Preprocessors (contrasted with conditional compilation)
24760
24761 Typically the Boolean constants will be in a separate package,
24762 something like:
24763
24764 @smallexample @c ada
24765 @group
24766 package Config is
24767    FP_Initialize_Required : constant Boolean := True;
24768    Reset_Available        : constant Boolean := False;
24769    @dots{}
24770 end Config;
24771 @end group
24772 @end smallexample
24773
24774 @noindent
24775 The @code{Config} package exists in multiple forms for the various targets,
24776 with an appropriate script selecting the version of @code{Config} needed.
24777 Then any other unit requiring conditional compilation can do a @code{with}
24778 of @code{Config} to make the constants visible.
24779
24780
24781 @node Debugging - A Special Case
24782 @section Debugging - A Special Case
24783
24784 @noindent
24785 A common use of conditional code is to execute statements (for example
24786 dynamic checks, or output of intermediate results) under control of a
24787 debug switch, so that the debugging behavior can be turned on and off.
24788 This can be done using a Boolean constant to control whether the code
24789 is active:
24790
24791 @smallexample @c ada
24792 @group
24793 if Debugging then
24794    Put_Line ("got to the first stage!");
24795 end if;
24796 @end group
24797 @end smallexample
24798
24799 @noindent
24800 or
24801
24802 @smallexample @c ada
24803 @group
24804 if Debugging and then Temperature > 999.0 then
24805    raise Temperature_Crazy;
24806 end if;
24807 @end group
24808 @end smallexample
24809
24810 @noindent
24811 Since this is a common case, there are special features to deal with
24812 this in a convenient manner. For the case of tests, Ada 2005 has added
24813 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24814 @cindex pragma @code{Assert}
24815 on the @code{Assert} pragma that has always been available in GNAT, so this
24816 feature may be used with GNAT even if you are not using Ada 2005 features.
24817 The use of pragma @code{Assert} is described in
24818 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24819 example, the last test could be written:
24820
24821 @smallexample @c ada
24822 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24823 @end smallexample
24824
24825 @noindent
24826 or simply
24827
24828 @smallexample @c ada
24829 pragma Assert (Temperature <= 999.0);
24830 @end smallexample
24831
24832 @noindent
24833 In both cases, if assertions are active and the temperature is excessive,
24834 the exception @code{Assert_Failure} will be raised, with the given string in
24835 the first case or a string indicating the location of the pragma in the second
24836 case used as the exception message.
24837
24838 You can turn assertions on and off by using the @code{Assertion_Policy}
24839 pragma.
24840 @cindex pragma @code{Assertion_Policy}
24841 This is an Ada 2005 pragma which is implemented in all modes by
24842 GNAT, but only in the latest versions of GNAT which include Ada 2005
24843 capability. Alternatively, you can use the @option{-gnata} switch
24844 @cindex @option{-gnata} switch
24845 to enable assertions from the command line (this is recognized by all versions
24846 of GNAT).
24847
24848 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24849 @code{Debug} can be used:
24850 @cindex pragma @code{Debug}
24851
24852 @smallexample @c ada
24853 pragma Debug (Put_Line ("got to the first stage!"));
24854 @end smallexample
24855
24856 @noindent
24857 If debug pragmas are enabled, the argument, which must be of the form of
24858 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24859 Only one call can be present, but of course a special debugging procedure
24860 containing any code you like can be included in the program and then
24861 called in a pragma @code{Debug} argument as needed.
24862
24863 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24864 construct is that pragma @code{Debug} can appear in declarative contexts,
24865 such as at the very beginning of a procedure, before local declarations have
24866 been elaborated.
24867
24868 Debug pragmas are enabled using either the @option{-gnata} switch that also
24869 controls assertions, or with a separate Debug_Policy pragma.
24870 @cindex pragma @code{Debug_Policy}
24871 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24872 in Ada 95 and Ada 83 programs as well), and is analogous to
24873 pragma @code{Assertion_Policy} to control assertions.
24874
24875 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24876 and thus they can appear in @file{gnat.adc} if you are not using a
24877 project file, or in the file designated to contain configuration pragmas
24878 in a project file.
24879 They then apply to all subsequent compilations. In practice the use of
24880 the @option{-gnata} switch is often the most convenient method of controlling
24881 the status of these pragmas.
24882
24883 Note that a pragma is not a statement, so in contexts where a statement
24884 sequence is required, you can't just write a pragma on its own. You have
24885 to add a @code{null} statement.
24886
24887 @smallexample @c ada
24888 @group
24889 if @dots{} then
24890    @dots{} -- some statements
24891 else
24892    pragma Assert (Num_Cases < 10);
24893    null;
24894 end if;
24895 @end group
24896 @end smallexample
24897
24898
24899 @node Conditionalizing Declarations
24900 @section Conditionalizing Declarations
24901
24902 @noindent
24903 In some cases, it may be necessary to conditionalize declarations to meet
24904 different requirements. For example we might want a bit string whose length
24905 is set to meet some hardware message requirement.
24906
24907 In some cases, it may be possible to do this using declare blocks controlled
24908 by conditional constants:
24909
24910 @smallexample @c ada
24911 @group
24912 if Small_Machine then
24913    declare
24914       X : Bit_String (1 .. 10);
24915    begin
24916       @dots{}
24917    end;
24918 else
24919    declare
24920       X : Large_Bit_String (1 .. 1000);
24921    begin
24922       @dots{}
24923    end;
24924 end if;
24925 @end group
24926 @end smallexample
24927
24928 @noindent
24929 Note that in this approach, both declarations are analyzed by the
24930 compiler so this can only be used where both declarations are legal,
24931 even though one of them will not be used.
24932
24933 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
24934 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24935 that are parameterized by these constants. For example
24936
24937 @smallexample @c ada
24938 @group
24939 for Rec use
24940   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24941 end record;
24942 @end group
24943 @end smallexample
24944
24945 @noindent
24946 If @code{Bits_Per_Word} is set to 32, this generates either
24947
24948 @smallexample @c ada
24949 @group
24950 for Rec use
24951   Field1 at 0 range 0 .. 32;
24952 end record;
24953 @end group
24954 @end smallexample
24955
24956 @noindent
24957 for the big endian case, or
24958
24959 @smallexample @c ada
24960 @group
24961 for Rec use record
24962   Field1 at 0 range 10 .. 32;
24963 end record;
24964 @end group
24965 @end smallexample
24966
24967 @noindent
24968 for the little endian case. Since a powerful subset of Ada expression
24969 notation is usable for creating static constants, clever use of this
24970 feature can often solve quite difficult problems in conditionalizing
24971 compilation (note incidentally that in Ada 95, the little endian
24972 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24973 need to define this one yourself).
24974
24975
24976 @node Use of Alternative Implementations
24977 @section Use of Alternative Implementations
24978
24979 @noindent
24980 In some cases, none of the approaches described above are adequate. This
24981 can occur for example if the set of declarations required is radically
24982 different for two different configurations.
24983
24984 In this situation, the official Ada way of dealing with conditionalizing
24985 such code is to write separate units for the different cases. As long as
24986 this does not result in excessive duplication of code, this can be done
24987 without creating maintenance problems. The approach is to share common
24988 code as far as possible, and then isolate the code and declarations
24989 that are different. Subunits are often a convenient method for breaking
24990 out a piece of a unit that is to be conditionalized, with separate files
24991 for different versions of the subunit for different targets, where the
24992 build script selects the right one to give to the compiler.
24993 @cindex Subunits (and conditional compilation)
24994
24995 As an example, consider a situation where a new feature in Ada 2005
24996 allows something to be done in a really nice way. But your code must be able
24997 to compile with an Ada 95 compiler. Conceptually you want to say:
24998
24999 @smallexample @c ada
25000 @group
25001 if Ada_2005 then
25002    @dots{} neat Ada 2005 code
25003 else
25004    @dots{} not quite as neat Ada 95 code
25005 end if;
25006 @end group
25007 @end smallexample
25008
25009 @noindent
25010 where @code{Ada_2005} is a Boolean constant.
25011
25012 But this won't work when @code{Ada_2005} is set to @code{False},
25013 since the @code{then} clause will be illegal for an Ada 95 compiler.
25014 (Recall that although such unreachable code would eventually be deleted
25015 by the compiler, it still needs to be legal.  If it uses features
25016 introduced in Ada 2005, it will be illegal in Ada 95.)
25017
25018 So instead we write
25019
25020 @smallexample @c ada
25021 procedure Insert is separate;
25022 @end smallexample
25023
25024 @noindent
25025 Then we have two files for the subunit @code{Insert}, with the two sets of
25026 code.
25027 If the package containing this is called @code{File_Queries}, then we might
25028 have two files
25029
25030 @itemize @bullet
25031 @item    @file{file_queries-insert-2005.adb}
25032 @item    @file{file_queries-insert-95.adb}
25033 @end itemize
25034
25035 @noindent
25036 and the build script renames the appropriate file to
25037
25038 @smallexample
25039 file_queries-insert.adb
25040 @end smallexample
25041
25042 @noindent
25043 and then carries out the compilation.
25044
25045 This can also be done with project files' naming schemes. For example:
25046
25047 @smallexample @c project
25048 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25049 @end smallexample
25050
25051 @noindent
25052 Note also that with project files it is desirable to use a different extension
25053 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25054 conflict may arise through another commonly used feature: to declare as part
25055 of the project a set of directories containing all the sources obeying the
25056 default naming scheme.
25057
25058 The use of alternative units is certainly feasible in all situations,
25059 and for example the Ada part of the GNAT run-time is conditionalized
25060 based on the target architecture using this approach. As a specific example,
25061 consider the implementation of the AST feature in VMS. There is one
25062 spec:
25063
25064 @smallexample
25065 s-asthan.ads
25066 @end smallexample
25067
25068 @noindent
25069 which is the same for all architectures, and three bodies:
25070
25071 @table @file
25072 @item    s-asthan.adb
25073 used for all non-VMS operating systems
25074 @item    s-asthan-vms-alpha.adb
25075 used for VMS on the Alpha
25076 @item    s-asthan-vms-ia64.adb
25077 used for VMS on the ia64
25078 @end table
25079
25080 @noindent
25081 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25082 this operating system feature is not available, and the two remaining
25083 versions interface with the corresponding versions of VMS to provide
25084 VMS-compatible AST handling. The GNAT build script knows the architecture
25085 and operating system, and automatically selects the right version,
25086 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25087
25088 Another style for arranging alternative implementations is through Ada's
25089 access-to-subprogram facility.
25090 In case some functionality is to be conditionally included,
25091 you can declare an access-to-procedure variable @code{Ref} that is initialized
25092 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25093 when appropriate.
25094 In some library package, set @code{Ref} to @code{Proc'Access} for some
25095 procedure @code{Proc} that performs the relevant processing.
25096 The initialization only occurs if the library package is included in the
25097 program.
25098 The same idea can also be implemented using tagged types and dispatching
25099 calls.
25100
25101
25102 @node Preprocessing
25103 @section Preprocessing
25104 @cindex Preprocessing
25105
25106 @noindent
25107 Although it is quite possible to conditionalize code without the use of
25108 C-style preprocessing, as described earlier in this section, it is
25109 nevertheless convenient in some cases to use the C approach. Moreover,
25110 older Ada compilers have often provided some preprocessing capability,
25111 so legacy code may depend on this approach, even though it is not
25112 standard.
25113
25114 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25115 extent on the various preprocessors that have been used
25116 with legacy code on other compilers, to enable easier transition).
25117
25118 The preprocessor may be used in two separate modes. It can be used quite
25119 separately from the compiler, to generate a separate output source file
25120 that is then fed to the compiler as a separate step. This is the
25121 @code{gnatprep} utility, whose use is fully described in
25122 @ref{Preprocessing Using gnatprep}.
25123 @cindex @code{gnatprep}
25124
25125 The preprocessing language allows such constructs as
25126
25127 @smallexample
25128 @group
25129 #if DEBUG or PRIORITY > 4 then
25130    bunch of declarations
25131 #else
25132    completely different bunch of declarations
25133 #end if;
25134 @end group
25135 @end smallexample
25136
25137 @noindent
25138 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25139 defined either on the command line or in a separate file.
25140
25141 The other way of running the preprocessor is even closer to the C style and
25142 often more convenient. In this approach the preprocessing is integrated into
25143 the compilation process. The compiler is fed the preprocessor input which
25144 includes @code{#if} lines etc, and then the compiler carries out the
25145 preprocessing internally and processes the resulting output.
25146 For more details on this approach, see @ref{Integrated Preprocessing}.
25147
25148
25149 @c *******************************
25150 @node Inline Assembler
25151 @appendix Inline Assembler
25152 @c *******************************
25153
25154 @noindent
25155 If you need to write low-level software that interacts directly
25156 with the hardware, Ada provides two ways to incorporate assembly
25157 language code into your program.  First, you can import and invoke
25158 external routines written in assembly language, an Ada feature fully
25159 supported by GNAT@.  However, for small sections of code it may be simpler
25160 or more efficient to include assembly language statements directly
25161 in your Ada source program, using the facilities of the implementation-defined
25162 package @code{System.Machine_Code}, which incorporates the gcc
25163 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25164 including the following:
25165
25166 @itemize @bullet
25167 @item No need to use non-Ada tools
25168 @item Consistent interface over different targets
25169 @item Automatic usage of the proper calling conventions
25170 @item Access to Ada constants and variables
25171 @item Definition of intrinsic routines
25172 @item Possibility of inlining a subprogram comprising assembler code
25173 @item Code optimizer can take Inline Assembler code into account
25174 @end itemize
25175
25176 This chapter presents a series of examples to show you how to use
25177 the Inline Assembler.  Although it focuses on the Intel x86,
25178 the general approach applies also to other processors.
25179 It is assumed that you are familiar with Ada
25180 and with assembly language programming.
25181
25182 @menu
25183 * Basic Assembler Syntax::
25184 * A Simple Example of Inline Assembler::
25185 * Output Variables in Inline Assembler::
25186 * Input Variables in Inline Assembler::
25187 * Inlining Inline Assembler Code::
25188 * Other Asm Functionality::
25189 @end menu
25190
25191 @c ---------------------------------------------------------------------------
25192 @node Basic Assembler Syntax
25193 @section Basic Assembler Syntax
25194
25195 @noindent
25196 The assembler used by GNAT and gcc is based not on the Intel assembly
25197 language, but rather on a language that descends from the AT&T Unix
25198 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25199 The following table summarizes the main features of @emph{as} syntax
25200 and points out the differences from the Intel conventions.
25201 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25202 pre-processor) documentation for further information.
25203
25204 @table @asis
25205 @item Register names
25206 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25207 @*
25208 Intel: No extra punctuation; for example @code{eax}
25209
25210 @item Immediate operand
25211 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25212 @*
25213 Intel: No extra punctuation; for example @code{4}
25214
25215 @item Address
25216 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25217 @*
25218 Intel: No extra punctuation; for example @code{loc}
25219
25220 @item Memory contents
25221 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25222 @*
25223 Intel: Square brackets; for example @code{[loc]}
25224
25225 @item Register contents
25226 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25227 @*
25228 Intel: Square brackets; for example @code{[eax]}
25229
25230 @item Hexadecimal numbers
25231 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25232 @*
25233 Intel: Trailing ``h''; for example @code{A0h}
25234
25235 @item Operand size
25236 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25237 a 16-bit word
25238 @*
25239 Intel: Implicit, deduced by assembler; for example @code{mov}
25240
25241 @item Instruction repetition
25242 gcc / @emph{as}: Split into two lines; for example
25243 @*
25244 @code{rep}
25245 @*
25246 @code{stosl}
25247 @*
25248 Intel: Keep on one line; for example @code{rep stosl}
25249
25250 @item Order of operands
25251 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25252 @*
25253 Intel: Destination first; for example @code{mov eax, 4}
25254 @end table
25255
25256 @c ---------------------------------------------------------------------------
25257 @node A Simple Example of Inline Assembler
25258 @section A Simple Example of Inline Assembler
25259
25260 @noindent
25261 The following example will generate a single assembly language statement,
25262 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25263 the example will be useful in illustrating the basics of
25264 the Inline Assembler facility.
25265
25266 @smallexample @c ada
25267 @group
25268 with System.Machine_Code; use System.Machine_Code;
25269 procedure Nothing is
25270 begin
25271    Asm ("nop");
25272 end Nothing;
25273 @end group
25274 @end smallexample
25275
25276 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25277 here it takes one parameter, a @emph{template string} that must be a static
25278 expression and that will form the generated instruction.
25279 @code{Asm} may be regarded as a compile-time procedure that parses
25280 the template string and additional parameters (none here),
25281 from which it generates a sequence of assembly language instructions.
25282
25283 The examples in this chapter will illustrate several of the forms
25284 for invoking @code{Asm}; a complete specification of the syntax
25285 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25286 Manual}.
25287
25288 Under the standard GNAT conventions, the @code{Nothing} procedure
25289 should be in a file named @file{nothing.adb}.
25290 You can build the executable in the usual way:
25291 @smallexample
25292 gnatmake nothing
25293 @end smallexample
25294 However, the interesting aspect of this example is not its run-time behavior
25295 but rather the generated assembly code.
25296 To see this output, invoke the compiler as follows:
25297 @smallexample
25298    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25299 @end smallexample
25300 where the options are:
25301
25302 @table @code
25303 @item -c
25304 compile only (no bind or link)
25305 @item -S
25306 generate assembler listing
25307 @item -fomit-frame-pointer
25308 do not set up separate stack frames
25309 @item -gnatp
25310 do not add runtime checks
25311 @end table
25312
25313 This gives a human-readable assembler version of the code. The resulting
25314 file will have the same name as the Ada source file, but with a @code{.s}
25315 extension. In our example, the file @file{nothing.s} has the following
25316 contents:
25317
25318 @smallexample
25319 @group
25320 .file "nothing.adb"
25321 gcc2_compiled.:
25322 ___gnu_compiled_ada:
25323 .text
25324    .align 4
25325 .globl __ada_nothing
25326 __ada_nothing:
25327 #APP
25328    nop
25329 #NO_APP
25330    jmp L1
25331    .align 2,0x90
25332 L1:
25333    ret
25334 @end group
25335 @end smallexample
25336
25337 The assembly code you included is clearly indicated by
25338 the compiler, between the @code{#APP} and @code{#NO_APP}
25339 delimiters. The character before the 'APP' and 'NOAPP'
25340 can differ on different targets. For example, GNU/Linux uses '#APP' while
25341 on NT you will see '/APP'.
25342
25343 If you make a mistake in your assembler code (such as using the
25344 wrong size modifier, or using a wrong operand for the instruction) GNAT
25345 will report this error in a temporary file, which will be deleted when
25346 the compilation is finished.  Generating an assembler file will help
25347 in such cases, since you can assemble this file separately using the
25348 @emph{as} assembler that comes with gcc.
25349
25350 Assembling the file using the command
25351
25352 @smallexample
25353 as @file{nothing.s}
25354 @end smallexample
25355 @noindent
25356 will give you error messages whose lines correspond to the assembler
25357 input file, so you can easily find and correct any mistakes you made.
25358 If there are no errors, @emph{as} will generate an object file
25359 @file{nothing.out}.
25360
25361 @c ---------------------------------------------------------------------------
25362 @node Output Variables in Inline Assembler
25363 @section Output Variables in Inline Assembler
25364
25365 @noindent
25366 The examples in this section, showing how to access the processor flags,
25367 illustrate how to specify the destination operands for assembly language
25368 statements.
25369
25370 @smallexample @c ada
25371 @group
25372 with Interfaces; use Interfaces;
25373 with Ada.Text_IO; use Ada.Text_IO;
25374 with System.Machine_Code; use System.Machine_Code;
25375 procedure Get_Flags is
25376    Flags : Unsigned_32;
25377    use ASCII;
25378 begin
25379    Asm ("pushfl"          & LF & HT & -- push flags on stack
25380         "popl %%eax"      & LF & HT & -- load eax with flags
25381         "movl %%eax, %0",             -- store flags in variable
25382         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25383    Put_Line ("Flags register:" & Flags'Img);
25384 end Get_Flags;
25385 @end group
25386 @end smallexample
25387
25388 In order to have a nicely aligned assembly listing, we have separated
25389 multiple assembler statements in the Asm template string with linefeed
25390 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25391 The resulting section of the assembly output file is:
25392
25393 @smallexample
25394 @group
25395 #APP
25396    pushfl
25397    popl %eax
25398    movl %eax, -40(%ebp)
25399 #NO_APP
25400 @end group
25401 @end smallexample
25402
25403 It would have been legal to write the Asm invocation as:
25404
25405 @smallexample
25406 Asm ("pushfl popl %%eax movl %%eax, %0")
25407 @end smallexample
25408
25409 but in the generated assembler file, this would come out as:
25410
25411 @smallexample
25412 #APP
25413    pushfl popl %eax movl %eax, -40(%ebp)
25414 #NO_APP
25415 @end smallexample
25416
25417 which is not so convenient for the human reader.
25418
25419 We use Ada comments
25420 at the end of each line to explain what the assembler instructions
25421 actually do.  This is a useful convention.
25422
25423 When writing Inline Assembler instructions, you need to precede each register
25424 and variable name with a percent sign.  Since the assembler already requires
25425 a percent sign at the beginning of a register name, you need two consecutive
25426 percent signs for such names in the Asm template string, thus @code{%%eax}.
25427 In the generated assembly code, one of the percent signs will be stripped off.
25428
25429 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25430 variables: operands you later define using @code{Input} or @code{Output}
25431 parameters to @code{Asm}.
25432 An output variable is illustrated in
25433 the third statement in the Asm template string:
25434 @smallexample
25435 movl %%eax, %0
25436 @end smallexample
25437 The intent is to store the contents of the eax register in a variable that can
25438 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25439 necessarily work, since the compiler might optimize by using a register
25440 to hold Flags, and the expansion of the @code{movl} instruction would not be
25441 aware of this optimization.  The solution is not to store the result directly
25442 but rather to advise the compiler to choose the correct operand form;
25443 that is the purpose of the @code{%0} output variable.
25444
25445 Information about the output variable is supplied in the @code{Outputs}
25446 parameter to @code{Asm}:
25447 @smallexample
25448 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25449 @end smallexample
25450
25451 The output is defined by the @code{Asm_Output} attribute of the target type;
25452 the general format is
25453 @smallexample
25454 Type'Asm_Output (constraint_string, variable_name)
25455 @end smallexample
25456
25457 The constraint string directs the compiler how
25458 to store/access the associated variable.  In the example
25459 @smallexample
25460 Unsigned_32'Asm_Output ("=m", Flags);
25461 @end smallexample
25462 the @code{"m"} (memory) constraint tells the compiler that the variable
25463 @code{Flags} should be stored in a memory variable, thus preventing
25464 the optimizer from keeping it in a register.  In contrast,
25465 @smallexample
25466 Unsigned_32'Asm_Output ("=r", Flags);
25467 @end smallexample
25468 uses the @code{"r"} (register) constraint, telling the compiler to
25469 store the variable in a register.
25470
25471 If the constraint is preceded by the equal character (@strong{=}), it tells
25472 the compiler that the variable will be used to store data into it.
25473
25474 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25475 allowing the optimizer to choose whatever it deems best.
25476
25477 There are a fairly large number of constraints, but the ones that are
25478 most useful (for the Intel x86 processor) are the following:
25479
25480 @table @code
25481 @item =
25482 output constraint
25483 @item g
25484 global (i.e.@: can be stored anywhere)
25485 @item m
25486 in memory
25487 @item I
25488 a constant
25489 @item a
25490 use eax
25491 @item b
25492 use ebx
25493 @item c
25494 use ecx
25495 @item d
25496 use edx
25497 @item S
25498 use esi
25499 @item D
25500 use edi
25501 @item r
25502 use one of eax, ebx, ecx or edx
25503 @item q
25504 use one of eax, ebx, ecx, edx, esi or edi
25505 @end table
25506
25507 The full set of constraints is described in the gcc and @emph{as}
25508 documentation; note that it is possible to combine certain constraints
25509 in one constraint string.
25510
25511 You specify the association of an output variable with an assembler operand
25512 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25513 integer.  Thus in
25514 @smallexample @c ada
25515 @group
25516 Asm ("pushfl"          & LF & HT & -- push flags on stack
25517      "popl %%eax"      & LF & HT & -- load eax with flags
25518      "movl %%eax, %0",             -- store flags in variable
25519      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25520 @end group
25521 @end smallexample
25522 @noindent
25523 @code{%0} will be replaced in the expanded code by the appropriate operand,
25524 whatever
25525 the compiler decided for the @code{Flags} variable.
25526
25527 In general, you may have any number of output variables:
25528 @itemize @bullet
25529 @item
25530 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25531 @item
25532 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25533 of @code{Asm_Output} attributes
25534 @end itemize
25535
25536 For example:
25537 @smallexample @c ada
25538 @group
25539 Asm ("movl %%eax, %0" & LF & HT &
25540      "movl %%ebx, %1" & LF & HT &
25541      "movl %%ecx, %2",
25542      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25543                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25544                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25545 @end group
25546 @end smallexample
25547 @noindent
25548 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25549 in the Ada program.
25550
25551 As a variation on the @code{Get_Flags} example, we can use the constraints
25552 string to direct the compiler to store the eax register into the @code{Flags}
25553 variable, instead of including the store instruction explicitly in the
25554 @code{Asm} template string:
25555
25556 @smallexample @c ada
25557 @group
25558 with Interfaces; use Interfaces;
25559 with Ada.Text_IO; use Ada.Text_IO;
25560 with System.Machine_Code; use System.Machine_Code;
25561 procedure Get_Flags_2 is
25562    Flags : Unsigned_32;
25563    use ASCII;
25564 begin
25565    Asm ("pushfl"      & LF & HT & -- push flags on stack
25566         "popl %%eax",             -- save flags in eax
25567         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25568    Put_Line ("Flags register:" & Flags'Img);
25569 end Get_Flags_2;
25570 @end group
25571 @end smallexample
25572
25573 @noindent
25574 The @code{"a"} constraint tells the compiler that the @code{Flags}
25575 variable will come from the eax register. Here is the resulting code:
25576
25577 @smallexample
25578 @group
25579 #APP
25580    pushfl
25581    popl %eax
25582 #NO_APP
25583    movl %eax,-40(%ebp)
25584 @end group
25585 @end smallexample
25586
25587 @noindent
25588 The compiler generated the store of eax into Flags after
25589 expanding the assembler code.
25590
25591 Actually, there was no need to pop the flags into the eax register;
25592 more simply, we could just pop the flags directly into the program variable:
25593
25594 @smallexample @c ada
25595 @group
25596 with Interfaces; use Interfaces;
25597 with Ada.Text_IO; use Ada.Text_IO;
25598 with System.Machine_Code; use System.Machine_Code;
25599 procedure Get_Flags_3 is
25600    Flags : Unsigned_32;
25601    use ASCII;
25602 begin
25603    Asm ("pushfl"  & LF & HT & -- push flags on stack
25604         "pop %0",             -- save flags in Flags
25605         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25606    Put_Line ("Flags register:" & Flags'Img);
25607 end Get_Flags_3;
25608 @end group
25609 @end smallexample
25610
25611 @c ---------------------------------------------------------------------------
25612 @node Input Variables in Inline Assembler
25613 @section Input Variables in Inline Assembler
25614
25615 @noindent
25616 The example in this section illustrates how to specify the source operands
25617 for assembly language statements.
25618 The program simply increments its input value by 1:
25619
25620 @smallexample @c ada
25621 @group
25622 with Interfaces; use Interfaces;
25623 with Ada.Text_IO; use Ada.Text_IO;
25624 with System.Machine_Code; use System.Machine_Code;
25625 procedure Increment is
25626
25627    function Incr (Value : Unsigned_32) return Unsigned_32 is
25628       Result : Unsigned_32;
25629    begin
25630       Asm ("incl %0",
25631            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25632            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25633       return Result;
25634    end Incr;
25635
25636    Value : Unsigned_32;
25637
25638 begin
25639    Value := 5;
25640    Put_Line ("Value before is" & Value'Img);
25641    Value := Incr (Value);
25642    Put_Line ("Value after is" & Value'Img);
25643 end Increment;
25644 @end group
25645 @end smallexample
25646
25647 The @code{Outputs} parameter to @code{Asm} specifies
25648 that the result will be in the eax register and that it is to be stored
25649 in the @code{Result} variable.
25650
25651 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25652 but with an @code{Asm_Input} attribute.
25653 The @code{"="} constraint, indicating an output value, is not present.
25654
25655 You can have multiple input variables, in the same way that you can have more
25656 than one output variable.
25657
25658 The parameter count (%0, %1) etc, now starts at the first input
25659 statement, and continues with the output statements.
25660 When both parameters use the same variable, the
25661 compiler will treat them as the same %n operand, which is the case here.
25662
25663 Just as the @code{Outputs} parameter causes the register to be stored into the
25664 target variable after execution of the assembler statements, so does the
25665 @code{Inputs} parameter cause its variable to be loaded into the register
25666 before execution of the assembler statements.
25667
25668 Thus the effect of the @code{Asm} invocation is:
25669 @enumerate
25670 @item load the 32-bit value of @code{Value} into eax
25671 @item execute the @code{incl %eax} instruction
25672 @item store the contents of eax into the @code{Result} variable
25673 @end enumerate
25674
25675 The resulting assembler file (with @option{-O2} optimization) contains:
25676 @smallexample
25677 @group
25678 _increment__incr.1:
25679    subl $4,%esp
25680    movl 8(%esp),%eax
25681 #APP
25682    incl %eax
25683 #NO_APP
25684    movl %eax,%edx
25685    movl %ecx,(%esp)
25686    addl $4,%esp
25687    ret
25688 @end group
25689 @end smallexample
25690
25691 @c ---------------------------------------------------------------------------
25692 @node Inlining Inline Assembler Code
25693 @section Inlining Inline Assembler Code
25694
25695 @noindent
25696 For a short subprogram such as the @code{Incr} function in the previous
25697 section, the overhead of the call and return (creating / deleting the stack
25698 frame) can be significant, compared to the amount of code in the subprogram
25699 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25700 which directs the compiler to expand invocations of the subprogram at the
25701 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25702 Here is the resulting program:
25703
25704 @smallexample @c ada
25705 @group
25706 with Interfaces; use Interfaces;
25707 with Ada.Text_IO; use Ada.Text_IO;
25708 with System.Machine_Code; use System.Machine_Code;
25709 procedure Increment_2 is
25710
25711    function Incr (Value : Unsigned_32) return Unsigned_32 is
25712       Result : Unsigned_32;
25713    begin
25714       Asm ("incl %0",
25715            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25716            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25717       return Result;
25718    end Incr;
25719    pragma Inline (Increment);
25720
25721    Value : Unsigned_32;
25722
25723 begin
25724    Value := 5;
25725    Put_Line ("Value before is" & Value'Img);
25726    Value := Increment (Value);
25727    Put_Line ("Value after is" & Value'Img);
25728 end Increment_2;
25729 @end group
25730 @end smallexample
25731
25732 Compile the program with both optimization (@option{-O2}) and inlining
25733 (@option{-gnatn}) enabled.
25734
25735 The @code{Incr} function is still compiled as usual, but at the
25736 point in @code{Increment} where our function used to be called:
25737
25738 @smallexample
25739 @group
25740 pushl %edi
25741 call _increment__incr.1
25742 @end group
25743 @end smallexample
25744
25745 @noindent
25746 the code for the function body directly appears:
25747
25748 @smallexample
25749 @group
25750 movl %esi,%eax
25751 #APP
25752    incl %eax
25753 #NO_APP
25754    movl %eax,%edx
25755 @end group
25756 @end smallexample
25757
25758 @noindent
25759 thus saving the overhead of stack frame setup and an out-of-line call.
25760
25761 @c ---------------------------------------------------------------------------
25762 @node Other Asm Functionality
25763 @section Other @code{Asm} Functionality
25764
25765 @noindent
25766 This section describes two important parameters to the @code{Asm}
25767 procedure: @code{Clobber}, which identifies register usage;
25768 and @code{Volatile}, which inhibits unwanted optimizations.
25769
25770 @menu
25771 * The Clobber Parameter::
25772 * The Volatile Parameter::
25773 @end menu
25774
25775 @c ---------------------------------------------------------------------------
25776 @node The Clobber Parameter
25777 @subsection The @code{Clobber} Parameter
25778
25779 @noindent
25780 One of the dangers of intermixing assembly language and a compiled language
25781 such as Ada is that the compiler needs to be aware of which registers are
25782 being used by the assembly code.  In some cases, such as the earlier examples,
25783 the constraint string is sufficient to indicate register usage (e.g.,
25784 @code{"a"} for
25785 the eax register).  But more generally, the compiler needs an explicit
25786 identification of the registers that are used by the Inline Assembly
25787 statements.
25788
25789 Using a register that the compiler doesn't know about
25790 could be a side effect of an instruction (like @code{mull}
25791 storing its result in both eax and edx).
25792 It can also arise from explicit register usage in your
25793 assembly code; for example:
25794 @smallexample
25795 @group
25796 Asm ("movl %0, %%ebx" & LF & HT &
25797      "movl %%ebx, %1",
25798      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25799      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25800 @end group
25801 @end smallexample
25802 @noindent
25803 where the compiler (since it does not analyze the @code{Asm} template string)
25804 does not know you are using the ebx register.
25805
25806 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25807 to identify the registers that will be used by your assembly code:
25808
25809 @smallexample
25810 @group
25811 Asm ("movl %0, %%ebx" & LF & HT &
25812      "movl %%ebx, %1",
25813      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25814      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25815      Clobber => "ebx");
25816 @end group
25817 @end smallexample
25818
25819 The Clobber parameter is a static string expression specifying the
25820 register(s) you are using.  Note that register names are @emph{not} prefixed
25821 by a percent sign. Also, if more than one register is used then their names
25822 are separated by commas; e.g., @code{"eax, ebx"}
25823
25824 The @code{Clobber} parameter has several additional uses:
25825 @enumerate
25826 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25827 @item Use ``register'' name @code{memory} if you changed a memory location
25828 @end enumerate
25829
25830 @c ---------------------------------------------------------------------------
25831 @node The Volatile Parameter
25832 @subsection The @code{Volatile} Parameter
25833 @cindex Volatile parameter
25834
25835 @noindent
25836 Compiler optimizations in the presence of Inline Assembler may sometimes have
25837 unwanted effects.  For example, when an @code{Asm} invocation with an input
25838 variable is inside a loop, the compiler might move the loading of the input
25839 variable outside the loop, regarding it as a one-time initialization.
25840
25841 If this effect is not desired, you can disable such optimizations by setting
25842 the @code{Volatile} parameter to @code{True}; for example:
25843
25844 @smallexample @c ada
25845 @group
25846 Asm ("movl %0, %%ebx" & LF & HT &
25847      "movl %%ebx, %1",
25848      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25849      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25850      Clobber  => "ebx",
25851      Volatile => True);
25852 @end group
25853 @end smallexample
25854
25855 By default, @code{Volatile} is set to @code{False} unless there is no
25856 @code{Outputs} parameter.
25857
25858 Although setting @code{Volatile} to @code{True} prevents unwanted
25859 optimizations, it will also disable other optimizations that might be
25860 important for efficiency. In general, you should set @code{Volatile}
25861 to @code{True} only if the compiler's optimizations have created
25862 problems.
25863 @c END OF INLINE ASSEMBLER CHAPTER
25864 @c ===============================
25865
25866 @c ***********************************
25867 @c * Compatibility and Porting Guide *
25868 @c ***********************************
25869 @node Compatibility and Porting Guide
25870 @appendix Compatibility and Porting Guide
25871
25872 @noindent
25873 This chapter describes the compatibility issues that may arise between
25874 GNAT and other Ada compilation systems (including those for Ada 83),
25875 and shows how GNAT can expedite porting
25876 applications developed in other Ada environments.
25877
25878 @menu
25879 * Compatibility with Ada 83::
25880 * Compatibility between Ada 95 and Ada 2005::
25881 * Implementation-dependent characteristics::
25882 * Compatibility with Other Ada Systems::
25883 * Representation Clauses::
25884 @ifclear vms
25885 @c Brief section is only in non-VMS version
25886 @c Full chapter is in VMS version
25887 * Compatibility with HP Ada 83::
25888 @end ifclear
25889 @ifset vms
25890 * Transitioning to 64-Bit GNAT for OpenVMS::
25891 @end ifset
25892 @end menu
25893
25894 @node Compatibility with Ada 83
25895 @section Compatibility with Ada 83
25896 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25897
25898 @noindent
25899 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
25900 particular, the design intention was that the difficulties associated
25901 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25902 that occur when moving from one Ada 83 system to another.
25903
25904 However, there are a number of points at which there are minor
25905 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25906 full details of these issues,
25907 and should be consulted for a complete treatment.
25908 In practice the
25909 following subsections treat the most likely issues to be encountered.
25910
25911 @menu
25912 * Legal Ada 83 programs that are illegal in Ada 95::
25913 * More deterministic semantics::
25914 * Changed semantics::
25915 * Other language compatibility issues::
25916 @end menu
25917
25918 @node Legal Ada 83 programs that are illegal in Ada 95
25919 @subsection Legal Ada 83 programs that are illegal in Ada 95
25920
25921 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25922 Ada 95 and thus also in Ada 2005:
25923
25924 @table @emph
25925 @item Character literals
25926 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25927 @code{Wide_Character} as a new predefined character type, some uses of
25928 character literals that were legal in Ada 83 are illegal in Ada 95.
25929 For example:
25930 @smallexample @c ada
25931    for Char in 'A' .. 'Z' loop @dots{} end loop;
25932 @end smallexample
25933
25934 @noindent
25935 The problem is that @code{'A'} and @code{'Z'} could be from either
25936 @code{Character} or @code{Wide_Character}.  The simplest correction
25937 is to make the type explicit; e.g.:
25938 @smallexample @c ada
25939    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25940 @end smallexample
25941
25942 @item New reserved words
25943 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25944 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25945 Existing Ada 83 code using any of these identifiers must be edited to
25946 use some alternative name.
25947
25948 @item Freezing rules
25949 The rules in Ada 95 are slightly different with regard to the point at
25950 which entities are frozen, and representation pragmas and clauses are
25951 not permitted past the freeze point.  This shows up most typically in
25952 the form of an error message complaining that a representation item
25953 appears too late, and the appropriate corrective action is to move
25954 the item nearer to the declaration of the entity to which it refers.
25955
25956 A particular case is that representation pragmas
25957 @ifset vms
25958 (including the
25959 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25960 @end ifset
25961 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25962 declaration must be introduced to which the pragma can be applied.
25963
25964 @item Optional bodies for library packages
25965 In Ada 83, a package that did not require a package body was nevertheless
25966 allowed to have one.  This lead to certain surprises in compiling large
25967 systems (situations in which the body could be unexpectedly ignored by the
25968 binder).  In Ada 95, if a package does not require a body then it is not
25969 permitted to have a body.  To fix this problem, simply remove a redundant
25970 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25971 into the spec that makes the body required.  One approach is to add a private
25972 part to the package declaration (if necessary), and define a parameterless
25973 procedure called @code{Requires_Body}, which must then be given a dummy
25974 procedure body in the package body, which then becomes required.
25975 Another approach (assuming that this does not introduce elaboration
25976 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25977 since one effect of this pragma is to require the presence of a package body.
25978
25979 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25980 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25981 @code{Constraint_Error}.
25982 This means that it is illegal to have separate exception handlers for
25983 the two exceptions.  The fix is simply to remove the handler for the
25984 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25985 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25986
25987 @item Indefinite subtypes in generics
25988 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25989 as the actual for a generic formal private type, but then the instantiation
25990 would be illegal if there were any instances of declarations of variables
25991 of this type in the generic body.  In Ada 95, to avoid this clear violation
25992 of the methodological principle known as the ``contract model'',
25993 the generic declaration explicitly indicates whether
25994 or not such instantiations are permitted.  If a generic formal parameter
25995 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25996 type name, then it can be instantiated with indefinite types, but no
25997 stand-alone variables can be declared of this type.  Any attempt to declare
25998 such a variable will result in an illegality at the time the generic is
25999 declared.  If the @code{(<>)} notation is not used, then it is illegal
26000 to instantiate the generic with an indefinite type.
26001 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26002 It will show up as a compile time error, and
26003 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26004 @end table
26005
26006 @node More deterministic semantics
26007 @subsection More deterministic semantics
26008
26009 @table @emph
26010 @item Conversions
26011 Conversions from real types to integer types round away from 0.  In Ada 83
26012 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26013 implementation freedom was intended to support unbiased rounding in
26014 statistical applications, but in practice it interfered with portability.
26015 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26016 is required.  Numeric code may be affected by this change in semantics.
26017 Note, though, that this issue is no worse than already existed in Ada 83
26018 when porting code from one vendor to another.
26019
26020 @item Tasking
26021 The Real-Time Annex introduces a set of policies that define the behavior of
26022 features that were implementation dependent in Ada 83, such as the order in
26023 which open select branches are executed.
26024 @end table
26025
26026 @node Changed semantics
26027 @subsection Changed semantics
26028
26029 @noindent
26030 The worst kind of incompatibility is one where a program that is legal in
26031 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26032 possible in Ada 83.  Fortunately this is extremely rare, but the one
26033 situation that you should be alert to is the change in the predefined type
26034 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26035
26036 @table @emph
26037 @item Range of type @code{Character}
26038 The range of @code{Standard.Character} is now the full 256 characters
26039 of Latin-1, whereas in most Ada 83 implementations it was restricted
26040 to 128 characters. Although some of the effects of
26041 this change will be manifest in compile-time rejection of legal
26042 Ada 83 programs it is possible for a working Ada 83 program to have
26043 a different effect in Ada 95, one that was not permitted in Ada 83.
26044 As an example, the expression
26045 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26046 delivers @code{255} as its value.
26047 In general, you should look at the logic of any
26048 character-processing Ada 83 program and see whether it needs to be adapted
26049 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26050 character handling package that may be relevant if code needs to be adapted
26051 to account for the additional Latin-1 elements.
26052 The desirable fix is to
26053 modify the program to accommodate the full character set, but in some cases
26054 it may be convenient to define a subtype or derived type of Character that
26055 covers only the restricted range.
26056 @cindex Latin-1
26057 @end table
26058
26059 @node Other language compatibility issues
26060 @subsection Other language compatibility issues
26061
26062 @table @emph
26063 @item @option{-gnat83} switch
26064 All implementations of GNAT provide a switch that causes GNAT to operate
26065 in Ada 83 mode.  In this mode, some but not all compatibility problems
26066 of the type described above are handled automatically.  For example, the
26067 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26068 as identifiers as in Ada 83.
26069 However,
26070 in practice, it is usually advisable to make the necessary modifications
26071 to the program to remove the need for using this switch.
26072 See @ref{Compiling Different Versions of Ada}.
26073
26074 @item Support for removed Ada 83 pragmas and attributes
26075 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26076 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26077 compilers are allowed, but not required, to implement these missing
26078 elements.  In contrast with some other compilers, GNAT implements all
26079 such pragmas and attributes, eliminating this compatibility concern.  These
26080 include @code{pragma Interface} and the floating point type attributes
26081 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26082 @end table
26083
26084
26085 @node Compatibility between Ada 95 and Ada 2005
26086 @section Compatibility between Ada 95 and Ada 2005
26087 @cindex Compatibility between Ada 95 and Ada 2005
26088
26089 @noindent
26090 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26091 a number of incompatibilities. Several are enumerated below;
26092 for a complete description please see the
26093 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26094 @cite{Rationale for Ada 2005}.
26095
26096 @table @emph
26097 @item New reserved words.
26098 The words @code{interface}, @code{overriding} and @code{synchronized} are
26099 reserved in Ada 2005.
26100 A pre-Ada 2005 program that uses any of these as an identifier will be
26101 illegal.
26102
26103 @item New declarations in predefined packages.
26104 A number of packages in the predefined environment contain new declarations:
26105 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26106 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26107 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26108 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26109 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26110 If an Ada 95 program does a @code{with} and @code{use} of any of these
26111 packages, the new declarations may cause name clashes.
26112
26113 @item Access parameters.
26114 A nondispatching subprogram with an access parameter cannot be renamed
26115 as a dispatching operation.  This was permitted in Ada 95.
26116
26117 @item Access types, discriminants, and constraints.
26118 Rule changes in this area have led to some incompatibilities; for example,
26119 constrained subtypes of some access types are not permitted in Ada 2005.
26120
26121 @item Aggregates for limited types.
26122 The allowance of aggregates for limited types in Ada 2005 raises the
26123 possibility of ambiguities in legal Ada 95 programs, since additional types
26124 now need to be considered in expression resolution.
26125
26126 @item Fixed-point multiplication and division.
26127 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26128 were legal in Ada 95 and invoked the predefined versions of these operations,
26129 are now ambiguous.
26130 The ambiguity may be resolved either by applying a type conversion to the
26131 expression, or by explicitly invoking the operation from package
26132 @code{Standard}.
26133
26134 @item Return-by-reference types.
26135 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26136 can declare a function returning a value from an anonymous access type.
26137 @end table
26138
26139
26140 @node Implementation-dependent characteristics
26141 @section Implementation-dependent characteristics
26142 @noindent
26143 Although the Ada language defines the semantics of each construct as
26144 precisely as practical, in some situations (for example for reasons of
26145 efficiency, or where the effect is heavily dependent on the host or target
26146 platform) the implementation is allowed some freedom.  In porting Ada 83
26147 code to GNAT, you need to be aware of whether / how the existing code
26148 exercised such implementation dependencies.  Such characteristics fall into
26149 several categories, and GNAT offers specific support in assisting the
26150 transition from certain Ada 83 compilers.
26151
26152 @menu
26153 * Implementation-defined pragmas::
26154 * Implementation-defined attributes::
26155 * Libraries::
26156 * Elaboration order::
26157 * Target-specific aspects::
26158 @end menu
26159
26160 @node Implementation-defined pragmas
26161 @subsection Implementation-defined pragmas
26162
26163 @noindent
26164 Ada compilers are allowed to supplement the language-defined pragmas, and
26165 these are a potential source of non-portability.  All GNAT-defined pragmas
26166 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26167 Reference Manual}, and these include several that are specifically
26168 intended to correspond to other vendors' Ada 83 pragmas.
26169 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26170 For compatibility with HP Ada 83, GNAT supplies the pragmas
26171 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26172 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26173 and @code{Volatile}.
26174 Other relevant pragmas include @code{External} and @code{Link_With}.
26175 Some vendor-specific
26176 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26177 recognized, thus
26178 avoiding compiler rejection of units that contain such pragmas; they are not
26179 relevant in a GNAT context and hence are not otherwise implemented.
26180
26181 @node Implementation-defined attributes
26182 @subsection Implementation-defined attributes
26183
26184 Analogous to pragmas, the set of attributes may be extended by an
26185 implementation.  All GNAT-defined attributes are described in
26186 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26187 Manual}, and these include several that are specifically intended
26188 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26189 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26190 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26191 @code{Type_Class}.
26192
26193 @node Libraries
26194 @subsection Libraries
26195 @noindent
26196 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26197 code uses vendor-specific libraries then there are several ways to manage
26198 this in Ada 95 or Ada 2005:
26199 @enumerate
26200 @item
26201 If the source code for the libraries (specs and bodies) are
26202 available, then the libraries can be migrated in the same way as the
26203 application.
26204 @item
26205 If the source code for the specs but not the bodies are
26206 available, then you can reimplement the bodies.
26207 @item
26208 Some features introduced by Ada 95 obviate the need for library support.  For
26209 example most Ada 83 vendors supplied a package for unsigned integers.  The
26210 Ada 95 modular type feature is the preferred way to handle this need, so
26211 instead of migrating or reimplementing the unsigned integer package it may
26212 be preferable to retrofit the application using modular types.
26213 @end enumerate
26214
26215 @node Elaboration order
26216 @subsection Elaboration order
26217 @noindent
26218 The implementation can choose any elaboration order consistent with the unit
26219 dependency relationship.  This freedom means that some orders can result in
26220 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26221 to invoke a subprogram its body has been elaborated, or to instantiate a
26222 generic before the generic body has been elaborated.  By default GNAT
26223 attempts to choose a safe order (one that will not encounter access before
26224 elaboration problems) by implicitly inserting @code{Elaborate} or
26225 @code{Elaborate_All} pragmas where
26226 needed.  However, this can lead to the creation of elaboration circularities
26227 and a resulting rejection of the program by gnatbind.  This issue is
26228 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26229 In brief, there are several
26230 ways to deal with this situation:
26231
26232 @itemize @bullet
26233 @item
26234 Modify the program to eliminate the circularities, e.g.@: by moving
26235 elaboration-time code into explicitly-invoked procedures
26236 @item
26237 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26238 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26239 @code{Elaborate_All}
26240 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26241 (by selectively suppressing elaboration checks via pragma
26242 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26243 @end itemize
26244
26245 @node Target-specific aspects
26246 @subsection Target-specific aspects
26247 @noindent
26248 Low-level applications need to deal with machine addresses, data
26249 representations, interfacing with assembler code, and similar issues.  If
26250 such an Ada 83 application is being ported to different target hardware (for
26251 example where the byte endianness has changed) then you will need to
26252 carefully examine the program logic; the porting effort will heavily depend
26253 on the robustness of the original design.  Moreover, Ada 95 (and thus
26254 Ada 2005) are sometimes
26255 incompatible with typical Ada 83 compiler practices regarding implicit
26256 packing, the meaning of the Size attribute, and the size of access values.
26257 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26258
26259 @node Compatibility with Other Ada Systems
26260 @section Compatibility with Other Ada Systems
26261
26262 @noindent
26263 If programs avoid the use of implementation dependent and
26264 implementation defined features, as documented in the @cite{Ada
26265 Reference Manual}, there should be a high degree of portability between
26266 GNAT and other Ada systems.  The following are specific items which
26267 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26268 compilers, but do not affect porting code to GNAT@.
26269 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26270 the following issues may or may not arise for Ada 2005 programs
26271 when other compilers appear.)
26272
26273 @table @emph
26274 @item Ada 83 Pragmas and Attributes
26275 Ada 95 compilers are allowed, but not required, to implement the missing
26276 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26277 GNAT implements all such pragmas and attributes, eliminating this as
26278 a compatibility concern, but some other Ada 95 compilers reject these
26279 pragmas and attributes.
26280
26281 @item Specialized Needs Annexes
26282 GNAT implements the full set of special needs annexes.  At the
26283 current time, it is the only Ada 95 compiler to do so.  This means that
26284 programs making use of these features may not be portable to other Ada
26285 95 compilation systems.
26286
26287 @item Representation Clauses
26288 Some other Ada 95 compilers implement only the minimal set of
26289 representation clauses required by the Ada 95 reference manual.  GNAT goes
26290 far beyond this minimal set, as described in the next section.
26291 @end table
26292
26293 @node Representation Clauses
26294 @section Representation Clauses
26295
26296 @noindent
26297 The Ada 83 reference manual was quite vague in describing both the minimal
26298 required implementation of representation clauses, and also their precise
26299 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26300 minimal set of capabilities required is still quite limited.
26301
26302 GNAT implements the full required set of capabilities in
26303 Ada 95 and Ada 2005, but also goes much further, and in particular
26304 an effort has been made to be compatible with existing Ada 83 usage to the
26305 greatest extent possible.
26306
26307 A few cases exist in which Ada 83 compiler behavior is incompatible with
26308 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26309 intentional or accidental dependence on specific implementation dependent
26310 characteristics of these Ada 83 compilers.  The following is a list of
26311 the cases most likely to arise in existing Ada 83 code.
26312
26313 @table @emph
26314 @item Implicit Packing
26315 Some Ada 83 compilers allowed a Size specification to cause implicit
26316 packing of an array or record.  This could cause expensive implicit
26317 conversions for change of representation in the presence of derived
26318 types, and the Ada design intends to avoid this possibility.
26319 Subsequent AI's were issued to make it clear that such implicit
26320 change of representation in response to a Size clause is inadvisable,
26321 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26322 Reference Manuals as implementation advice that is followed by GNAT@.
26323 The problem will show up as an error
26324 message rejecting the size clause.  The fix is simply to provide
26325 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26326 a Component_Size clause.
26327
26328 @item Meaning of Size Attribute
26329 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26330 the minimal number of bits required to hold values of the type.  For example,
26331 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26332 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26333 some 32 in this situation.  This problem will usually show up as a compile
26334 time error, but not always.  It is a good idea to check all uses of the
26335 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26336 Object_Size can provide a useful way of duplicating the behavior of
26337 some Ada 83 compiler systems.
26338
26339 @item Size of Access Types
26340 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26341 and that therefore it will be the same size as a System.Address value.  This
26342 assumption is true for GNAT in most cases with one exception.  For the case of
26343 a pointer to an unconstrained array type (where the bounds may vary from one
26344 value of the access type to another), the default is to use a ``fat pointer'',
26345 which is represented as two separate pointers, one to the bounds, and one to
26346 the array.  This representation has a number of advantages, including improved
26347 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26348 code which makes the assumption that, for example, pointers fit in 32 bits on
26349 a machine with 32-bit addressing.
26350
26351 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26352 access types in this case (where the designated type is an unconstrained array
26353 type).  These thin pointers are indeed the same size as a System.Address value.
26354 To specify a thin pointer, use a size clause for the type, for example:
26355
26356 @smallexample @c ada
26357 type X is access all String;
26358 for X'Size use Standard'Address_Size;
26359 @end smallexample
26360
26361 @noindent
26362 which will cause the type X to be represented using a single pointer.
26363 When using this representation, the bounds are right behind the array.
26364 This representation is slightly less efficient, and does not allow quite
26365 such flexibility in the use of foreign pointers or in using the
26366 Unrestricted_Access attribute to create pointers to non-aliased objects.
26367 But for any standard portable use of the access type it will work in
26368 a functionally correct manner and allow porting of existing code.
26369 Note that another way of forcing a thin pointer representation
26370 is to use a component size clause for the element size in an array,
26371 or a record representation clause for an access field in a record.
26372 @end table
26373
26374 @ifclear vms
26375 @c This brief section is only in the non-VMS version
26376 @c The complete chapter on HP Ada is in the VMS version
26377 @node Compatibility with HP Ada 83
26378 @section Compatibility with HP Ada 83
26379
26380 @noindent
26381 The VMS version of GNAT fully implements all the pragmas and attributes
26382 provided by HP Ada 83, as well as providing the standard HP Ada 83
26383 libraries, including Starlet.  In addition, data layouts and parameter
26384 passing conventions are highly compatible.  This means that porting
26385 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26386 most other porting efforts.  The following are some of the most
26387 significant differences between GNAT and HP Ada 83.
26388
26389 @table @emph
26390 @item Default floating-point representation
26391 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26392 it is VMS format.  GNAT does implement the necessary pragmas
26393 (Long_Float, Float_Representation) for changing this default.
26394
26395 @item System
26396 The package System in GNAT exactly corresponds to the definition in the
26397 Ada 95 reference manual, which means that it excludes many of the
26398 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26399 that contains the additional definitions, and a special pragma,
26400 Extend_System allows this package to be treated transparently as an
26401 extension of package System.
26402
26403 @item To_Address
26404 The definitions provided by Aux_DEC are exactly compatible with those
26405 in the HP Ada 83 version of System, with one exception.
26406 HP Ada provides the following declarations:
26407
26408 @smallexample @c ada
26409 TO_ADDRESS (INTEGER)
26410 TO_ADDRESS (UNSIGNED_LONGWORD)
26411 TO_ADDRESS (@i{universal_integer})
26412 @end smallexample
26413
26414 @noindent
26415 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26416 an extension to Ada 83 not strictly compatible with the reference manual.
26417 In GNAT, we are constrained to be exactly compatible with the standard,
26418 and this means we cannot provide this capability.  In HP Ada 83, the
26419 point of this definition is to deal with a call like:
26420
26421 @smallexample @c ada
26422 TO_ADDRESS (16#12777#);
26423 @end smallexample
26424
26425 @noindent
26426 Normally, according to the Ada 83 standard, one would expect this to be
26427 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26428 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26429 definition using @i{universal_integer} takes precedence.
26430
26431 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26432 is not possible to be 100% compatible.  Since there are many programs using
26433 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26434 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26435 declarations provided in the GNAT version of AUX_Dec are:
26436
26437 @smallexample @c ada
26438 function To_Address (X : Integer) return Address;
26439 pragma Pure_Function (To_Address);
26440
26441 function To_Address_Long (X : Unsigned_Longword)
26442  return Address;
26443 pragma Pure_Function (To_Address_Long);
26444 @end smallexample
26445
26446 @noindent
26447 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26448 change the name to TO_ADDRESS_LONG@.
26449
26450 @item Task_Id values
26451 The Task_Id values assigned will be different in the two systems, and GNAT
26452 does not provide a specified value for the Task_Id of the environment task,
26453 which in GNAT is treated like any other declared task.
26454 @end table
26455
26456 @noindent
26457 For full details on these and other less significant compatibility issues,
26458 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26459 Overview and Comparison on HP Platforms}.
26460
26461 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26462 attributes are recognized, although only a subset of them can sensibly
26463 be implemented.  The description of pragmas in @ref{Implementation
26464 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26465 indicates whether or not they are applicable to non-VMS systems.
26466 @end ifclear
26467
26468 @ifset vms
26469 @node Transitioning to 64-Bit GNAT for OpenVMS
26470 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26471
26472 @noindent
26473 This section is meant to assist users of pre-2006 @value{EDITION}
26474 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26475 the version of the GNAT technology supplied in 2006 and later for
26476 OpenVMS on both Alpha and I64.
26477
26478 @menu
26479 * Introduction to transitioning::
26480 * Migration of 32 bit code::
26481 * Taking advantage of 64 bit addressing::
26482 * Technical details::
26483 @end menu
26484
26485 @node Introduction to transitioning
26486 @subsection Introduction
26487
26488 @noindent
26489 64-bit @value{EDITION} for Open VMS has been designed to meet
26490 three main goals:
26491
26492 @enumerate
26493 @item
26494 Providing a full conforming implementation of Ada 95 and Ada 2005
26495
26496 @item
26497 Allowing maximum backward compatibility, thus easing migration of existing
26498 Ada source code
26499
26500 @item
26501 Supplying a path for exploiting the full 64-bit address range
26502 @end enumerate
26503
26504 @noindent
26505 Ada's strong typing semantics has made it
26506 impractical to have different 32-bit and 64-bit modes. As soon as
26507 one object could possibly be outside the 32-bit address space, this
26508 would make it necessary for the @code{System.Address} type to be 64 bits.
26509 In particular, this would cause inconsistencies if 32-bit code is
26510 called from 64-bit code that raises an exception.
26511
26512 This issue has been resolved by always using 64-bit addressing
26513 at the system level, but allowing for automatic conversions between
26514 32-bit and 64-bit addresses where required. Thus users who
26515 do not currently require 64-bit addressing capabilities, can
26516 recompile their code with only minimal changes (and indeed
26517 if the code is written in portable Ada, with no assumptions about
26518 the size of the @code{Address} type, then no changes at all are necessary).
26519 At the same time,
26520 this approach provides a simple, gradual upgrade path to future
26521 use of larger memories than available for 32-bit systems.
26522 Also, newly written applications or libraries will by default
26523 be fully compatible with future systems exploiting 64-bit
26524 addressing capabilities.
26525
26526 @ref{Migration of 32 bit code}, will focus on porting applications
26527 that do not require more than 2 GB of
26528 addressable memory. This code will be referred to as
26529 @emph{32-bit code}.
26530 For applications intending to exploit the full 64-bit address space,
26531 @ref{Taking advantage of 64 bit addressing},
26532 will consider further changes that may be required.
26533 Such code will be referred to below as @emph{64-bit code}.
26534
26535 @node Migration of 32 bit code
26536 @subsection Migration of 32-bit code
26537
26538 @menu
26539 * Address types::
26540 * Access types::
26541 * Unchecked conversions::
26542 * Predefined constants::
26543 * Interfacing with C::
26544 * Experience with source compatibility::
26545 @end menu
26546
26547 @node Address types
26548 @subsubsection Address types
26549
26550 @noindent
26551 To solve the problem of mixing 64-bit and 32-bit addressing,
26552 while maintaining maximum backward compatibility, the following
26553 approach has been taken:
26554
26555 @itemize @bullet
26556 @item
26557 @code{System.Address} always has a size of 64 bits
26558
26559 @item
26560 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26561 @end itemize
26562
26563 @noindent
26564 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26565 a @code{Short_Address}
26566 may be used where an @code{Address} is required, and vice versa, without
26567 needing explicit type conversions.
26568 By virtue of the Open VMS parameter passing conventions,
26569 even imported
26570 and exported subprograms that have 32-bit address parameters are
26571 compatible with those that have 64-bit address parameters.
26572 (See @ref{Making code 64 bit clean} for details.)
26573
26574 The areas that may need attention are those where record types have
26575 been defined that contain components of the type @code{System.Address}, and
26576 where objects of this type are passed to code expecting a record layout with
26577 32-bit addresses.
26578
26579 Different compilers on different platforms cannot be
26580 expected to represent the same type in the same way,
26581 since alignment constraints
26582 and other system-dependent properties affect the compiler's decision.
26583 For that reason, Ada code
26584 generally uses representation clauses to specify the expected
26585 layout where required.
26586
26587 If such a representation clause uses 32 bits for a component having
26588 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26589 will detect that error and produce a specific diagnostic message.
26590 The developer should then determine whether the representation
26591 should be 64 bits or not and make either of two changes:
26592 change the size to 64 bits and leave the type as @code{System.Address}, or
26593 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26594 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26595 required in any code setting or accessing the field; the compiler will
26596 automatically perform any needed conversions between address
26597 formats.
26598
26599 @node Access types
26600 @subsubsection Access types
26601
26602 @noindent
26603 By default, objects designated by access values are always
26604 allocated in the 32-bit
26605 address space. Thus legacy code will never contain
26606 any objects that are not addressable with 32-bit addresses, and
26607 the compiler will never raise exceptions as result of mixing
26608 32-bit and 64-bit addresses.
26609
26610 However, the access values themselves are represented in 64 bits, for optimum
26611 performance and future compatibility with 64-bit code. As was
26612 the case with @code{System.Address}, the compiler will give an error message
26613 if an object or record component has a representation clause that
26614 requires the access value to fit in 32 bits. In such a situation,
26615 an explicit size clause for the access type, specifying 32 bits,
26616 will have the desired effect.
26617
26618 General access types (declared with @code{access all}) can never be
26619 32 bits, as values of such types must be able to refer to any object
26620 of the  designated type,
26621 including objects residing outside the 32-bit address range.
26622 Existing Ada 83 code will not contain such type definitions,
26623 however, since general access types were introduced in Ada 95.
26624
26625 @node Unchecked conversions
26626 @subsubsection Unchecked conversions
26627
26628 @noindent
26629 In the case of an @code{Unchecked_Conversion} where the source type is a
26630 64-bit access type or the type @code{System.Address}, and the target
26631 type is a 32-bit type, the compiler will generate a warning.
26632 Even though the generated code will still perform the required
26633 conversions, it is highly recommended in these cases to use
26634 respectively a 32-bit access type or @code{System.Short_Address}
26635 as the source type.
26636
26637 @node Predefined constants
26638 @subsubsection Predefined constants
26639
26640 @noindent
26641 The following table shows the correspondence between pre-2006 versions of
26642 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26643 (``New''):
26644
26645 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26646 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26647 @item   @code{System.Word_Size}          @tab 32      @tab 64
26648 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26649 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26650 @item   @code{System.Address_Size}       @tab 32      @tab 64
26651 @end multitable
26652
26653 @noindent
26654 If you need to refer to the specific
26655 memory size of a 32-bit implementation, instead of the
26656 actual memory size, use @code{System.Short_Memory_Size}
26657 rather than @code{System.Memory_Size}.
26658 Similarly, references to @code{System.Address_Size} may need
26659 to be replaced by @code{System.Short_Address'Size}.
26660 The program @command{gnatfind} may be useful for locating
26661 references to the above constants, so that you can verify that they
26662 are still correct.
26663
26664 @node Interfacing with C
26665 @subsubsection Interfacing with C
26666
26667 @noindent
26668 In order to minimize the impact of the transition to 64-bit addresses on
26669 legacy programs, some fundamental types in the @code{Interfaces.C}
26670 package hierarchy continue to be represented in 32 bits.
26671 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26672 This eases integration with the default HP C layout choices, for example
26673 as found in the system routines in @code{DECC$SHR.EXE}.
26674 Because of this implementation choice, the type fully compatible with
26675 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26676 Depending on the context the compiler will issue a
26677 warning or an error when type @code{Address} is used, alerting the user to a
26678 potential problem. Otherwise 32-bit programs that use
26679 @code{Interfaces.C} should normally not require code modifications
26680
26681 The other issue arising with C interfacing concerns pragma @code{Convention}.
26682 For VMS 64-bit systems, there is an issue of the appropriate default size
26683 of C convention pointers in the absence of an explicit size clause. The HP
26684 C compiler can choose either 32 or 64 bits depending on compiler options.
26685 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26686 clause is given. This proves a better choice for porting 32-bit legacy
26687 applications. In order to have a 64-bit representation, it is necessary to
26688 specify a size representation clause. For example:
26689
26690 @smallexample @c ada
26691 type int_star is access Interfaces.C.int;
26692 pragma Convention(C, int_star);
26693 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26694 @end smallexample
26695
26696 @node Experience with source compatibility
26697 @subsubsection Experience with source compatibility
26698
26699 @noindent
26700 The Security Server and STARLET on I64 provide an interesting ``test case''
26701 for source compatibility issues, since it is in such system code
26702 where assumptions about @code{Address} size might be expected to occur.
26703 Indeed, there were a small number of occasions in the Security Server
26704 file @file{jibdef.ads}
26705 where a representation clause for a record type specified
26706 32 bits for a component of type @code{Address}.
26707 All of these errors were detected by the compiler.
26708 The repair was obvious and immediate; to simply replace @code{Address} by
26709 @code{Short_Address}.
26710
26711 In the case of STARLET, there were several record types that should
26712 have had representation clauses but did not.  In these record types
26713 there was an implicit assumption that an @code{Address} value occupied
26714 32 bits.
26715 These compiled without error, but their usage resulted in run-time error
26716 returns from STARLET system calls.
26717 Future GNAT technology enhancements may include a tool that detects and flags
26718 these sorts of potential source code porting problems.
26719
26720 @c ****************************************
26721 @node Taking advantage of 64 bit addressing
26722 @subsection Taking advantage of 64-bit addressing
26723
26724 @menu
26725 * Making code 64 bit clean::
26726 * Allocating memory from the 64 bit storage pool::
26727 * Restrictions on use of 64 bit objects::
26728 * Using 64 bit storage pools by default::
26729 * General access types::
26730 * STARLET and other predefined libraries::
26731 @end menu
26732
26733 @node Making code 64 bit clean
26734 @subsubsection Making code 64-bit clean
26735
26736 @noindent
26737 In order to prevent problems that may occur when (parts of) a
26738 system start using memory outside the 32-bit address range,
26739 we recommend some additional guidelines:
26740
26741 @itemize @bullet
26742 @item
26743 For imported subprograms that take parameters of the
26744 type @code{System.Address}, ensure that these subprograms can
26745 indeed handle 64-bit addresses. If not, or when in doubt,
26746 change the subprogram declaration to specify
26747 @code{System.Short_Address} instead.
26748
26749 @item
26750 Resolve all warnings related to size mismatches in
26751 unchecked conversions. Failing to do so causes
26752 erroneous execution if the source object is outside
26753 the 32-bit address space.
26754
26755 @item
26756 (optional) Explicitly use the 32-bit storage pool
26757 for access types used in a 32-bit context, or use
26758 generic access types where possible
26759 (@pxref{Restrictions on use of 64 bit objects}).
26760 @end itemize
26761
26762 @noindent
26763 If these rules are followed, the compiler will automatically insert
26764 any necessary checks to ensure that no addresses or access values
26765 passed to 32-bit code ever refer to objects outside the 32-bit
26766 address range.
26767 Any attempt to do this will raise @code{Constraint_Error}.
26768
26769 @node Allocating memory from the 64 bit storage pool
26770 @subsubsection Allocating memory from the 64-bit storage pool
26771
26772 @noindent
26773 For any access type @code{T} that potentially requires memory allocations
26774 beyond the 32-bit address space,
26775 use the following representation clause:
26776
26777 @smallexample @c ada
26778    for T'Storage_Pool use System.Pool_64;
26779 @end smallexample
26780
26781 @node Restrictions on use of 64 bit objects
26782 @subsubsection Restrictions on use of 64-bit objects
26783
26784 @noindent
26785 Taking the address of an object allocated from a 64-bit storage pool,
26786 and then passing this address to a subprogram expecting
26787 @code{System.Short_Address},
26788 or assigning it to a variable of type @code{Short_Address}, will cause
26789 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26790 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26791 no exception is raised and execution
26792 will become erroneous.
26793
26794 @node Using 64 bit storage pools by default
26795 @subsubsection Using 64-bit storage pools by default
26796
26797 @noindent
26798 In some cases it may be desirable to have the compiler allocate
26799 from 64-bit storage pools by default. This may be the case for
26800 libraries that are 64-bit clean, but may be used in both 32-bit
26801 and 64-bit contexts. For these cases the following configuration
26802 pragma may be specified:
26803
26804 @smallexample @c ada
26805   pragma Pool_64_Default;
26806 @end smallexample
26807
26808 @noindent
26809 Any code compiled in the context of this pragma will by default
26810 use the @code{System.Pool_64} storage pool. This default may be overridden
26811 for a specific access type @code{T} by the representation clause:
26812
26813 @smallexample @c ada
26814    for T'Storage_Pool use System.Pool_32;
26815 @end smallexample
26816
26817 @noindent
26818 Any object whose address may be passed to a subprogram with a
26819 @code{Short_Address} argument, or assigned to a variable of type
26820 @code{Short_Address}, needs to be allocated from this pool.
26821
26822 @node General access types
26823 @subsubsection General access types
26824
26825 @noindent
26826 Objects designated by access values from a
26827 general access type (declared with @code{access all}) are never allocated
26828 from a 64-bit storage pool. Code that uses general access types will
26829 accept objects allocated in either 32-bit or 64-bit address spaces,
26830 but never allocate objects outside the 32-bit address space.
26831 Using general access types ensures maximum compatibility with both
26832 32-bit and 64-bit code.
26833
26834 @node STARLET and other predefined libraries
26835 @subsubsection STARLET and other predefined libraries
26836
26837 @noindent
26838 All code that comes as part of GNAT is 64-bit clean, but the
26839 restrictions given in @ref{Restrictions on use of 64 bit objects},
26840 still apply. Look at the package
26841 specs to see in which contexts objects allocated
26842 in 64-bit address space are acceptable.
26843
26844 @node Technical details
26845 @subsection Technical details
26846
26847 @noindent
26848 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26849 Ada standard with respect to the type of @code{System.Address}. Previous
26850 versions of GNAT Pro have defined this type as private and implemented it as a
26851 modular type.
26852
26853 In order to allow defining @code{System.Short_Address} as a proper subtype,
26854 and to match the implicit sign extension in parameter passing,
26855 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26856 visible (i.e., non-private) integer type.
26857 Standard operations on the type, such as the binary operators ``+'', ``-'',
26858 etc., that take @code{Address} operands and return an @code{Address} result,
26859 have been hidden by declaring these
26860 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26861 ambiguities that would otherwise result from overloading.
26862 (Note that, although @code{Address} is a visible integer type,
26863 good programming practice dictates against exploiting the type's
26864 integer properties such as literals, since this will compromise
26865 code portability.)
26866
26867 Defining @code{Address} as a visible integer type helps achieve
26868 maximum compatibility for existing Ada code,
26869 without sacrificing the capabilities of the 64-bit architecture.
26870 @end ifset
26871
26872 @c ************************************************
26873 @ifset unw
26874 @node Microsoft Windows Topics
26875 @appendix Microsoft Windows Topics
26876 @cindex Windows NT
26877 @cindex Windows 95
26878 @cindex Windows 98
26879
26880 @noindent
26881 This chapter describes topics that are specific to the Microsoft Windows
26882 platforms (NT, 2000, and XP Professional).
26883
26884 @menu
26885 * Using GNAT on Windows::
26886 * Using a network installation of GNAT::
26887 * CONSOLE and WINDOWS subsystems::
26888 * Temporary Files::
26889 * Mixed-Language Programming on Windows::
26890 * Windows Calling Conventions::
26891 * Introduction to Dynamic Link Libraries (DLLs)::
26892 * Using DLLs with GNAT::
26893 * Building DLLs with GNAT Project files::
26894 * Building DLLs with GNAT::
26895 * Building DLLs with gnatdll::
26896 * GNAT and Windows Resources::
26897 * Debugging a DLL::
26898 * Setting Stack Size from gnatlink::
26899 * Setting Heap Size from gnatlink::
26900 @end menu
26901
26902 @node Using GNAT on Windows
26903 @section Using GNAT on Windows
26904
26905 @noindent
26906 One of the strengths of the GNAT technology is that its tool set
26907 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26908 @code{gdb} debugger, etc.) is used in the same way regardless of the
26909 platform.
26910
26911 On Windows this tool set is complemented by a number of Microsoft-specific
26912 tools that have been provided to facilitate interoperability with Windows
26913 when this is required. With these tools:
26914
26915 @itemize @bullet
26916
26917 @item
26918 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26919 subsystems.
26920
26921 @item
26922 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26923 relocatable and non-relocatable DLLs are supported).
26924
26925 @item
26926 You can build Ada DLLs for use in other applications. These applications
26927 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26928 relocatable and non-relocatable Ada DLLs are supported.
26929
26930 @item
26931 You can include Windows resources in your Ada application.
26932
26933 @item
26934 You can use or create COM/DCOM objects.
26935 @end itemize
26936
26937 @noindent
26938 Immediately below are listed all known general GNAT-for-Windows restrictions.
26939 Other restrictions about specific features like Windows Resources and DLLs
26940 are listed in separate sections below.
26941
26942 @itemize @bullet
26943
26944 @item
26945 It is not possible to use @code{GetLastError} and @code{SetLastError}
26946 when tasking, protected records, or exceptions are used. In these
26947 cases, in order to implement Ada semantics, the GNAT run-time system
26948 calls certain Win32 routines that set the last error variable to 0 upon
26949 success. It should be possible to use @code{GetLastError} and
26950 @code{SetLastError} when tasking, protected record, and exception
26951 features are not used, but it is not guaranteed to work.
26952
26953 @item
26954 It is not possible to link against Microsoft libraries except for
26955 import libraries. Interfacing must be done by the mean of DLLs.
26956
26957 @item
26958 When the compilation environment is located on FAT32 drives, users may
26959 experience recompilations of the source files that have not changed if
26960 Daylight Saving Time (DST) state has changed since the last time files
26961 were compiled. NTFS drives do not have this problem.
26962
26963 @item
26964 No components of the GNAT toolset use any entries in the Windows
26965 registry. The only entries that can be created are file associations and
26966 PATH settings, provided the user has chosen to create them at installation
26967 time, as well as some minimal book-keeping information needed to correctly
26968 uninstall or integrate different GNAT products.
26969 @end itemize
26970
26971 @node Using a network installation of GNAT
26972 @section Using a network installation of GNAT
26973
26974 @noindent
26975 Make sure the system on which GNAT is installed is accessible from the
26976 current machine, i.e., the install location is shared over the network.
26977 Shared resources are accessed on Windows by means of UNC paths, which
26978 have the format @code{\\server\sharename\path}
26979
26980 In order to use such a network installation, simply add the UNC path of the
26981 @file{bin} directory of your GNAT installation in front of your PATH. For
26982 example, if GNAT is installed in @file{\GNAT} directory of a share location
26983 called @file{c-drive} on a machine @file{LOKI}, the following command will
26984 make it available:
26985
26986 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26987
26988 Be aware that every compilation using the network installation results in the
26989 transfer of large amounts of data across the network and will likely cause
26990 serious performance penalty.
26991
26992 @node CONSOLE and WINDOWS subsystems
26993 @section CONSOLE and WINDOWS subsystems
26994 @cindex CONSOLE Subsystem
26995 @cindex WINDOWS Subsystem
26996 @cindex -mwindows
26997
26998 @noindent
26999 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27000 (which is the default subsystem) will always create a console when
27001 launching the application. This is not something desirable when the
27002 application has a Windows GUI. To get rid of this console the
27003 application must be using the @code{WINDOWS} subsystem. To do so
27004 the @option{-mwindows} linker option must be specified.
27005
27006 @smallexample
27007 $ gnatmake winprog -largs -mwindows
27008 @end smallexample
27009
27010 @node Temporary Files
27011 @section Temporary Files
27012 @cindex Temporary files
27013
27014 @noindent
27015 It is possible to control where temporary files gets created by setting
27016 the @env{TMP} environment variable. The file will be created:
27017
27018 @itemize
27019 @item Under the directory pointed to by the @env{TMP} environment variable if
27020 this directory exists.
27021
27022 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27023 set (or not pointing to a directory) and if this directory exists.
27024
27025 @item Under the current working directory otherwise.
27026 @end itemize
27027
27028 @noindent
27029 This allows you to determine exactly where the temporary
27030 file will be created. This is particularly useful in networked
27031 environments where you may not have write access to some
27032 directories.
27033
27034 @node Mixed-Language Programming on Windows
27035 @section Mixed-Language Programming on Windows
27036
27037 @noindent
27038 Developing pure Ada applications on Windows is no different than on
27039 other GNAT-supported platforms. However, when developing or porting an
27040 application that contains a mix of Ada and C/C++, the choice of your
27041 Windows C/C++ development environment conditions your overall
27042 interoperability strategy.
27043
27044 If you use @command{gcc} to compile the non-Ada part of your application,
27045 there are no Windows-specific restrictions that affect the overall
27046 interoperability with your Ada code. If you do want to use the
27047 Microsoft tools for your non-Ada code, you have two choices:
27048
27049 @enumerate
27050 @item
27051 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27052 application. In this case, use the Microsoft or whatever environment to
27053 build the DLL and use GNAT to build your executable
27054 (@pxref{Using DLLs with GNAT}).
27055
27056 @item
27057 Or you can encapsulate your Ada code in a DLL to be linked with the
27058 other part of your application. In this case, use GNAT to build the DLL
27059 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27060 or whatever environment to build your executable.
27061 @end enumerate
27062
27063 @node Windows Calling Conventions
27064 @section Windows Calling Conventions
27065 @findex Stdcall
27066 @findex APIENTRY
27067
27068 This section pertain only to Win32. On Win64 there is a single native
27069 calling convention. All convention specifiers are ignored on this
27070 platform.
27071
27072 @menu
27073 * C Calling Convention::
27074 * Stdcall Calling Convention::
27075 * Win32 Calling Convention::
27076 * DLL Calling Convention::
27077 @end menu
27078
27079 @noindent
27080 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27081 (callee), there are several ways to push @code{G}'s parameters on the
27082 stack and there are several possible scenarios to clean up the stack
27083 upon @code{G}'s return. A calling convention is an agreed upon software
27084 protocol whereby the responsibilities between the caller (@code{F}) and
27085 the callee (@code{G}) are clearly defined. Several calling conventions
27086 are available for Windows:
27087
27088 @itemize @bullet
27089 @item
27090 @code{C} (Microsoft defined)
27091
27092 @item
27093 @code{Stdcall} (Microsoft defined)
27094
27095 @item
27096 @code{Win32} (GNAT specific)
27097
27098 @item
27099 @code{DLL} (GNAT specific)
27100 @end itemize
27101
27102 @node C Calling Convention
27103 @subsection @code{C} Calling Convention
27104
27105 @noindent
27106 This is the default calling convention used when interfacing to C/C++
27107 routines compiled with either @command{gcc} or Microsoft Visual C++.
27108
27109 In the @code{C} calling convention subprogram parameters are pushed on the
27110 stack by the caller from right to left. The caller itself is in charge of
27111 cleaning up the stack after the call. In addition, the name of a routine
27112 with @code{C} calling convention is mangled by adding a leading underscore.
27113
27114 The name to use on the Ada side when importing (or exporting) a routine
27115 with @code{C} calling convention is the name of the routine. For
27116 instance the C function:
27117
27118 @smallexample
27119 int get_val (long);
27120 @end smallexample
27121
27122 @noindent
27123 should be imported from Ada as follows:
27124
27125 @smallexample @c ada
27126 @group
27127 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27128 pragma Import (C, Get_Val, External_Name => "get_val");
27129 @end group
27130 @end smallexample
27131
27132 @noindent
27133 Note that in this particular case the @code{External_Name} parameter could
27134 have been omitted since, when missing, this parameter is taken to be the
27135 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27136 is missing, as in the above example, this parameter is set to be the
27137 @code{External_Name} with a leading underscore.
27138
27139 When importing a variable defined in C, you should always use the @code{C}
27140 calling convention unless the object containing the variable is part of a
27141 DLL (in which case you should use the @code{Stdcall} calling
27142 convention, @pxref{Stdcall Calling Convention}).
27143
27144 @node Stdcall Calling Convention
27145 @subsection @code{Stdcall} Calling Convention
27146
27147 @noindent
27148 This convention, which was the calling convention used for Pascal
27149 programs, is used by Microsoft for all the routines in the Win32 API for
27150 efficiency reasons. It must be used to import any routine for which this
27151 convention was specified.
27152
27153 In the @code{Stdcall} calling convention subprogram parameters are pushed
27154 on the stack by the caller from right to left. The callee (and not the
27155 caller) is in charge of cleaning the stack on routine exit. In addition,
27156 the name of a routine with @code{Stdcall} calling convention is mangled by
27157 adding a leading underscore (as for the @code{C} calling convention) and a
27158 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27159 bytes) of the parameters passed to the routine.
27160
27161 The name to use on the Ada side when importing a C routine with a
27162 @code{Stdcall} calling convention is the name of the C routine. The leading
27163 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27164 the compiler. For instance the Win32 function:
27165
27166 @smallexample
27167 @b{APIENTRY} int get_val (long);
27168 @end smallexample
27169
27170 @noindent
27171 should be imported from Ada as follows:
27172
27173 @smallexample @c ada
27174 @group
27175 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27176 pragma Import (Stdcall, Get_Val);
27177 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27178 @end group
27179 @end smallexample
27180
27181 @noindent
27182 As for the @code{C} calling convention, when the @code{External_Name}
27183 parameter is missing, it is taken to be the name of the Ada entity in lower
27184 case. If instead of writing the above import pragma you write:
27185
27186 @smallexample @c ada
27187 @group
27188 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27189 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27190 @end group
27191 @end smallexample
27192
27193 @noindent
27194 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27195 of specifying the @code{External_Name} parameter you specify the
27196 @code{Link_Name} as in the following example:
27197
27198 @smallexample @c ada
27199 @group
27200 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27201 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27202 @end group
27203 @end smallexample
27204
27205 @noindent
27206 then the imported routine is @code{retrieve_val}, that is, there is no
27207 decoration at all. No leading underscore and no Stdcall suffix
27208 @code{@@}@code{@var{nn}}.
27209
27210 @noindent
27211 This is especially important as in some special cases a DLL's entry
27212 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27213 name generated for a call has it.
27214
27215 @noindent
27216 It is also possible to import variables defined in a DLL by using an
27217 import pragma for a variable. As an example, if a DLL contains a
27218 variable defined as:
27219
27220 @smallexample
27221 int my_var;
27222 @end smallexample
27223
27224 @noindent
27225 then, to access this variable from Ada you should write:
27226
27227 @smallexample @c ada
27228 @group
27229 My_Var : Interfaces.C.int;
27230 pragma Import (Stdcall, My_Var);
27231 @end group
27232 @end smallexample
27233
27234 @noindent
27235 Note that to ease building cross-platform bindings this convention
27236 will be handled as a @code{C} calling convention on non-Windows platforms.
27237
27238 @node Win32 Calling Convention
27239 @subsection @code{Win32} Calling Convention
27240
27241 @noindent
27242 This convention, which is GNAT-specific is fully equivalent to the
27243 @code{Stdcall} calling convention described above.
27244
27245 @node DLL Calling Convention
27246 @subsection @code{DLL} Calling Convention
27247
27248 @noindent
27249 This convention, which is GNAT-specific is fully equivalent to the
27250 @code{Stdcall} calling convention described above.
27251
27252 @node Introduction to Dynamic Link Libraries (DLLs)
27253 @section Introduction to Dynamic Link Libraries (DLLs)
27254 @findex DLL
27255
27256 @noindent
27257 A Dynamically Linked Library (DLL) is a library that can be shared by
27258 several applications running under Windows. A DLL can contain any number of
27259 routines and variables.
27260
27261 One advantage of DLLs is that you can change and enhance them without
27262 forcing all the applications that depend on them to be relinked or
27263 recompiled. However, you should be aware than all calls to DLL routines are
27264 slower since, as you will understand below, such calls are indirect.
27265
27266 To illustrate the remainder of this section, suppose that an application
27267 wants to use the services of a DLL @file{API.dll}. To use the services
27268 provided by @file{API.dll} you must statically link against the DLL or
27269 an import library which contains a jump table with an entry for each
27270 routine and variable exported by the DLL. In the Microsoft world this
27271 import library is called @file{API.lib}. When using GNAT this import
27272 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27273 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27274
27275 After you have linked your application with the DLL or the import library
27276 and you run your application, here is what happens:
27277
27278 @enumerate
27279 @item
27280 Your application is loaded into memory.
27281
27282 @item
27283 The DLL @file{API.dll} is mapped into the address space of your
27284 application. This means that:
27285
27286 @itemize @bullet
27287 @item
27288 The DLL will use the stack of the calling thread.
27289
27290 @item
27291 The DLL will use the virtual address space of the calling process.
27292
27293 @item
27294 The DLL will allocate memory from the virtual address space of the calling
27295 process.
27296
27297 @item
27298 Handles (pointers) can be safely exchanged between routines in the DLL
27299 routines and routines in the application using the DLL.
27300 @end itemize
27301
27302 @item
27303 The entries in the jump table (from the import library @file{libAPI.dll.a}
27304 or @file{API.lib} or automatically created when linking against a DLL)
27305 which is part of your application are initialized with the addresses
27306 of the routines and variables in @file{API.dll}.
27307
27308 @item
27309 If present in @file{API.dll}, routines @code{DllMain} or
27310 @code{DllMainCRTStartup} are invoked. These routines typically contain
27311 the initialization code needed for the well-being of the routines and
27312 variables exported by the DLL.
27313 @end enumerate
27314
27315 @noindent
27316 There is an additional point which is worth mentioning. In the Windows
27317 world there are two kind of DLLs: relocatable and non-relocatable
27318 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27319 in the target application address space. If the addresses of two
27320 non-relocatable DLLs overlap and these happen to be used by the same
27321 application, a conflict will occur and the application will run
27322 incorrectly. Hence, when possible, it is always preferable to use and
27323 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27324 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27325 User's Guide) removes the debugging symbols from the DLL but the DLL can
27326 still be relocated.
27327
27328 As a side note, an interesting difference between Microsoft DLLs and
27329 Unix shared libraries, is the fact that on most Unix systems all public
27330 routines are exported by default in a Unix shared library, while under
27331 Windows it is possible (but not required) to list exported routines in
27332 a definition file (@pxref{The Definition File}).
27333
27334 @node Using DLLs with GNAT
27335 @section Using DLLs with GNAT
27336
27337 @menu
27338 * Creating an Ada Spec for the DLL Services::
27339 * Creating an Import Library::
27340 @end menu
27341
27342 @noindent
27343 To use the services of a DLL, say @file{API.dll}, in your Ada application
27344 you must have:
27345
27346 @enumerate
27347 @item
27348 The Ada spec for the routines and/or variables you want to access in
27349 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27350 header files provided with the DLL.
27351
27352 @item
27353 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27354 mentioned an import library is a statically linked library containing the
27355 import table which will be filled at load time to point to the actual
27356 @file{API.dll} routines. Sometimes you don't have an import library for the
27357 DLL you want to use. The following sections will explain how to build
27358 one. Note that this is optional.
27359
27360 @item
27361 The actual DLL, @file{API.dll}.
27362 @end enumerate
27363
27364 @noindent
27365 Once you have all the above, to compile an Ada application that uses the
27366 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27367 you simply issue the command
27368
27369 @smallexample
27370 $ gnatmake my_ada_app -largs -lAPI
27371 @end smallexample
27372
27373 @noindent
27374 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27375 tells the GNAT linker to look for an import library. The linker will
27376 look for a library name in this specific order:
27377
27378 @enumerate
27379 @item @file{libAPI.dll.a}
27380 @item @file{API.dll.a}
27381 @item @file{libAPI.a}
27382 @item @file{API.lib}
27383 @item @file{libAPI.dll}
27384 @item @file{API.dll}
27385 @end enumerate
27386
27387 The first three are the GNU style import libraries. The third is the
27388 Microsoft style import libraries. The last two are the DLL themself.
27389
27390 Note that if the Ada package spec for @file{API.dll} contains the
27391 following pragma
27392
27393 @smallexample @c ada
27394 pragma Linker_Options ("-lAPI");
27395 @end smallexample
27396
27397 @noindent
27398 you do not have to add @option{-largs -lAPI} at the end of the
27399 @command{gnatmake} command.
27400
27401 If any one of the items above is missing you will have to create it
27402 yourself. The following sections explain how to do so using as an
27403 example a fictitious DLL called @file{API.dll}.
27404
27405 @node Creating an Ada Spec for the DLL Services
27406 @subsection Creating an Ada Spec for the DLL Services
27407
27408 @noindent
27409 A DLL typically comes with a C/C++ header file which provides the
27410 definitions of the routines and variables exported by the DLL. The Ada
27411 equivalent of this header file is a package spec that contains definitions
27412 for the imported entities. If the DLL you intend to use does not come with
27413 an Ada spec you have to generate one such spec yourself. For example if
27414 the header file of @file{API.dll} is a file @file{api.h} containing the
27415 following two definitions:
27416
27417 @smallexample
27418 @group
27419 @cartouche
27420 int some_var;
27421 int get (char *);
27422 @end cartouche
27423 @end group
27424 @end smallexample
27425
27426 @noindent
27427 then the equivalent Ada spec could be:
27428
27429 @smallexample @c ada
27430 @group
27431 @cartouche
27432 with Interfaces.C.Strings;
27433 package API is
27434    use Interfaces;
27435
27436    Some_Var : C.int;
27437    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27438
27439 private
27440    pragma Import (C, Get);
27441    pragma Import (DLL, Some_Var);
27442 end API;
27443 @end cartouche
27444 @end group
27445 @end smallexample
27446
27447 @noindent
27448 Note that a variable is
27449 @strong{always imported with a DLL convention}. A function
27450 can have @code{C} or @code{Stdcall} convention.
27451 (@pxref{Windows Calling Conventions}).
27452
27453 @node Creating an Import Library
27454 @subsection Creating an Import Library
27455 @cindex Import library
27456
27457 @menu
27458 * The Definition File::
27459 * GNAT-Style Import Library::
27460 * Microsoft-Style Import Library::
27461 @end menu
27462
27463 @noindent
27464 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27465 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27466 with @file{API.dll} you can skip this section. You can also skip this
27467 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27468 as in this case it is possible to link directly against the
27469 DLL. Otherwise read on.
27470
27471 @node The Definition File
27472 @subsubsection The Definition File
27473 @cindex Definition file
27474 @findex .def
27475
27476 @noindent
27477 As previously mentioned, and unlike Unix systems, the list of symbols
27478 that are exported from a DLL must be provided explicitly in Windows.
27479 The main goal of a definition file is precisely that: list the symbols
27480 exported by a DLL. A definition file (usually a file with a @code{.def}
27481 suffix) has the following structure:
27482
27483 @smallexample
27484 @group
27485 @cartouche
27486 @r{[}LIBRARY @var{name}@r{]}
27487 @r{[}DESCRIPTION @var{string}@r{]}
27488 EXPORTS
27489    @var{symbol1}
27490    @var{symbol2}
27491    @dots{}
27492 @end cartouche
27493 @end group
27494 @end smallexample
27495
27496 @table @code
27497 @item LIBRARY @var{name}
27498 This section, which is optional, gives the name of the DLL.
27499
27500 @item DESCRIPTION @var{string}
27501 This section, which is optional, gives a description string that will be
27502 embedded in the import library.
27503
27504 @item EXPORTS
27505 This section gives the list of exported symbols (procedures, functions or
27506 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27507 section of @file{API.def} looks like:
27508
27509 @smallexample
27510 @group
27511 @cartouche
27512 EXPORTS
27513    some_var
27514    get
27515 @end cartouche
27516 @end group
27517 @end smallexample
27518 @end table
27519
27520 @noindent
27521 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27522 (@pxref{Windows Calling Conventions}) for a Stdcall
27523 calling convention function in the exported symbols list.
27524
27525 @noindent
27526 There can actually be other sections in a definition file, but these
27527 sections are not relevant to the discussion at hand.
27528
27529 @node GNAT-Style Import Library
27530 @subsubsection GNAT-Style Import Library
27531
27532 @noindent
27533 To create a static import library from @file{API.dll} with the GNAT tools
27534 you should proceed as follows:
27535
27536 @enumerate
27537 @item
27538 Create the definition file @file{API.def} (@pxref{The Definition File}).
27539 For that use the @code{dll2def} tool as follows:
27540
27541 @smallexample
27542 $ dll2def API.dll > API.def
27543 @end smallexample
27544
27545 @noindent
27546 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27547 to standard output the list of entry points in the DLL. Note that if
27548 some routines in the DLL have the @code{Stdcall} convention
27549 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27550 suffix then you'll have to edit @file{api.def} to add it, and specify
27551 @option{-k} to @command{gnatdll} when creating the import library.
27552
27553 @noindent
27554 Here are some hints to find the right @code{@@}@var{nn} suffix.
27555
27556 @enumerate
27557 @item
27558 If you have the Microsoft import library (.lib), it is possible to get
27559 the right symbols by using Microsoft @code{dumpbin} tool (see the
27560 corresponding Microsoft documentation for further details).
27561
27562 @smallexample
27563 $ dumpbin /exports api.lib
27564 @end smallexample
27565
27566 @item
27567 If you have a message about a missing symbol at link time the compiler
27568 tells you what symbol is expected. You just have to go back to the
27569 definition file and add the right suffix.
27570 @end enumerate
27571
27572 @item
27573 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27574 (@pxref{Using gnatdll}) as follows:
27575
27576 @smallexample
27577 $ gnatdll -e API.def -d API.dll
27578 @end smallexample
27579
27580 @noindent
27581 @code{gnatdll} takes as input a definition file @file{API.def} and the
27582 name of the DLL containing the services listed in the definition file
27583 @file{API.dll}. The name of the static import library generated is
27584 computed from the name of the definition file as follows: if the
27585 definition file name is @var{xyz}@code{.def}, the import library name will
27586 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27587 @option{-e} could have been removed because the name of the definition
27588 file (before the ``@code{.def}'' suffix) is the same as the name of the
27589 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27590 @end enumerate
27591
27592 @node Microsoft-Style Import Library
27593 @subsubsection Microsoft-Style Import Library
27594
27595 @noindent
27596 With GNAT you can either use a GNAT-style or Microsoft-style import
27597 library. A Microsoft import library is needed only if you plan to make an
27598 Ada DLL available to applications developed with Microsoft
27599 tools (@pxref{Mixed-Language Programming on Windows}).
27600
27601 To create a Microsoft-style import library for @file{API.dll} you
27602 should proceed as follows:
27603
27604 @enumerate
27605 @item
27606 Create the definition file @file{API.def} from the DLL. For this use either
27607 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27608 tool (see the corresponding Microsoft documentation for further details).
27609
27610 @item
27611 Build the actual import library using Microsoft's @code{lib} utility:
27612
27613 @smallexample
27614 $ lib -machine:IX86 -def:API.def -out:API.lib
27615 @end smallexample
27616
27617 @noindent
27618 If you use the above command the definition file @file{API.def} must
27619 contain a line giving the name of the DLL:
27620
27621 @smallexample
27622 LIBRARY      "API"
27623 @end smallexample
27624
27625 @noindent
27626 See the Microsoft documentation for further details about the usage of
27627 @code{lib}.
27628 @end enumerate
27629
27630 @node Building DLLs with GNAT Project files
27631 @section Building DLLs with GNAT Project files
27632 @cindex DLLs, building
27633
27634 @noindent
27635 There is nothing specific to Windows in the build process.
27636 @pxref{Library Projects}.
27637
27638 @noindent
27639 Due to a system limitation, it is not possible under Windows to create threads
27640 when inside the @code{DllMain} routine which is used for auto-initialization
27641 of shared libraries, so it is not possible to have library level tasks in SALs.
27642
27643 @node Building DLLs with GNAT
27644 @section Building DLLs with GNAT
27645 @cindex DLLs, building
27646
27647 @noindent
27648 This section explain how to build DLLs using the GNAT built-in DLL
27649 support. With the following procedure it is straight forward to build
27650 and use DLLs with GNAT.
27651
27652 @enumerate
27653
27654 @item building object files
27655
27656 The first step is to build all objects files that are to be included
27657 into the DLL. This is done by using the standard @command{gnatmake} tool.
27658
27659 @item building the DLL
27660
27661 To build the DLL you must use @command{gcc}'s @option{-shared}
27662 option. It is quite simple to use this method:
27663
27664 @smallexample
27665 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
27666 @end smallexample
27667
27668 It is important to note that in this case all symbols found in the
27669 object files are automatically exported. It is possible to restrict
27670 the set of symbols to export by passing to @command{gcc} a definition
27671 file, @pxref{The Definition File}. For example:
27672
27673 @smallexample
27674 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
27675 @end smallexample
27676
27677 If you use a definition file you must export the elaboration procedures
27678 for every package that required one. Elaboration procedures are named
27679 using the package name followed by "_E".
27680
27681 @item preparing DLL to be used
27682
27683 For the DLL to be used by client programs the bodies must be hidden
27684 from it and the .ali set with read-only attribute. This is very important
27685 otherwise GNAT will recompile all packages and will not actually use
27686 the code in the DLL. For example:
27687
27688 @smallexample
27689 $ mkdir apilib
27690 $ copy *.ads *.ali api.dll apilib
27691 $ attrib +R apilib\*.ali
27692 @end smallexample
27693
27694 @end enumerate
27695
27696 At this point it is possible to use the DLL by directly linking
27697 against it. Note that you must use the GNAT shared runtime when using
27698 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27699 option.
27700
27701 @smallexample
27702 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27703 @end smallexample
27704
27705 @node Building DLLs with gnatdll
27706 @section Building DLLs with gnatdll
27707 @cindex DLLs, building
27708
27709 @menu
27710 * Limitations When Using Ada DLLs from Ada::
27711 * Exporting Ada Entities::
27712 * Ada DLLs and Elaboration::
27713 * Ada DLLs and Finalization::
27714 * Creating a Spec for Ada DLLs::
27715 * Creating the Definition File::
27716 * Using gnatdll::
27717 @end menu
27718
27719 @noindent
27720 Note that it is preferred to use GNAT Project files
27721 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27722 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27723
27724 This section explains how to build DLLs containing Ada code using
27725 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27726 remainder of this section.
27727
27728 The steps required to build an Ada DLL that is to be used by Ada as well as
27729 non-Ada applications are as follows:
27730
27731 @enumerate
27732 @item
27733 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27734 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27735 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27736 skip this step if you plan to use the Ada DLL only from Ada applications.
27737
27738 @item
27739 Your Ada code must export an initialization routine which calls the routine
27740 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27741 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27742 routine exported by the Ada DLL must be invoked by the clients of the DLL
27743 to initialize the DLL.
27744
27745 @item
27746 When useful, the DLL should also export a finalization routine which calls
27747 routine @code{adafinal} generated by @command{gnatbind} to perform the
27748 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27749 The finalization routine exported by the Ada DLL must be invoked by the
27750 clients of the DLL when the DLL services are no further needed.
27751
27752 @item
27753 You must provide a spec for the services exported by the Ada DLL in each
27754 of the programming languages to which you plan to make the DLL available.
27755
27756 @item
27757 You must provide a definition file listing the exported entities
27758 (@pxref{The Definition File}).
27759
27760 @item
27761 Finally you must use @code{gnatdll} to produce the DLL and the import
27762 library (@pxref{Using gnatdll}).
27763 @end enumerate
27764
27765 @noindent
27766 Note that a relocatable DLL stripped using the @code{strip}
27767 binutils tool will not be relocatable anymore. To build a DLL without
27768 debug information pass @code{-largs -s} to @code{gnatdll}. This
27769 restriction does not apply to a DLL built using a Library Project.
27770 @pxref{Library Projects}.
27771
27772 @node Limitations When Using Ada DLLs from Ada
27773 @subsection Limitations When Using Ada DLLs from Ada
27774
27775 @noindent
27776 When using Ada DLLs from Ada applications there is a limitation users
27777 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27778 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27779 each Ada DLL includes the services of the GNAT run time that are necessary
27780 to the Ada code inside the DLL. As a result, when an Ada program uses an
27781 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27782 one in the main program.
27783
27784 It is therefore not possible to exchange GNAT run-time objects between the
27785 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27786 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27787 types, etc.
27788
27789 It is completely safe to exchange plain elementary, array or record types,
27790 Windows object handles, etc.
27791
27792 @node Exporting Ada Entities
27793 @subsection Exporting Ada Entities
27794 @cindex Export table
27795
27796 @noindent
27797 Building a DLL is a way to encapsulate a set of services usable from any
27798 application. As a result, the Ada entities exported by a DLL should be
27799 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27800 any Ada name mangling. As an example here is an Ada package
27801 @code{API}, spec and body, exporting two procedures, a function, and a
27802 variable:
27803
27804 @smallexample @c ada
27805 @group
27806 @cartouche
27807 with Interfaces.C; use Interfaces;
27808 package API is
27809    Count : C.int := 0;
27810    function Factorial (Val : C.int) return C.int;
27811
27812    procedure Initialize_API;
27813    procedure Finalize_API;
27814    --  Initialization & Finalization routines. More in the next section.
27815 private
27816    pragma Export (C, Initialize_API);
27817    pragma Export (C, Finalize_API);
27818    pragma Export (C, Count);
27819    pragma Export (C, Factorial);
27820 end API;
27821 @end cartouche
27822 @end group
27823 @end smallexample
27824
27825 @smallexample @c ada
27826 @group
27827 @cartouche
27828 package body API is
27829    function Factorial (Val : C.int) return C.int is
27830       Fact : C.int := 1;
27831    begin
27832       Count := Count + 1;
27833       for K in 1 .. Val loop
27834          Fact := Fact * K;
27835       end loop;
27836       return Fact;
27837    end Factorial;
27838
27839    procedure Initialize_API is
27840       procedure Adainit;
27841       pragma Import (C, Adainit);
27842    begin
27843       Adainit;
27844    end Initialize_API;
27845
27846    procedure Finalize_API is
27847       procedure Adafinal;
27848       pragma Import (C, Adafinal);
27849    begin
27850       Adafinal;
27851    end Finalize_API;
27852 end API;
27853 @end cartouche
27854 @end group
27855 @end smallexample
27856
27857 @noindent
27858 If the Ada DLL you are building will only be used by Ada applications
27859 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27860 convention. As an example, the previous package could be written as
27861 follows:
27862
27863 @smallexample @c ada
27864 @group
27865 @cartouche
27866 package API is
27867    Count : Integer := 0;
27868    function Factorial (Val : Integer) return Integer;
27869
27870    procedure Initialize_API;
27871    procedure Finalize_API;
27872    --  Initialization and Finalization routines.
27873 end API;
27874 @end cartouche
27875 @end group
27876 @end smallexample
27877
27878 @smallexample @c ada
27879 @group
27880 @cartouche
27881 package body API is
27882    function Factorial (Val : Integer) return Integer is
27883       Fact : Integer := 1;
27884    begin
27885       Count := Count + 1;
27886       for K in 1 .. Val loop
27887          Fact := Fact * K;
27888       end loop;
27889       return Fact;
27890    end Factorial;
27891
27892    @dots{}
27893    --  The remainder of this package body is unchanged.
27894 end API;
27895 @end cartouche
27896 @end group
27897 @end smallexample
27898
27899 @noindent
27900 Note that if you do not export the Ada entities with a @code{C} or
27901 @code{Stdcall} convention you will have to provide the mangled Ada names
27902 in the definition file of the Ada DLL
27903 (@pxref{Creating the Definition File}).
27904
27905 @node Ada DLLs and Elaboration
27906 @subsection Ada DLLs and Elaboration
27907 @cindex DLLs and elaboration
27908
27909 @noindent
27910 The DLL that you are building contains your Ada code as well as all the
27911 routines in the Ada library that are needed by it. The first thing a
27912 user of your DLL must do is elaborate the Ada code
27913 (@pxref{Elaboration Order Handling in GNAT}).
27914
27915 To achieve this you must export an initialization routine
27916 (@code{Initialize_API} in the previous example), which must be invoked
27917 before using any of the DLL services. This elaboration routine must call
27918 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27919 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27920 @code{Initialize_Api} for an example. Note that the GNAT binder is
27921 automatically invoked during the DLL build process by the @code{gnatdll}
27922 tool (@pxref{Using gnatdll}).
27923
27924 When a DLL is loaded, Windows systematically invokes a routine called
27925 @code{DllMain}. It would therefore be possible to call @code{adainit}
27926 directly from @code{DllMain} without having to provide an explicit
27927 initialization routine. Unfortunately, it is not possible to call
27928 @code{adainit} from the @code{DllMain} if your program has library level
27929 tasks because access to the @code{DllMain} entry point is serialized by
27930 the system (that is, only a single thread can execute ``through'' it at a
27931 time), which means that the GNAT run time will deadlock waiting for the
27932 newly created task to complete its initialization.
27933
27934 @node Ada DLLs and Finalization
27935 @subsection Ada DLLs and Finalization
27936 @cindex DLLs and finalization
27937
27938 @noindent
27939 When the services of an Ada DLL are no longer needed, the client code should
27940 invoke the DLL finalization routine, if available. The DLL finalization
27941 routine is in charge of releasing all resources acquired by the DLL. In the
27942 case of the Ada code contained in the DLL, this is achieved by calling
27943 routine @code{adafinal} generated by the GNAT binder
27944 (@pxref{Binding with Non-Ada Main Programs}).
27945 See the body of @code{Finalize_Api} for an
27946 example. As already pointed out the GNAT binder is automatically invoked
27947 during the DLL build process by the @code{gnatdll} tool
27948 (@pxref{Using gnatdll}).
27949
27950 @node Creating a Spec for Ada DLLs
27951 @subsection Creating a Spec for Ada DLLs
27952
27953 @noindent
27954 To use the services exported by the Ada DLL from another programming
27955 language (e.g.@: C), you have to translate the specs of the exported Ada
27956 entities in that language. For instance in the case of @code{API.dll},
27957 the corresponding C header file could look like:
27958
27959 @smallexample
27960 @group
27961 @cartouche
27962 extern int *_imp__count;
27963 #define count (*_imp__count)
27964 int factorial (int);
27965 @end cartouche
27966 @end group
27967 @end smallexample
27968
27969 @noindent
27970 It is important to understand that when building an Ada DLL to be used by
27971 other Ada applications, you need two different specs for the packages
27972 contained in the DLL: one for building the DLL and the other for using
27973 the DLL. This is because the @code{DLL} calling convention is needed to
27974 use a variable defined in a DLL, but when building the DLL, the variable
27975 must have either the @code{Ada} or @code{C} calling convention. As an
27976 example consider a DLL comprising the following package @code{API}:
27977
27978 @smallexample @c ada
27979 @group
27980 @cartouche
27981 package API is
27982    Count : Integer := 0;
27983    @dots{}
27984    --  Remainder of the package omitted.
27985 end API;
27986 @end cartouche
27987 @end group
27988 @end smallexample
27989
27990 @noindent
27991 After producing a DLL containing package @code{API}, the spec that
27992 must be used to import @code{API.Count} from Ada code outside of the
27993 DLL is:
27994
27995 @smallexample @c ada
27996 @group
27997 @cartouche
27998 package API is
27999    Count : Integer;
28000    pragma Import (DLL, Count);
28001 end API;
28002 @end cartouche
28003 @end group
28004 @end smallexample
28005
28006 @node Creating the Definition File
28007 @subsection Creating the Definition File
28008
28009 @noindent
28010 The definition file is the last file needed to build the DLL. It lists
28011 the exported symbols. As an example, the definition file for a DLL
28012 containing only package @code{API} (where all the entities are exported
28013 with a @code{C} calling convention) is:
28014
28015 @smallexample
28016 @group
28017 @cartouche
28018 EXPORTS
28019     count
28020     factorial
28021     finalize_api
28022     initialize_api
28023 @end cartouche
28024 @end group
28025 @end smallexample
28026
28027 @noindent
28028 If the @code{C} calling convention is missing from package @code{API},
28029 then the definition file contains the mangled Ada names of the above
28030 entities, which in this case are:
28031
28032 @smallexample
28033 @group
28034 @cartouche
28035 EXPORTS
28036     api__count
28037     api__factorial
28038     api__finalize_api
28039     api__initialize_api
28040 @end cartouche
28041 @end group
28042 @end smallexample
28043
28044 @node Using gnatdll
28045 @subsection Using @code{gnatdll}
28046 @findex gnatdll
28047
28048 @menu
28049 * gnatdll Example::
28050 * gnatdll behind the Scenes::
28051 * Using dlltool::
28052 @end menu
28053
28054 @noindent
28055 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28056 and non-Ada sources that make up your DLL have been compiled.
28057 @code{gnatdll} is actually in charge of two distinct tasks: build the
28058 static import library for the DLL and the actual DLL. The form of the
28059 @code{gnatdll} command is
28060
28061 @smallexample
28062 @cartouche
28063 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28064 @c Expanding @ovar macro inline (explanation in macro def comments)
28065 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28066 @end cartouche
28067 @end smallexample
28068
28069 @noindent
28070 where @var{list-of-files} is a list of ALI and object files. The object
28071 file list must be the exact list of objects corresponding to the non-Ada
28072 sources whose services are to be included in the DLL. The ALI file list
28073 must be the exact list of ALI files for the corresponding Ada sources
28074 whose services are to be included in the DLL. If @var{list-of-files} is
28075 missing, only the static import library is generated.
28076
28077 @noindent
28078 You may specify any of the following switches to @code{gnatdll}:
28079
28080 @table @code
28081 @c @item -a@ovar{address}
28082 @c Expanding @ovar macro inline (explanation in macro def comments)
28083 @item -a@r{[}@var{address}@r{]}
28084 @cindex @option{-a} (@code{gnatdll})
28085 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28086 specified the default address @var{0x11000000} will be used. By default,
28087 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28088 advise the reader to build relocatable DLL.
28089
28090 @item -b @var{address}
28091 @cindex @option{-b} (@code{gnatdll})
28092 Set the relocatable DLL base address. By default the address is
28093 @code{0x11000000}.
28094
28095 @item -bargs @var{opts}
28096 @cindex @option{-bargs} (@code{gnatdll})
28097 Binder options. Pass @var{opts} to the binder.
28098
28099 @item -d @var{dllfile}
28100 @cindex @option{-d} (@code{gnatdll})
28101 @var{dllfile} is the name of the DLL. This switch must be present for
28102 @code{gnatdll} to do anything. The name of the generated import library is
28103 obtained algorithmically from @var{dllfile} as shown in the following
28104 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28105 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28106 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28107 as shown in the following example:
28108 if @var{dllfile} is @code{xyz.dll}, the definition
28109 file used is @code{xyz.def}.
28110
28111 @item -e @var{deffile}
28112 @cindex @option{-e} (@code{gnatdll})
28113 @var{deffile} is the name of the definition file.
28114
28115 @item -g
28116 @cindex @option{-g} (@code{gnatdll})
28117 Generate debugging information. This information is stored in the object
28118 file and copied from there to the final DLL file by the linker,
28119 where it can be read by the debugger. You must use the
28120 @option{-g} switch if you plan on using the debugger or the symbolic
28121 stack traceback.
28122
28123 @item -h
28124 @cindex @option{-h} (@code{gnatdll})
28125 Help mode. Displays @code{gnatdll} switch usage information.
28126
28127 @item -Idir
28128 @cindex @option{-I} (@code{gnatdll})
28129 Direct @code{gnatdll} to search the @var{dir} directory for source and
28130 object files needed to build the DLL.
28131 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28132
28133 @item -k
28134 @cindex @option{-k} (@code{gnatdll})
28135 Removes the @code{@@}@var{nn} suffix from the import library's exported
28136 names, but keeps them for the link names. You must specify this
28137 option if you want to use a @code{Stdcall} function in a DLL for which
28138 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28139 of the Windows NT DLL for example. This option has no effect when
28140 @option{-n} option is specified.
28141
28142 @item -l @var{file}
28143 @cindex @option{-l} (@code{gnatdll})
28144 The list of ALI and object files used to build the DLL are listed in
28145 @var{file}, instead of being given in the command line. Each line in
28146 @var{file} contains the name of an ALI or object file.
28147
28148 @item -n
28149 @cindex @option{-n} (@code{gnatdll})
28150 No Import. Do not create the import library.
28151
28152 @item -q
28153 @cindex @option{-q} (@code{gnatdll})
28154 Quiet mode. Do not display unnecessary messages.
28155
28156 @item -v
28157 @cindex @option{-v} (@code{gnatdll})
28158 Verbose mode. Display extra information.
28159
28160 @item -largs @var{opts}
28161 @cindex @option{-largs} (@code{gnatdll})
28162 Linker options. Pass @var{opts} to the linker.
28163 @end table
28164
28165 @node gnatdll Example
28166 @subsubsection @code{gnatdll} Example
28167
28168 @noindent
28169 As an example the command to build a relocatable DLL from @file{api.adb}
28170 once @file{api.adb} has been compiled and @file{api.def} created is
28171
28172 @smallexample
28173 $ gnatdll -d api.dll api.ali
28174 @end smallexample
28175
28176 @noindent
28177 The above command creates two files: @file{libapi.dll.a} (the import
28178 library) and @file{api.dll} (the actual DLL). If you want to create
28179 only the DLL, just type:
28180
28181 @smallexample
28182 $ gnatdll -d api.dll -n api.ali
28183 @end smallexample
28184
28185 @noindent
28186 Alternatively if you want to create just the import library, type:
28187
28188 @smallexample
28189 $ gnatdll -d api.dll
28190 @end smallexample
28191
28192 @node gnatdll behind the Scenes
28193 @subsubsection @code{gnatdll} behind the Scenes
28194
28195 @noindent
28196 This section details the steps involved in creating a DLL. @code{gnatdll}
28197 does these steps for you. Unless you are interested in understanding what
28198 goes on behind the scenes, you should skip this section.
28199
28200 We use the previous example of a DLL containing the Ada package @code{API},
28201 to illustrate the steps necessary to build a DLL. The starting point is a
28202 set of objects that will make up the DLL and the corresponding ALI
28203 files. In the case of this example this means that @file{api.o} and
28204 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28205 the following:
28206
28207 @enumerate
28208 @item
28209 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28210 the information necessary to generate relocation information for the
28211 DLL.
28212
28213 @smallexample
28214 @group
28215 $ gnatbind -n api
28216 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28217 @end group
28218 @end smallexample
28219
28220 @noindent
28221 In addition to the base file, the @command{gnatlink} command generates an
28222 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28223 asks @command{gnatlink} to generate the routines @code{DllMain} and
28224 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28225 is loaded into memory.
28226
28227 @item
28228 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28229 export table (@file{api.exp}). The export table contains the relocation
28230 information in a form which can be used during the final link to ensure
28231 that the Windows loader is able to place the DLL anywhere in memory.
28232
28233 @smallexample
28234 @group
28235 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28236           --output-exp api.exp
28237 @end group
28238 @end smallexample
28239
28240 @item
28241 @code{gnatdll} builds the base file using the new export table. Note that
28242 @command{gnatbind} must be called once again since the binder generated file
28243 has been deleted during the previous call to @command{gnatlink}.
28244
28245 @smallexample
28246 @group
28247 $ gnatbind -n api
28248 $ gnatlink api -o api.jnk api.exp -mdll
28249       -Wl,--base-file,api.base
28250 @end group
28251 @end smallexample
28252
28253 @item
28254 @code{gnatdll} builds the new export table using the new base file and
28255 generates the DLL import library @file{libAPI.dll.a}.
28256
28257 @smallexample
28258 @group
28259 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28260           --output-exp api.exp --output-lib libAPI.a
28261 @end group
28262 @end smallexample
28263
28264 @item
28265 Finally @code{gnatdll} builds the relocatable DLL using the final export
28266 table.
28267
28268 @smallexample
28269 @group
28270 $ gnatbind -n api
28271 $ gnatlink api api.exp -o api.dll -mdll
28272 @end group
28273 @end smallexample
28274 @end enumerate
28275
28276 @node Using dlltool
28277 @subsubsection Using @code{dlltool}
28278
28279 @noindent
28280 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28281 DLLs and static import libraries. This section summarizes the most
28282 common @code{dlltool} switches. The form of the @code{dlltool} command
28283 is
28284
28285 @smallexample
28286 @c $ dlltool @ovar{switches}
28287 @c Expanding @ovar macro inline (explanation in macro def comments)
28288 $ dlltool @r{[}@var{switches}@r{]}
28289 @end smallexample
28290
28291 @noindent
28292 @code{dlltool} switches include:
28293
28294 @table @option
28295 @item --base-file @var{basefile}
28296 @cindex @option{--base-file} (@command{dlltool})
28297 Read the base file @var{basefile} generated by the linker. This switch
28298 is used to create a relocatable DLL.
28299
28300 @item --def @var{deffile}
28301 @cindex @option{--def} (@command{dlltool})
28302 Read the definition file.
28303
28304 @item --dllname @var{name}
28305 @cindex @option{--dllname} (@command{dlltool})
28306 Gives the name of the DLL. This switch is used to embed the name of the
28307 DLL in the static import library generated by @code{dlltool} with switch
28308 @option{--output-lib}.
28309
28310 @item -k
28311 @cindex @option{-k} (@command{dlltool})
28312 Kill @code{@@}@var{nn} from exported names
28313 (@pxref{Windows Calling Conventions}
28314 for a discussion about @code{Stdcall}-style symbols.
28315
28316 @item --help
28317 @cindex @option{--help} (@command{dlltool})
28318 Prints the @code{dlltool} switches with a concise description.
28319
28320 @item --output-exp @var{exportfile}
28321 @cindex @option{--output-exp} (@command{dlltool})
28322 Generate an export file @var{exportfile}. The export file contains the
28323 export table (list of symbols in the DLL) and is used to create the DLL.
28324
28325 @item --output-lib @var{libfile}
28326 @cindex @option{--output-lib} (@command{dlltool})
28327 Generate a static import library @var{libfile}.
28328
28329 @item -v
28330 @cindex @option{-v} (@command{dlltool})
28331 Verbose mode.
28332
28333 @item --as @var{assembler-name}
28334 @cindex @option{--as} (@command{dlltool})
28335 Use @var{assembler-name} as the assembler. The default is @code{as}.
28336 @end table
28337
28338 @node GNAT and Windows Resources
28339 @section GNAT and Windows Resources
28340 @cindex Resources, windows
28341
28342 @menu
28343 * Building Resources::
28344 * Compiling Resources::
28345 * Using Resources::
28346 @end menu
28347
28348 @noindent
28349 Resources are an easy way to add Windows specific objects to your
28350 application. The objects that can be added as resources include:
28351
28352 @itemize @bullet
28353 @item
28354 menus
28355
28356 @item
28357 accelerators
28358
28359 @item
28360 dialog boxes
28361
28362 @item
28363 string tables
28364
28365 @item
28366 bitmaps
28367
28368 @item
28369 cursors
28370
28371 @item
28372 icons
28373
28374 @item
28375 fonts
28376 @end itemize
28377
28378 @noindent
28379 This section explains how to build, compile and use resources.
28380
28381 @node Building Resources
28382 @subsection Building Resources
28383 @cindex Resources, building
28384
28385 @noindent
28386 A resource file is an ASCII file. By convention resource files have an
28387 @file{.rc} extension.
28388 The easiest way to build a resource file is to use Microsoft tools
28389 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28390 @code{dlgedit.exe} to build dialogs.
28391 It is always possible to build an @file{.rc} file yourself by writing a
28392 resource script.
28393
28394 It is not our objective to explain how to write a resource file. A
28395 complete description of the resource script language can be found in the
28396 Microsoft documentation.
28397
28398 @node Compiling Resources
28399 @subsection Compiling Resources
28400 @findex rc
28401 @findex windres
28402 @cindex Resources, compiling
28403
28404 @noindent
28405 This section describes how to build a GNAT-compatible (COFF) object file
28406 containing the resources. This is done using the Resource Compiler
28407 @code{windres} as follows:
28408
28409 @smallexample
28410 $ windres -i myres.rc -o myres.o
28411 @end smallexample
28412
28413 @noindent
28414 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28415 file. You can specify an alternate preprocessor (usually named
28416 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28417 parameter. A list of all possible options may be obtained by entering
28418 the command @code{windres} @option{--help}.
28419
28420 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28421 to produce a @file{.res} file (binary resource file). See the
28422 corresponding Microsoft documentation for further details. In this case
28423 you need to use @code{windres} to translate the @file{.res} file to a
28424 GNAT-compatible object file as follows:
28425
28426 @smallexample
28427 $ windres -i myres.res -o myres.o
28428 @end smallexample
28429
28430 @node Using Resources
28431 @subsection Using Resources
28432 @cindex Resources, using
28433
28434 @noindent
28435 To include the resource file in your program just add the
28436 GNAT-compatible object file for the resource(s) to the linker
28437 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28438 option:
28439
28440 @smallexample
28441 $ gnatmake myprog -largs myres.o
28442 @end smallexample
28443
28444 @node Debugging a DLL
28445 @section Debugging a DLL
28446 @cindex DLL debugging
28447
28448 @menu
28449 * Program and DLL Both Built with GCC/GNAT::
28450 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28451 @end menu
28452
28453 @noindent
28454 Debugging a DLL is similar to debugging a standard program. But
28455 we have to deal with two different executable parts: the DLL and the
28456 program that uses it. We have the following four possibilities:
28457
28458 @enumerate 1
28459 @item
28460 The program and the DLL are built with @code{GCC/GNAT}.
28461 @item
28462 The program is built with foreign tools and the DLL is built with
28463 @code{GCC/GNAT}.
28464 @item
28465 The program is built with @code{GCC/GNAT} and the DLL is built with
28466 foreign tools.
28467 @end enumerate
28468
28469 @noindent
28470 In this section we address only cases one and two above.
28471 There is no point in trying to debug
28472 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28473 information in it. To do so you must use a debugger compatible with the
28474 tools suite used to build the DLL.
28475
28476 @node Program and DLL Both Built with GCC/GNAT
28477 @subsection Program and DLL Both Built with GCC/GNAT
28478
28479 @noindent
28480 This is the simplest case. Both the DLL and the program have @code{GDB}
28481 compatible debugging information. It is then possible to break anywhere in
28482 the process. Let's suppose here that the main procedure is named
28483 @code{ada_main} and that in the DLL there is an entry point named
28484 @code{ada_dll}.
28485
28486 @noindent
28487 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28488 program must have been built with the debugging information (see GNAT -g
28489 switch). Here are the step-by-step instructions for debugging it:
28490
28491 @enumerate 1
28492 @item Launch @code{GDB} on the main program.
28493
28494 @smallexample
28495 $ gdb -nw ada_main
28496 @end smallexample
28497
28498 @item Start the program and stop at the beginning of the main procedure
28499
28500 @smallexample
28501 (gdb) start
28502 @end smallexample
28503
28504 @noindent
28505 This step is required to be able to set a breakpoint inside the DLL. As long
28506 as the program is not run, the DLL is not loaded. This has the
28507 consequence that the DLL debugging information is also not loaded, so it is not
28508 possible to set a breakpoint in the DLL.
28509
28510 @item Set a breakpoint inside the DLL
28511
28512 @smallexample
28513 (gdb) break ada_dll
28514 (gdb) cont
28515 @end smallexample
28516
28517 @end enumerate
28518
28519 @noindent
28520 At this stage a breakpoint is set inside the DLL. From there on
28521 you can use the standard approach to debug the whole program
28522 (@pxref{Running and Debugging Ada Programs}).
28523
28524 @ignore
28525 @c This used to work, probably because the DLLs were non-relocatable
28526 @c keep this section around until the problem is sorted out.
28527
28528 To break on the @code{DllMain} routine it is not possible to follow
28529 the procedure above. At the time the program stop on @code{ada_main}
28530 the @code{DllMain} routine as already been called. Either you can use
28531 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28532
28533 @enumerate 1
28534 @item Launch @code{GDB} on the main program.
28535
28536 @smallexample
28537 $ gdb ada_main
28538 @end smallexample
28539
28540 @item Load DLL symbols
28541
28542 @smallexample
28543 (gdb) add-sym api.dll
28544 @end smallexample
28545
28546 @item Set a breakpoint inside the DLL
28547
28548 @smallexample
28549 (gdb) break ada_dll.adb:45
28550 @end smallexample
28551
28552 Note that at this point it is not possible to break using the routine symbol
28553 directly as the program is not yet running. The solution is to break
28554 on the proper line (break in @file{ada_dll.adb} line 45).
28555
28556 @item Start the program
28557
28558 @smallexample
28559 (gdb) run
28560 @end smallexample
28561
28562 @end enumerate
28563 @end ignore
28564
28565 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28566 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28567
28568 @menu
28569 * Debugging the DLL Directly::
28570 * Attaching to a Running Process::
28571 @end menu
28572
28573 @noindent
28574 In this case things are slightly more complex because it is not possible to
28575 start the main program and then break at the beginning to load the DLL and the
28576 associated DLL debugging information. It is not possible to break at the
28577 beginning of the program because there is no @code{GDB} debugging information,
28578 and therefore there is no direct way of getting initial control. This
28579 section addresses this issue by describing some methods that can be used
28580 to break somewhere in the DLL to debug it.
28581
28582 @noindent
28583 First suppose that the main procedure is named @code{main} (this is for
28584 example some C code built with Microsoft Visual C) and that there is a
28585 DLL named @code{test.dll} containing an Ada entry point named
28586 @code{ada_dll}.
28587
28588 @noindent
28589 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28590 been built with debugging information (see GNAT -g option).
28591
28592 @node Debugging the DLL Directly
28593 @subsubsection Debugging the DLL Directly
28594
28595 @enumerate 1
28596 @item
28597 Find out the executable starting address
28598
28599 @smallexample
28600 $ objdump --file-header main.exe
28601 @end smallexample
28602
28603 The starting address is reported on the last line. For example:
28604
28605 @smallexample
28606 main.exe:     file format pei-i386
28607 architecture: i386, flags 0x0000010a:
28608 EXEC_P, HAS_DEBUG, D_PAGED
28609 start address 0x00401010
28610 @end smallexample
28611
28612 @item
28613 Launch the debugger on the executable.
28614
28615 @smallexample
28616 $ gdb main.exe
28617 @end smallexample
28618
28619 @item
28620 Set a breakpoint at the starting address, and launch the program.
28621
28622 @smallexample
28623 $ (gdb) break *0x00401010
28624 $ (gdb) run
28625 @end smallexample
28626
28627 The program will stop at the given address.
28628
28629 @item
28630 Set a breakpoint on a DLL subroutine.
28631
28632 @smallexample
28633 (gdb) break ada_dll.adb:45
28634 @end smallexample
28635
28636 Or if you want to break using a symbol on the DLL, you need first to
28637 select the Ada language (language used by the DLL).
28638
28639 @smallexample
28640 (gdb) set language ada
28641 (gdb) break ada_dll
28642 @end smallexample
28643
28644 @item
28645 Continue the program.
28646
28647 @smallexample
28648 (gdb) cont
28649 @end smallexample
28650
28651 @noindent
28652 This will run the program until it reaches the breakpoint that has been
28653 set. From that point you can use the standard way to debug a program
28654 as described in (@pxref{Running and Debugging Ada Programs}).
28655
28656 @end enumerate
28657
28658 @noindent
28659 It is also possible to debug the DLL by attaching to a running process.
28660
28661 @node Attaching to a Running Process
28662 @subsubsection Attaching to a Running Process
28663 @cindex DLL debugging, attach to process
28664
28665 @noindent
28666 With @code{GDB} it is always possible to debug a running process by
28667 attaching to it. It is possible to debug a DLL this way. The limitation
28668 of this approach is that the DLL must run long enough to perform the
28669 attach operation. It may be useful for instance to insert a time wasting
28670 loop in the code of the DLL to meet this criterion.
28671
28672 @enumerate 1
28673
28674 @item Launch the main program @file{main.exe}.
28675
28676 @smallexample
28677 $ main
28678 @end smallexample
28679
28680 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28681 that the process PID for @file{main.exe} is 208.
28682
28683 @item Launch gdb.
28684
28685 @smallexample
28686 $ gdb
28687 @end smallexample
28688
28689 @item Attach to the running process to be debugged.
28690
28691 @smallexample
28692 (gdb) attach 208
28693 @end smallexample
28694
28695 @item Load the process debugging information.
28696
28697 @smallexample
28698 (gdb) symbol-file main.exe
28699 @end smallexample
28700
28701 @item Break somewhere in the DLL.
28702
28703 @smallexample
28704 (gdb) break ada_dll
28705 @end smallexample
28706
28707 @item Continue process execution.
28708
28709 @smallexample
28710 (gdb) cont
28711 @end smallexample
28712
28713 @end enumerate
28714
28715 @noindent
28716 This last step will resume the process execution, and stop at
28717 the breakpoint we have set. From there you can use the standard
28718 approach to debug a program as described in
28719 (@pxref{Running and Debugging Ada Programs}).
28720
28721 @node Setting Stack Size from gnatlink
28722 @section Setting Stack Size from @command{gnatlink}
28723
28724 @noindent
28725 It is possible to specify the program stack size at link time. On modern
28726 versions of Windows, starting with XP, this is mostly useful to set the size of
28727 the main stack (environment task). The other task stacks are set with pragma
28728 Storage_Size or with the @command{gnatbind -d} command.
28729
28730 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28731 reserve size of individual tasks, the link-time stack size applies to all
28732 tasks, and pragma Storage_Size has no effect.
28733 In particular, Stack Overflow checks are made against this
28734 link-time specified size.
28735
28736 This setting can be done with
28737 @command{gnatlink} using either:
28738
28739 @itemize @bullet
28740
28741 @item using @option{-Xlinker} linker option
28742
28743 @smallexample
28744 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28745 @end smallexample
28746
28747 This sets the stack reserve size to 0x10000 bytes and the stack commit
28748 size to 0x1000 bytes.
28749
28750 @item using @option{-Wl} linker option
28751
28752 @smallexample
28753 $ gnatlink hello -Wl,--stack=0x1000000
28754 @end smallexample
28755
28756 This sets the stack reserve size to 0x1000000 bytes. Note that with
28757 @option{-Wl} option it is not possible to set the stack commit size
28758 because the coma is a separator for this option.
28759
28760 @end itemize
28761
28762 @node Setting Heap Size from gnatlink
28763 @section Setting Heap Size from @command{gnatlink}
28764
28765 @noindent
28766 Under Windows systems, it is possible to specify the program heap size from
28767 @command{gnatlink} using either:
28768
28769 @itemize @bullet
28770
28771 @item using @option{-Xlinker} linker option
28772
28773 @smallexample
28774 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28775 @end smallexample
28776
28777 This sets the heap reserve size to 0x10000 bytes and the heap commit
28778 size to 0x1000 bytes.
28779
28780 @item using @option{-Wl} linker option
28781
28782 @smallexample
28783 $ gnatlink hello -Wl,--heap=0x1000000
28784 @end smallexample
28785
28786 This sets the heap reserve size to 0x1000000 bytes. Note that with
28787 @option{-Wl} option it is not possible to set the heap commit size
28788 because the coma is a separator for this option.
28789
28790 @end itemize
28791
28792 @end ifset
28793
28794 @c **********************************
28795 @c * GNU Free Documentation License *
28796 @c **********************************
28797 @include fdl.texi
28798 @c GNU Free Documentation License
28799
28800 @node Index,,GNU Free Documentation License, Top
28801 @unnumbered Index
28802
28803 @printindex cp
28804
28805 @contents
28806 @c Put table of contents at end, otherwise it precedes the "title page" in
28807 @c the .txt version
28808 @c Edit the pdf file to move the contents to the beginning, after the title
28809 @c page
28810
28811 @bye